org.jtwig.JtwigModel - java examples

Here are the examples of the java api org.jtwig.JtwigModel taken from open source projects. By voting up you can indicate which examples are most useful and appropriate.

112 Examples 7

19 View Complete Implementation : RelationalOperatorsTest.java
Copyright Apache License 2.0
Author : jtwig
@Test
public void greaterOrEqualFalse() throws Exception {
    JtwigModel model = new JtwigModel();
    model.with("var1", "b").with("var2", "a");
    String result = JtwigTemplate.inlineTemplate("{{ var1 >= var2 }}").render(model);
    replacedertThat(result, is(equalTo("true")));
}

19 View Complete Implementation : TernaryOperatorTest.java
Copyright Apache License 2.0
Author : jtwig
@Test
public void testFalse() throws Exception {
    JtwigModel model = new JtwigModel();
    String result = JtwigTemplate.inlineTemplate("{{ false ? 1 : 2 }}").render(model);
    replacedertThat(result, is(equalTo("2")));
}

19 View Complete Implementation : IsTest.java
Copyright Apache License 2.0
Author : jtwig
@Test
public void isFunctionFalse() throws Exception {
    JtwigModel model = new JtwigModel();
    String result = JtwigTemplate.inlineTemplate("{% if (blah is function) %}Hi{% else %}blue{% endif %}").render(model);
    replacedertThat(result, is(equalTo("blue")));
}

19 View Complete Implementation : RelationalOperatorsTest.java
Copyright Apache License 2.0
Author : jtwig
@Test
public void differentTypesWithSameStringValueAreEqual2() throws Exception {
    JtwigModel model = new JtwigModel();
    model.with("var1", 'a').with("var2", "a");
    String result = JtwigTemplate.inlineTemplate("{{ var1 == var2 }}").render(model);
    replacedertThat(result, is(equalTo("true")));
}

19 View Complete Implementation : IsTest.java
Copyright Apache License 2.0
Author : jtwig
@Test
public void isOperatorConstantFunction() throws Exception {
    JtwigModel model = new JtwigModel();
    String result = JtwigTemplate.inlineTemplate("{% if ('one' is constant('org.jtwig.integration.expression.IsTest.HELLO')) %}Hi{% endif %}").render(model);
    replacedertThat(result, is(equalTo("Hi")));
}

19 View Complete Implementation : JtwigModelValueContext.java
Copyright Apache License 2.0
Author : jtwig
public clreplaced JtwigModelValueContext implements ValueContext {

    private final JtwigModel jtwigModel;

    public JtwigModelValueContext(JtwigModel jtwigModel) {
        this.jtwigModel = jtwigModel;
    }

    @Override
    public Object resolve(String key) {
        Optional<Value> result = jtwigModel.get(key);
        if (result.isPresent()) {
            return result.get().getValue();
        } else {
            return Undefined.UNDEFINED;
        }
    }

    @Override
    public ValueContext with(String key, Object value) {
        throw new IllegalArgumentException("JtwigModelValueContext cannot implement such write operation as it is readonly. Tip: Wrap it inside a modifiable value context");
    }
}

19 View Complete Implementation : RelationalOperatorsTest.java
Copyright Apache License 2.0
Author : jtwig
@Test
public void lessOrEqualFalse() throws Exception {
    JtwigModel model = new JtwigModel();
    model.with("var1", "b").with("var2", "a");
    String result = JtwigTemplate.inlineTemplate("{{ var1 <= var2 }}").render(model);
    replacedertThat(result, is(equalTo("false")));
}

19 View Complete Implementation : ProfileRoutes.java
Copyright The Unlicense
Author : grishka
public static Object following(Request req, Response resp) throws SQLException {
    String username = req.params(":username");
    User user = UserStorage.getByUsername(username);
    if (user != null) {
        JtwigModel model = JtwigModel.newModel();
        model.with("friendList", UserStorage.getNonMutualFollowers(user.id, false, true)).with("owner", user).with("following", true).with("tab", 2);
        return Utils.renderTemplate(req, "friends", model);
    }
    resp.status(404);
    return Utils.wrapError(req, "user_not_found");
}

19 View Complete Implementation : Issue075Test.java
Copyright Apache License 2.0
Author : jtwig
@Test
public void issue75IsNull() throws Exception {
    JtwigModel model = new JtwigModel();
    model.with("a", new NullPointer());
    String result = JtwigTemplate.inlineTemplate("{% if (a.value is null) %}A{% else %}B{% endif %}").render(model);
    replacedertThat(result, containsString("A"));
}

19 View Complete Implementation : ProfileRoutes.java
Copyright The Unlicense
Author : grishka
public static Object followers(Request req, Response resp) throws SQLException {
    String username = req.params(":username");
    User user = UserStorage.getByUsername(username);
    if (user != null) {
        JtwigModel model = JtwigModel.newModel();
        model.with("friendList", UserStorage.getNonMutualFollowers(user.id, true, true)).with("owner", user).with("followers", true).with("tab", 1);
        return Utils.renderTemplate(req, "friends", model);
    }
    resp.status(404);
    return Utils.wrapError(req, "user_not_found");
}

19 View Complete Implementation : IsTest.java
Copyright Apache License 2.0
Author : jtwig
@Test
public void isFunctionTrue() throws Exception {
    JtwigModel model = new JtwigModel();
    String result = JtwigTemplate.inlineTemplate("{% if (defined is function) %}Hi{% else %}blue{% endif %}").render(model);
    replacedertThat(result, is(equalTo("Hi")));
}

19 View Complete Implementation : IsTest.java
Copyright Apache License 2.0
Author : jtwig
@Test
public void isIterableFunction() throws Exception {
    JtwigModel model = new JtwigModel();
    String result = JtwigTemplate.inlineTemplate("{% if ([] is iterable) %}Hi{% endif %}").render(model);
    replacedertThat(result, is(equalTo("Hi")));
}

19 View Complete Implementation : Utils.java
Copyright The Unlicense
Author : grishka
public static String renderTemplate(Request req, String name, JtwigModel model) {
    addGlobalParamsToTemplate(req, model);
    JtwigTemplate template = JtwigTemplate.clreplacedpathTemplate("templates/desktop/" + name + ".twig", Main.jtwigEnv);
    return template.render(model);
}

19 View Complete Implementation : RelationalOperatorsTest.java
Copyright Apache License 2.0
Author : jtwig
@Test
public void lessFalse() throws Exception {
    JtwigModel model = new JtwigModel();
    model.with("var1", "b").with("var2", "a");
    String result = JtwigTemplate.inlineTemplate("{{ var1 < var2 }}").render(model);
    replacedertThat(result, is(equalTo("false")));
}

19 View Complete Implementation : ProfileRoutes.java
Copyright The Unlicense
Author : grishka
public static Object incomingFriendRequests(Request req, Response resp, Account self) throws SQLException {
    String username = req.params(":username");
    if (!self.user.username.equalsIgnoreCase(username)) {
        resp.redirect(Utils.back(req));
        return "";
    }
    List<FriendRequest> requests = UserStorage.getIncomingFriendRequestsForUser(self.user.id, 0, 100);
    JtwigModel model = JtwigModel.newModel();
    model.with("friendRequests", requests);
    return Utils.renderTemplate(req, "friend_requests", model);
}

19 View Complete Implementation : RelationalOperatorsTest.java
Copyright Apache License 2.0
Author : jtwig
@Test
public void diffOperatorWhenTrue() throws Exception {
    JtwigModel model = new JtwigModel();
    String result = JtwigTemplate.inlineTemplate("{% if ('one' != 'two') %}Hi{% endif %}").render(model);
    replacedertThat(result, is(equalTo("Hi")));
}

19 View Complete Implementation : IsTest.java
Copyright Apache License 2.0
Author : jtwig
@Test
public void isOddFunction() throws Exception {
    JtwigModel model = new JtwigModel();
    String result = JtwigTemplate.inlineTemplate("{% if (1 is odd) %}Hi{% endif %}").render(model);
    replacedertThat(result, is(equalTo("Hi")));
}

19 View Complete Implementation : RelationalOperatorsTest.java
Copyright Apache License 2.0
Author : jtwig
@Test
public void lessTrue() throws Exception {
    JtwigModel model = new JtwigModel();
    model.with("var1", 'a').with("var2", "b");
    String result = JtwigTemplate.inlineTemplate("{{ var1 < var2 }}").render(model);
    replacedertThat(result, is(equalTo("true")));
}

19 View Complete Implementation : ActivityPubRoutes.java
Copyright The Unlicense
Author : grishka
public static Object externalInteraction(Request req, Response resp, Account self) {
    // ?type=reblog
    // ?type=favourite
    // ?type=reply
    // user/remote_follow
    String ref = req.headers("referer");
    ActivityPubObject remoteObj;
    try {
        remoteObj = ActivityPub.fetchRemoteObject(req.queryParams("uri"));
    } catch (IOException | JSONException x) {
        return x.getMessage();
    }
    if (remoteObj instanceof ForeignUser) {
        try {
            ForeignUser foreignUser = (ForeignUser) remoteObj;
            // System.out.println(foreignUser);
            UserStorage.putOrUpdateForeignUser(foreignUser);
            FriendshipStatus status = UserStorage.getFriendshipStatus(self.user.id, foreignUser.id);
            if (status == FriendshipStatus.REQUEST_SENT) {
                return Utils.wrapError(req, "err_friend_req_already_sent");
            } else if (status == FriendshipStatus.FOLLOWING) {
                return Utils.wrapError(req, "err_already_following");
            } else if (status == FriendshipStatus.FRIENDS) {
                return Utils.wrapError(req, "err_already_friends");
            }
            JtwigModel model = JtwigModel.newModel().with("user", foreignUser);
            return Utils.renderTemplate(req, "remote_follow", model);
        } catch (Exception x) {
            x.printStackTrace();
            return x.toString();
        }
    }
    return "Referer: " + ref + "<hr/>URL: " + req.queryParams("uri") + "<hr/>Object:<br/><pre>" + remoteObj.toString().replace("<", "<") + "</pre>";
}

19 View Complete Implementation : VariableNestedAccessTest.java
Copyright Apache License 2.0
Author : jtwig
@Test
public void test() {
    String template = "{{ " + testCase.getExpression() + " }}";
    System.out.println(testCase + ":");
    System.out.println(template);
    JtwigModel model = JtwigModel.newModel().with("map", testmap).with("list", teslist).with("object", testobject);
    String result = JtwigTemplate.inlineTemplate(template).render(model);
    replacedertThat(result, is(String.valueOf(EXPECTED_VALUE)));
}

19 View Complete Implementation : IsTest.java
Copyright Apache License 2.0
Author : jtwig
@Test
public void isDefinedFunctionWithStrictMode() throws Exception {
    JtwigModel model = new JtwigModel();
    String result = JtwigTemplate.inlineTemplate("{% if (variable is not defined) %}Hi{% else %}blue{% endif %}", configuration().render().withStrictMode(true).and().build()).render(model);
    replacedertThat(result, is(equalTo("Hi")));
}

19 View Complete Implementation : IsTest.java
Copyright Apache License 2.0
Author : jtwig
@Test
public void isEvenFunction() throws Exception {
    JtwigModel model = new JtwigModel();
    String result = JtwigTemplate.inlineTemplate("{% if (1 is not even) %}Hi{% endif %}").render(model);
    replacedertThat(result, is(equalTo("Hi")));
}

19 View Complete Implementation : PostRoutes.java
Copyright The Unlicense
Author : grishka
public static Object feed(Request req, Response resp, Account self) throws SQLException {
    int userID = self.user.id;
    List<NewsfeedEntry> feed = PostStorage.getFeed(userID);
    for (NewsfeedEntry e : feed) {
        if (e instanceof PostNewsfeedEntry) {
            PostNewsfeedEntry pe = (PostNewsfeedEntry) e;
            if (pe.post != null)
                pe.post.replies = PostStorage.getRepliesForFeed(e.objectID);
            else
                System.err.println("No post: " + pe);
        }
    }
    JtwigModel model = JtwigModel.newModel().with("replacedle", Utils.lang(req).get("feed")).with("feed", feed);
    return Utils.renderTemplate(req, "feed", model);
}

19 View Complete Implementation : IsTest.java
Copyright Apache License 2.0
Author : jtwig
@Test
public void isDefinedFunction() throws Exception {
    JtwigModel model = new JtwigModel();
    String result = JtwigTemplate.inlineTemplate("{% if (variable is not defined) %}Hi{% endif %}").render(model);
    replacedertThat(result, is(equalTo("Hi")));
}

19 View Complete Implementation : SessionRoutes.java
Copyright The Unlicense
Author : grishka
public static Object login(Request req, Response resp) throws SQLException {
    SessionInfo info = Utils.sessionInfo(req);
    if (info != null && info.account != null) {
        resp.redirect("/feed");
        return "";
    }
    JtwigModel model = JtwigModel.newModel();
    if (req.requestMethod().equalsIgnoreCase("post")) {
        Account acc = SessionStorage.getAccountForUsernameAndPreplacedword(req.queryParams("username"), req.queryParams("preplacedword"));
        if (acc != null) {
            setupSessionWithAccount(req, resp, acc);
            String to = req.queryParams("to");
            if (StringUtils.isNotEmpty(to))
                resp.redirect(to);
            else
                resp.redirect("/feed");
            return "";
        }
        model.with("message", Utils.lang(req).get("login_incorrect"));
    } else if (StringUtils.isNotEmpty(req.queryParams("to"))) {
        model.with("message", Utils.lang(req).get("login_needed"));
    }
    model.with("additionalParams", req.queryString());
    return Utils.renderTemplate(req, "login", model);
}

19 View Complete Implementation : IsTest.java
Copyright Apache License 2.0
Author : jtwig
@Test
public void isNotOddFunction() throws Exception {
    JtwigModel model = new JtwigModel();
    String result = JtwigTemplate.inlineTemplate("{% if (1 is not odd) %}Hi{% endif %}").render(model);
    replacedertThat(result, is(equalTo("")));
}

19 View Complete Implementation : IsTest.java
Copyright Apache License 2.0
Author : jtwig
@Test
public void isIterableArrayFunction() throws Exception {
    JtwigModel model = new JtwigModel();
    model.with("value", new Object[0]);
    String result = JtwigTemplate.inlineTemplate("{% if (value is iterable) %}Hi{% endif %}").render(model);
    replacedertThat(result, is(equalTo("Hi")));
}

19 View Complete Implementation : SettingsRoutes.java
Copyright The Unlicense
Author : grishka
public static Object settings(Request req, Response resp, Account self) throws SQLException {
    JtwigModel model = JtwigModel.newModel();
    model.with("invitations", UserStorage.getInvites(self.id, true));
    model.with("languages", Lang.list).with("selectedLang", Utils.lang(req));
    Session s = req.session();
    if (s.attribute("settings.nameMessage") != null) {
        model.with("nameMessage", s.attribute("settings.nameMessage"));
        s.removeAttribute("settings.nameMessage");
    }
    if (s.attribute("settings.preplacedwordMessage") != null) {
        model.with("preplacedwordMessage", s.attribute("settings.preplacedwordMessage"));
        s.removeAttribute("settings.preplacedwordMessage");
    }
    if (s.attribute("settings.inviteMessage") != null) {
        model.with("inviteMessage", s.attribute("settings.inviteMessage"));
        s.removeAttribute("settings.inviteMessage");
    }
    if (s.attribute("settings.profilePicMessage") != null) {
        model.with("profilePicMessage", s.attribute("settings.profilePicMessage"));
        s.removeAttribute("settings.profilePicMessage");
    }
    return Utils.renderTemplate(req, "settings", model);
}

19 View Complete Implementation : RelationalOperatorsTest.java
Copyright Apache License 2.0
Author : jtwig
@Test
public void diffOperatorWhenFalse() throws Exception {
    JtwigModel model = new JtwigModel();
    String result = JtwigTemplate.inlineTemplate("{% if ('one' != 'one') %}Hi{% endif %}").render(model);
    replacedertThat(result, is(equalTo("")));
}

19 View Complete Implementation : ProfileRoutes.java
Copyright The Unlicense
Author : grishka
public static Object friends(Request req, Response resp) throws SQLException {
    String username = req.params(":username");
    User user = UserStorage.getByUsername(username);
    if (user != null) {
        JtwigModel model = JtwigModel.newModel();
        model.with("friendList", UserStorage.getFriendListForUser(user.id)).with("owner", user).with("tab", 0);
        return Utils.renderTemplate(req, "friends", model);
    }
    resp.status(404);
    return Utils.wrapError(req, "user_not_found");
}

19 View Complete Implementation : RelationalOperatorsTest.java
Copyright Apache License 2.0
Author : jtwig
@Test
public void greaterFalse() throws Exception {
    JtwigModel model = new JtwigModel();
    model.with("var1", "b").with("var2", "a");
    String result = JtwigTemplate.inlineTemplate("{{ var1 > var2 }}").render(model);
    replacedertThat(result, is(equalTo("true")));
}

19 View Complete Implementation : Utils.java
Copyright The Unlicense
Author : grishka
public static void addGlobalParamsToTemplate(Request req, JtwigModel model) {
    JSONObject jsConfig = new JSONObject();
    if (req.session(false) != null) {
        SessionInfo info = req.session().attribute("info");
        if (info == null) {
            info = new SessionInfo();
            req.session().attribute("info", info);
        }
        Account account = info.account;
        if (account != null) {
            model.with("currentUser", account.user);
            model.with("csrf", info.csrfToken);
            jsConfig.put("csrf", info.csrfToken);
            jsConfig.put("uid", info.account.user.id);
            try {
                UserNotifications notifications = UserStorage.getNotificationsForUser(account.user.id);
                model.with("userNotifications", notifications);
            } catch (SQLException x) {
                throw new RuntimeException(x);
            }
        }
    }
    TimeZone tz = timeZoneForRequest(req);
    jsConfig.put("timeZone", tz != null ? tz.getID() : null);
    model.with("locale", localeForRequest(req)).with("timeZone", tz != null ? tz : TimeZone.getDefault()).with("jsConfig", jsConfig.toString());
}

19 View Complete Implementation : RelationalOperatorsTest.java
Copyright Apache License 2.0
Author : jtwig
@Test
public void greaterOrEqualTrue() throws Exception {
    JtwigModel model = new JtwigModel();
    model.with("var1", 'a').with("var2", "b");
    String result = JtwigTemplate.inlineTemplate("{{ var1 >= var2 }}").render(model);
    replacedertThat(result, is(equalTo("false")));
}

19 View Complete Implementation : Main.java
Copyright The Unlicense
Author : grishka
private static Object indexPage(Request req, Response resp) {
    SessionInfo info = req.session().attribute("info");
    if (info != null && info.account != null) {
        resp.redirect("/feed");
        return "";
    }
    JtwigModel model = JtwigModel.newModel().with("replacedle", "Smithereen");
    return Utils.renderTemplate(req, "index", model);
}

19 View Complete Implementation : RelationalOperatorsTest.java
Copyright Apache License 2.0
Author : jtwig
@Test
public void lessOrEqualTrue() throws Exception {
    JtwigModel model = new JtwigModel();
    model.with("var1", 'a').with("var2", "b");
    String result = JtwigTemplate.inlineTemplate("{{ var1 <= var2 }}").render(model);
    replacedertThat(result, is(equalTo("true")));
}

19 View Complete Implementation : ParentFunctionTest.java
Copyright Apache License 2.0
Author : jtwig
public clreplaced ParentFunctionTest {

    private JtwigModel model;

    private EnvironmentConfiguration configTemplate;

    @Before
    public void setupModel() {
        model = JtwigModel.newModel().with("aVar", "A").with("bVar", "B").with("cVar", "C").with("zVar", "Z");
    }

    @Before
    public void setupConfiguration() {
        TypedResourceLoader templateResourceA = new TypedResourceLoader(MEMORY, InMemoryResourceLoader.builder().withResource("a", "x{% block a %}{{ aVar }}{% endblock %}x{% block z %}{% endblock %}").build());
        TypedResourceLoader templateResourceB = new TypedResourceLoader(MEMORY, InMemoryResourceLoader.builder().withResource("b", "{% extends 'memory:a' %}" + "{% block a %}{{ bVar }}{{ parent() }}B{% endblock %}").build());
        TypedResourceLoader templateResourceC = new TypedResourceLoader(MEMORY, InMemoryResourceLoader.builder().withResource("c", "{% extends 'memory:b' %}" + "{% block a %}C{{ parent() }}{{ cVar }}{{ parent() }}C{% endblock %}").build());
        TypedResourceLoader templateResourceWithBlockFunction = new TypedResourceLoader(MEMORY, InMemoryResourceLoader.builder().withResource("withblockfn", "<replacedle>{% block replacedle %}replacedle{% endblock %}</replacedle>" + "{% block body %}<h1>{{ block('replacedle') }}{% endblock %}</h1>").build());
        configTemplate = configuration().resources().resourceLoaders().add(templateResourceA).add(templateResourceB).add(templateResourceC).add(templateResourceWithBlockFunction).and().and().build();
    }

    private void testWith(String template, String expected) {
        String result = JtwigTemplate.inlineTemplate(template, configTemplate).render(model);
        replacedertThat(result, is(expected));
    }

    @Test
    public void inheritsParentBlock() {
        testWith("{% extends 'memory:a' %}" + "{% block a %}{{ bVar }}{{ parent() }}{% endblock %}", "xBAx");
    }

    @Test
    public void inheritsParentBlockWithSuffix() {
        testWith("{% extends 'memory:a' %}" + "{% block a %}{{ bVar }}{{ parent() }}B{% endblock %}", "xBABx");
    }

    @Test(expected = ParentFunctionWithoutExtending.clreplaced)
    public void errorWhenCallingParentWithoutExtending() {
        testWith("{% block a %}B{{ parent() }}{% endblock %}", "");
    }

    @Test(expected = ParentFunctionOutsideBlockException.clreplaced)
    public void errorWhenCallingParentOutsideOfBlock() {
        testWith("z{{ parent() }}z", "");
    }

    @Test
    public void inheritsParentBlockTwiceIfRequested() {
        testWith("{% extends 'memory:a' %}" + "{% block a %}{{ parent() }}B{{ parent() }}{% endblock %}", "xABAx");
    }

    @Test
    public void inheritsParentBlockThroughTwoLevels() {
        testWith("{% extends 'memory:b' %}" + "{% block a %}C{{ parent() }}C{% endblock %}", "xCBABCx");
    }

    @Test
    public void inheritsParentBlockTwiceThroughTwoLevels() {
        testWith("{% extends 'memory:b' %}" + "{% block a %}C{{ parent() }}C{{ parent() }}C{% endblock %}", "xCBABCBABCx");
    }

    @Test
    public void inheritsParentBlockThroughThreeLevels() {
        testWith("{% extends 'memory:c' %}" + "{% block a %}D{{ parent() }}D{% endblock %}", "xDCBABCBABCDx");
    }

    @Test
    public void inheritsParentBlockTwiceThroughThreeLevels() {
        testWith("{% extends 'memory:c' %}" + "{% block a %}D{{ parent() }}D{{ parent() }}D{% endblock %}", "xDCBABCBABCDCBABCBABCDx");
    }

    @Test
    public void blockFunctionInterpretsInheritedBlocks() {
        testWith("{% extends 'memory:a' %}" + "{% block a %}{{ parent() }}B{{ parent() }}{% endblock %}" + "{% block z %}Z{{ block('a')}}Z{% endblock %}", "xABAxZABAZ");
    }

    @Test
    public void blockFunctionInterpretsInheritedBlocksIndependentOfOrder() {
        testWith("{% extends 'memory:a' %}" + "{% block z %}Z{{ block('a')}}Z{% endblock %}" + "{% block a %}{{ parent() }}B{{ parent() }}{% endblock %}", "xABAxZABAZ");
    }

    @Test
    public void blockFunctionInterpretsInheritedBlocksThroughMultipleLevels() {
        testWith("{% extends 'memory:b' %}" + "{% block a %}C{{ parent() }}C{% endblock %}" + "{% block z %}Z{{ block('a')}}Z{% endblock %}", "xCBABCxZCBABCZ");
    }

    @Test
    public void blockFunctionInParentTemplateReferencesCurrentBlock() {
        testWith("{% extends 'memory:withblockfn' %}" + "{% block replacedle %}Subreplacedle - {{ parent() }}{% endblock %}", "<replacedle>Subreplacedle - replacedle</replacedle><h1>Subreplacedle - replacedle</h1>");
    }
}

19 View Complete Implementation : RelationalOperatorsTest.java
Copyright Apache License 2.0
Author : jtwig
@Test
public void greaterTrue() throws Exception {
    JtwigModel model = new JtwigModel();
    model.with("var1", 'a').with("var2", "b");
    String result = JtwigTemplate.inlineTemplate("{{ var1 > var2 }}").render(model);
    replacedertThat(result, is(equalTo("false")));
}

19 View Complete Implementation : ProfileRoutes.java
Copyright The Unlicense
Author : grishka
public static Object profile(Request req, Response resp) throws SQLException {
    SessionInfo info = Utils.sessionInfo(req);
    @Nullable
    Account self = info != null ? info.account : null;
    String username = req.params(":username");
    User user = UserStorage.getByUsername(username);
    if (user != null) {
        int[] postCount = { 0 };
        List<Post> wall = PostStorage.getUserWall(user.id, 0, 0, postCount);
        JtwigModel model = JtwigModel.newModel().with("replacedle", user.getFullName()).with("user", user).with("wall", wall).with("own", self != null && self.user.id == user.id).with("postCount", postCount[0]);
        int[] friendCount = { 0 };
        List<User> friends = UserStorage.getRandomFriendsForProfile(user.id, friendCount);
        model.with("friendCount", friendCount[0]).with("friends", friends);
        if (self != null) {
            FriendshipStatus status = UserStorage.getFriendshipStatus(self.user.id, user.id);
            if (status == FriendshipStatus.FRIENDS)
                model.with("isFriend", true);
            else if (status == FriendshipStatus.REQUEST_SENT)
                model.with("friendRequestSent", true);
            else if (status == FriendshipStatus.REQUEST_RECVD)
                model.with("friendRequestRecvd", true);
        }
        return Utils.renderTemplate(req, "profile", model);
    } else {
        resp.status(404);
        return Utils.wrapError(req, "err_user_not_found");
    }
}

19 View Complete Implementation : RelationalOperatorsTest.java
Copyright Apache License 2.0
Author : jtwig
@Test
public void differentTypesWithSameStringValueAreEqual() throws Exception {
    JtwigModel model = new JtwigModel();
    model.with("var1", 5L).with("var2", "5");
    String result = JtwigTemplate.inlineTemplate("{{ var1 == var2 }}").render(model);
    replacedertThat(result, is(equalTo("true")));
}

19 View Complete Implementation : IsTest.java
Copyright Apache License 2.0
Author : jtwig
@Test
public void isNullFunction() throws Exception {
    JtwigModel model = new JtwigModel();
    model.with("value", null);
    String result = JtwigTemplate.inlineTemplate("{% if (value is null) %}Hi{% endif %}").render(model);
    replacedertThat(result, is(equalTo("Hi")));
}

19 View Complete Implementation : TernaryOperatorTest.java
Copyright Apache License 2.0
Author : jtwig
@Test
public void testTemplateTrue() throws Exception {
    JtwigModel model = new JtwigModel();
    model.with("value", true);
    String result = JtwigTemplate.inlineTemplate("{{ value ? '1' : '2' }}").render(model);
    replacedertThat(result, is(equalTo("1")));
}

19 View Complete Implementation : AbstractTemplateOutputBuilder.java
Copyright Apache License 2.0
Author : ConSol
/**
 * Converts the current test data enreplacedy to a string based on the template for the concrete converter.
 *
 * @param abstractTestDataEnreplacedy Test data enreplacedy, which has to be converted
 * @return A string representation of the provided test data enreplacedy
 */
public String createOutput(AbstractTestDataEnreplacedy abstractTestDataEnreplacedy) throws SakuliForwarderCheckedException {
    try {
        JtwigModel model = createModel(abstractTestDataEnreplacedy);
        EnvironmentConfiguration configuration = EnvironmentConfigurationBuilder.configuration().extensions().add(new SpacelessExtension(new SpacelessConfiguration(new LeadingWhitespaceRemover()))).and().functions().add(new IsBlankFunction()).add(new GetOutputStateFunction()).add(new GetOutputDurationFunction()).add(new ExtractScreenshotFunction(screenshotDivConverter)).add(new AbbreviateFunction()).add(new UnixTimestampConverterFunction()).add(new GetTestDataEnreplacedyTypeFunction()).and().build();
        JtwigTemplate template = JtwigTemplate.fileTemplate(getTemplatePath().toFile(), configuration);
        logger.debug(String.format("Render model into JTwig template. Model: '%s'", model));
        return template.render(model);
    } catch (Exception e) {
        throw new SakuliForwarderCheckedException(e, "Exception during rendering of Twig template occurred!");
    }
}

19 View Complete Implementation : TernaryOperatorTest.java
Copyright Apache License 2.0
Author : jtwig
@Test
public void testTrue() throws Exception {
    JtwigModel model = new JtwigModel();
    String result = JtwigTemplate.inlineTemplate("{{ true ? 1 : 2 }}").render(model);
    replacedertThat(result, is(equalTo("1")));
}

19 View Complete Implementation : IsTest.java
Copyright Apache License 2.0
Author : jtwig
@Test
public void isOperatorEmptyFunction() throws Exception {
    JtwigModel model = new JtwigModel();
    String result = JtwigTemplate.inlineTemplate("{% if ([] is empty) %}Hi{% endif %}").render(model);
    replacedertThat(result, is(equalTo("Hi")));
}

19 View Complete Implementation : ProfileRoutes.java
Copyright The Unlicense
Author : grishka
public static Object confirmRemoveFriend(Request req, Response resp, Account self) throws SQLException {
    req.attribute("noHistory", true);
    String username = req.params(":username");
    User user = UserStorage.getByUsername(username);
    if (user != null) {
        FriendshipStatus status = UserStorage.getFriendshipStatus(self.user.id, user.id);
        if (status == FriendshipStatus.FRIENDS || status == FriendshipStatus.REQUEST_SENT || status == FriendshipStatus.FOLLOWING) {
            Lang l = Utils.lang(req);
            String back = Utils.back(req);
            JtwigModel model = JtwigModel.newModel().with("message", l.get("confirm_unfriend_X", user.getFullName())).with("formAction", user.getProfileURL("doRemoveFriend") + "?_redir=" + URLEncoder.encode(back)).with("back", back);
            return Utils.renderTemplate(req, "generic_confirm", model);
        } else {
            return Utils.wrapError(req, "err_not_friends");
        }
    } else {
        resp.status(404);
        return Utils.wrapError(req, "user_not_found");
    }
}

19 View Complete Implementation : AbstractTemplateOutputBuilder.java
Copyright Apache License 2.0
Author : ConSol
/**
 * Creates the model used as input for the template engine. This can be overwritten by the concrete
 * OutputBuilder to add some specific objects to the model (e.g. specific properties)
 *
 * @return
 */
protected JtwigModel createModel(AbstractTestDataEnreplacedy abstractTestDataEnreplacedy) {
    JtwigModel model = JtwigModel.newModel().with(TEST_DATA_ENreplacedY.getName(), abstractTestDataEnreplacedy).with(SAKULI_PROPERTIES.getName(), sakuliProperties);
    if (getSpecificModelEnreplacedies() != null) {
        getSpecificModelEnreplacedies().forEach((templateModelEnreplacedyName, object) -> {
            model.with(templateModelEnreplacedyName.getName(), object);
        });
    }
    return model;
}

19 View Complete Implementation : NativeQueryInfo.java
Copyright MIT License
Author : gasparbarancelli
String getSql() {
    if (sql == null) {
        JtwigTemplate template = JtwigTemplate.clreplacedpathTemplate(file, JtwigTemplateConfig.get());
        JtwigModel model = JtwigModel.newModel();
        parameterList.forEach(p -> model.with(p.getName(), p.getValue()));
        sql = template.render(model);
        for (Clreplaced<ProcessorSql> aClreplaced : processorSqlList) {
            try {
                ProcessorSql processor = aClreplaced.newInstance();
                processor.execute(sql, replaceSql);
            } catch (Exception e) {
                throw new RuntimeException(e.getMessage());
            }
        }
        for (Map.Entry<String, String> replaceSqlEntry : replaceSql.entrySet()) {
            sql = sql.replaceAll("\\$\\{" + replaceSqlEntry.getKey() + "}", replaceSqlEntry.getValue());
        }
        if (sort != null) {
            StringBuilder orderBuilder = new StringBuilder();
            for (Sort.Order order : sort) {
                if (orderBuilder.length() == 0) {
                    orderBuilder.append(" ORDER BY ");
                } else {
                    orderBuilder.append(", ");
                }
                orderBuilder.append(order.getProperty()).append(" ").append(order.getDirection().name());
            }
            sql += orderBuilder.toString();
        }
    }
    if (useTenant) {
        NativeQueryTenantNamedParameterJdbcTemplateInterceptor tenantJdbcTemplate = ApplicationContextProvider.getApplicationContext().getBean(NativeQueryTenantNamedParameterJdbcTemplateInterceptor.clreplaced);
        sql = sql.replace(":SCHEMA", tenantJdbcTemplate.getTenant());
    }
    return sql;
}

19 View Complete Implementation : ProfileRoutes.java
Copyright The Unlicense
Author : grishka
public static Object confirmSendFriendRequest(Request req, Response resp, Account self) throws SQLException {
    req.attribute("noHistory", true);
    String username = req.params(":username");
    User user = UserStorage.getByUsername(username);
    if (user != null) {
        if (user.id == self.user.id) {
            return Utils.wrapError(req, "err_cant_friend_self");
        }
        FriendshipStatus status = UserStorage.getFriendshipStatus(self.user.id, user.id);
        if (status == FriendshipStatus.NONE) {
            JtwigModel model = JtwigModel.newModel();
            model.with("targetUser", user);
            return Utils.renderTemplate(req, "send_friend_request", model);
        } else if (status == FriendshipStatus.FRIENDS) {
            return Utils.wrapError(req, "err_already_friends");
        } else if (status == FriendshipStatus.REQUEST_RECVD) {
            return Utils.wrapError(req, "err_have_incoming_friend_req");
        } else {
            // REQ_SENT
            return Utils.wrapError(req, "err_friend_req_already_sent");
        }
    } else {
        resp.status(404);
        return Utils.wrapError(req, "user_not_found");
    }
}

19 View Complete Implementation : SessionRoutes.java
Copyright The Unlicense
Author : grishka
private static String regError(Request req, String errKey) {
    JtwigModel model = JtwigModel.newModel().with("message", Utils.lang(req).get(errKey)).with("username", req.queryParams("username")).with("preplacedword", req.queryParams("preplacedword")).with("preplacedword2", req.queryParams("preplacedword2")).with("email", req.queryParams("email")).with("first_name", req.queryParams("first_name")).with("last_name", req.queryParams("last_name")).with("invite", req.queryParams("invite"));
    return Utils.renderTemplate(req, "register", model);
}

19 View Complete Implementation : IsTest.java
Copyright Apache License 2.0
Author : jtwig
@Test
public void isDivisibleFunction() throws Exception {
    JtwigModel model = new JtwigModel();
    String result = JtwigTemplate.inlineTemplate("{% if (3 is divisible by 1) %}Hi{% else %}OH{% endif %}").render(model);
    replacedertThat(result, is(equalTo("Hi")));
}