Example usage for org.apache.commons.lang3 StringEscapeUtils escapeHtml4

List of usage examples for org.apache.commons.lang3 StringEscapeUtils escapeHtml4

Introduction

In this page you can find the example usage for org.apache.commons.lang3 StringEscapeUtils escapeHtml4.

Prototype

public static final String escapeHtml4(final String input) 

Source Link

Document

Escapes the characters in a String using HTML entities.

For example:

"bread" & "butter"

becomes:

"bread" & "butter".

Usage

From source file:de.akra.idocit.wsdl.services.DocumentationGenerator.java

/**
 * Adds the <code>text</code> as {@link Node#TEXT_NODE}s to the <code>element</code>.
 * Newline and tabulator characters are replaced with &lt;br/&gt; and &lt;tab/&gt;
 * elements./*from w ww . ja va2 s . c o  m*/
 * 
 * @param element
 *            The {@link Element} to which the <code>text</code> should be added.
 * @param text
 *            The text to convert and add to the <code>element</code>.
 * @return The <code>element</code>.
 */
private static Element addTextAsNodes(Element element, String text) {
    String escapedText = StringEscapeUtils.escapeHtml4(text);

    StringBuilder tmpText = new StringBuilder();

    for (int i = 0; i < escapedText.length(); ++i) {
        switch (escapedText.charAt(i)) {
        case '\t':
            if (tmpText.length() > 0) {
                element.appendChild(domDocument.createTextNode(tmpText.toString()));
                tmpText = new StringBuilder();
            }
            element.appendChild(domDocument.createElement(XML_TAG_TAB));
            break;

        case '\r':
            if (tmpText.length() > 0) {
                element.appendChild(domDocument.createTextNode(tmpText.toString()));
                tmpText = new StringBuilder();
            }
            element.appendChild(domDocument.createElement(XML_TAG_BR));

            // if CR and LF are together, replace it only once
            // Changes due to Issue #2
            if ((escapedText.length() > i + 1) && escapedText.charAt(i + 1) == '\n')
            // End changes due to Issue #2
            {
                i++;
            }
            break;

        case '\n':
            if (tmpText.length() > 0) {
                element.appendChild(domDocument.createTextNode(tmpText.toString()));
                tmpText = new StringBuilder();
            }
            element.appendChild(domDocument.createElement(XML_TAG_BR));

            // if CR and LF are together, replace it only once
            // Changes due to Issue #2
            if ((escapedText.length() > i + 1) && escapedText.charAt(i + 1) == '\r')
            // End changes due to Issue #2
            {
                i++;
            }
            break;

        default:
            tmpText.append(escapedText.charAt(i));
            break;
        }
    }

    // append pending text
    if (tmpText.length() > 0) {
        element.appendChild(domDocument.createTextNode(tmpText.toString()));
    }

    return element;
}

From source file:net.longfalcon.web.ProfileController.java

@RequestMapping(value = "/profileedit", method = RequestMethod.POST)
public View profileEditPost(@ModelAttribute("profile") ProfileVO profileVO, HttpSession httpSession,
        Model model) {//  w ww  .  j  av a  2 s.  c o m
    String error = "";
    User user = userDAO.findByUserId(profileVO.getUserId());
    String email = profileVO.getEmail();
    if (ValidatorUtil.isValidEmail(email)) {
        if (userDAO.findByEmail(email) == null) {
            user.setEmail(email);
        } else {
            error += "Email address " + StringEscapeUtils.escapeHtml4(email) + " is taken or unavailable<br/>";
        }
    } else {
        error += "Email address " + StringEscapeUtils.escapeHtml4(email) + " is invalid<br/>";
    }

    String newPassword = profileVO.getPassword();
    String newPasswordConfirm = profileVO.getConfirmPassword();
    if (ValidatorUtil.isNotNull(newPassword)) {
        if (newPassword.equals(newPasswordConfirm)) {
            try {
                user.setPassword(PasswordHash.createHash(newPassword));
            } catch (NoSuchAlgorithmException | InvalidKeySpecException e) {
                _log.error(e);
            }
        } else {
            error += "Password Mismatch<br/>";
        }
    }
    user.setMovieView(profileVO.isMovieView() ? 1 : 0);
    user.setMusicView(profileVO.isMusicView() ? 1 : 0);
    user.setConsoleView(profileVO.isConsoleView() ? 1 : 0);
    List<Integer> exCatIds = profileVO.getExCatIds();
    // TODO update excats

    if (ValidatorUtil.isNull(error)) {
        userDAO.update(user);
    }
    httpSession.setAttribute("errors", error);

    return safeRedirect("/profileedit");
}

From source file:es.iesnervion.Week3.Ex3_2Ex3_3.BlogController.java

private void initializeRoutes() throws IOException {
    // this is the blog home page
    get(new FreemarkerBasedRoute("/", "blog_template.ftl") {
        @Override//from w ww  .  java  2 s .com
        public void doHandle(Request request, Response response, Writer writer)
                throws IOException, TemplateException {
            String username = sessionDAO.findUserNameBySessionId(getSessionCookie(request));

            List<Document> posts = blogPostDAO.findByDateDescending(10);
            SimpleHash root = new SimpleHash();

            root.put("myposts", posts);
            if (username != null) {
                root.put("username", username);
            }

            template.process(root, writer);
        }
    });

    // used to display actual blog post detail page
    get(new FreemarkerBasedRoute("/post/:permalink", "entry_template.ftl") {
        @Override
        protected void doHandle(Request request, Response response, Writer writer)
                throws IOException, TemplateException {
            String permalink = request.params(":permalink");

            System.out.println("/post: get " + permalink);

            Document post = blogPostDAO.findByPermalink(permalink);
            if (post == null) {
                response.redirect("/post_not_found");
            } else {
                // empty comment to hold new comment in form at bottom of blog entry detail page
                SimpleHash newComment = new SimpleHash();
                newComment.put("name", "");
                newComment.put("email", "");
                newComment.put("body", "");

                SimpleHash root = new SimpleHash();

                root.put("post", post);
                root.put("comments", newComment);

                template.process(root, writer);
            }
        }
    });

    // handle the signup post
    post(new FreemarkerBasedRoute("/signup", "signup.ftl") {
        @Override
        protected void doHandle(Request request, Response response, Writer writer)
                throws IOException, TemplateException {
            String email = request.queryParams("email");
            String username = request.queryParams("username");
            String password = request.queryParams("password");
            String verify = request.queryParams("verify");

            HashMap<String, String> root = new HashMap<String, String>();
            root.put("username", StringEscapeUtils.escapeHtml4(username));
            root.put("email", StringEscapeUtils.escapeHtml4(email));

            if (validateSignup(username, password, verify, email, root)) {
                // good user
                System.out.println("Signup: Creating user with: " + username + " " + password);
                if (!userDAO.addUser(username, password, email)) {
                    // duplicate user
                    root.put("username_error", "Username already in use, Please choose another");
                    template.process(root, writer);
                } else {
                    // good user, let's start a session
                    String sessionID = sessionDAO.startSession(username);
                    System.out.println("Session ID is" + sessionID);

                    response.raw().addCookie(new Cookie("session", sessionID));
                    response.redirect("/welcome");
                }
            } else {
                // bad signup
                System.out.println("User Registration did not validate");
                template.process(root, writer);
            }
        }
    });

    // present signup form for blog
    get(new FreemarkerBasedRoute("/signup", "signup.ftl") {
        @Override
        protected void doHandle(Request request, Response response, Writer writer)
                throws IOException, TemplateException {

            SimpleHash root = new SimpleHash();

            // initialize values for the form.
            root.put("username", "");
            root.put("password", "");
            root.put("email", "");
            root.put("password_error", "");
            root.put("username_error", "");
            root.put("email_error", "");
            root.put("verify_error", "");

            template.process(root, writer);
        }
    });

    get(new FreemarkerBasedRoute("/welcome", "welcome.ftl") {
        @Override
        protected void doHandle(Request request, Response response, Writer writer)
                throws IOException, TemplateException {

            String cookie = getSessionCookie(request);
            String username = sessionDAO.findUserNameBySessionId(cookie);

            if (username == null) {
                System.out.println("welcome() can't identify the user, redirecting to signup");
                response.redirect("/signup");

            } else {
                SimpleHash root = new SimpleHash();

                root.put("username", username);

                template.process(root, writer);
            }
        }
    });

    // will present the form used to process new blog posts
    get(new FreemarkerBasedRoute("/newpost", "newpost_template.ftl") {
        @Override
        protected void doHandle(Request request, Response response, Writer writer)
                throws IOException, TemplateException {

            // get cookie
            String username = sessionDAO.findUserNameBySessionId(getSessionCookie(request));

            if (username == null) {
                // looks like a bad request. user is not logged in
                response.redirect("/login");
            } else {
                SimpleHash root = new SimpleHash();
                root.put("username", username);

                template.process(root, writer);
            }
        }
    });

    // handle the new post submission
    post(new FreemarkerBasedRoute("/newpost", "newpost_template.ftl") {
        @Override
        protected void doHandle(Request request, Response response, Writer writer)
                throws IOException, TemplateException {

            String title = StringEscapeUtils.escapeHtml4(request.queryParams("subject"));
            String post = StringEscapeUtils.escapeHtml4(request.queryParams("body"));
            String tags = StringEscapeUtils.escapeHtml4(request.queryParams("tags"));

            String username = sessionDAO.findUserNameBySessionId(getSessionCookie(request));

            if (username == null) {
                response.redirect("/login"); // only logged in users can post to blog
            } else if (title.equals("") || post.equals("")) {
                // redisplay page with errors
                HashMap<String, String> root = new HashMap<String, String>();
                root.put("errors", "post must contain a title and blog entry.");
                root.put("subject", title);
                root.put("username", username);
                root.put("tags", tags);
                root.put("body", post);
                template.process(root, writer);
            } else {
                // extract tags
                ArrayList<String> tagsArray = extractTags(tags);

                // substitute some <p> for the paragraph breaks
                post = post.replaceAll("\\r?\\n", "<p>");

                String permalink = blogPostDAO.addPost(title, post, tagsArray, username);

                // now redirect to the blog permalink
                response.redirect("/post/" + permalink);
            }
        }
    });

    get(new FreemarkerBasedRoute("/welcome", "welcome.ftl") {
        @Override
        protected void doHandle(Request request, Response response, Writer writer)
                throws IOException, TemplateException {

            String cookie = getSessionCookie(request);
            String username = sessionDAO.findUserNameBySessionId(cookie);

            if (username == null) {
                System.out.println("welcome() can't identify the user, redirecting to signup");
                response.redirect("/signup");

            } else {
                SimpleHash root = new SimpleHash();

                root.put("username", username);

                template.process(root, writer);
            }
        }
    });

    // process a new comment
    post(new FreemarkerBasedRoute("/newcomment", "entry_template.ftl") {
        @Override
        protected void doHandle(Request request, Response response, Writer writer)
                throws IOException, TemplateException {
            String name = StringEscapeUtils.escapeHtml4(request.queryParams("commentName"));
            String email = StringEscapeUtils.escapeHtml4(request.queryParams("commentEmail"));
            String body = StringEscapeUtils.escapeHtml4(request.queryParams("commentBody"));
            String permalink = request.queryParams("permalink");

            Document post = blogPostDAO.findByPermalink(permalink);
            if (post == null) {
                response.redirect("/post_not_found");
            }
            // check that comment is good
            else if (name.equals("") || body.equals("")) {
                // bounce this back to the user for correction
                SimpleHash root = new SimpleHash();
                SimpleHash comment = new SimpleHash();

                comment.put("name", name);
                comment.put("email", email);
                comment.put("body", body);
                root.put("comment", comment);
                root.put("post", post);
                root.put("errors", "Post must contain your name and an actual comment");

                template.process(root, writer);
            } else {
                blogPostDAO.addPostComment(name, email, body, permalink);
                response.redirect("/post/" + permalink);
            }
        }
    });

    // present the login page
    get(new FreemarkerBasedRoute("/login", "login.ftl") {
        @Override
        protected void doHandle(Request request, Response response, Writer writer)
                throws IOException, TemplateException {
            SimpleHash root = new SimpleHash();

            root.put("username", "");
            root.put("login_error", "");

            template.process(root, writer);
        }
    });

    // process output coming from login form. On success redirect folks to the welcome page
    // on failure, just return an error and let them try again.
    post(new FreemarkerBasedRoute("/login", "login.ftl") {
        @Override
        protected void doHandle(Request request, Response response, Writer writer)
                throws IOException, TemplateException {

            String username = request.queryParams("username");
            String password = request.queryParams("password");

            System.out.println("Login: User submitted: " + username + "  " + password);

            Document user = userDAO.validateLogin(username, password);

            if (user != null) {

                // valid user, let's log them in
                String sessionID = sessionDAO.startSession(user.get("_id").toString());

                if (sessionID == null) {
                    response.redirect("/internal_error");
                } else {
                    // set the cookie for the user's browser
                    response.raw().addCookie(new Cookie("session", sessionID));

                    response.redirect("/welcome");
                }
            } else {
                SimpleHash root = new SimpleHash();

                root.put("username", StringEscapeUtils.escapeHtml4(username));
                root.put("password", "");
                root.put("login_error", "Invalid Login");
                template.process(root, writer);
            }
        }
    });

    // tells the user that the URL is dead
    get(new FreemarkerBasedRoute("/post_not_found", "post_not_found.ftl") {
        @Override
        protected void doHandle(Request request, Response response, Writer writer)
                throws IOException, TemplateException {
            SimpleHash root = new SimpleHash();
            template.process(root, writer);
        }
    });

    // allows the user to logout of the blog
    get(new FreemarkerBasedRoute("/logout", "signup.ftl") {
        @Override
        protected void doHandle(Request request, Response response, Writer writer)
                throws IOException, TemplateException {

            String sessionID = getSessionCookie(request);

            if (sessionID == null) {
                // no session to end
                response.redirect("/login");
            } else {
                // deletes from session table
                sessionDAO.endSession(sessionID);

                // this should delete the cookie
                Cookie c = getSessionCookieActual(request);
                c.setMaxAge(0);

                response.raw().addCookie(c);

                response.redirect("/login");
            }
        }
    });

    // used to process internal errors
    get(new FreemarkerBasedRoute("/internal_error", "error_template.ftl") {
        @Override
        protected void doHandle(Request request, Response response, Writer writer)
                throws IOException, TemplateException {
            SimpleHash root = new SimpleHash();

            root.put("error", "System has encountered an error.");
            template.process(root, writer);
        }
    });
}

From source file:alxpez.blog.BlogController.java

private void initializeRoutes() throws IOException {
    // this is the blog home page
    get(new FreemarkerBasedRoute("/", "blog_template.ftl") {
        @Override/*from w  w w . ja  v a2 s.c om*/
        public void doHandle(Request request, Response response, Writer writer)
                throws IOException, TemplateException {
            String username = sessionDAO.findUserNameBySessionId(getSessionCookie(request));

            List<Document> posts = blogPostDAO.findByDateDescending(10);
            SimpleHash root = new SimpleHash();

            root.put("myposts", posts);
            if (username != null) {
                root.put("username", username);
            }

            template.process(root, writer);
        }
    });

    // used to display actual blog post detail page
    get(new FreemarkerBasedRoute("/post/:permalink", "entry_template.ftl") {
        @Override
        protected void doHandle(Request request, Response response, Writer writer)
                throws IOException, TemplateException {
            String permalink = request.params(":permalink");

            System.out.println("/post: get " + permalink);

            Document post = blogPostDAO.findByPermalink(permalink);
            if (post == null) {
                response.redirect("/post_not_found");
            } else {
                // empty comment to hold new comment in form at bottom of blog entry detail page
                SimpleHash newComment = new SimpleHash();
                newComment.put("name", "");
                newComment.put("email", "");
                newComment.put("body", "");

                SimpleHash root = new SimpleHash();

                root.put("post", post);
                root.put("comment", newComment);

                template.process(root, writer);
            }
        }
    });

    // handle the signup post
    post(new FreemarkerBasedRoute("/signup", "signup.ftl") {
        @Override
        protected void doHandle(Request request, Response response, Writer writer)
                throws IOException, TemplateException {
            String email = request.queryParams("email");
            String username = request.queryParams("username");
            String password = request.queryParams("password");
            String verify = request.queryParams("verify");

            HashMap<String, String> root = new HashMap<String, String>();
            root.put("username", StringEscapeUtils.escapeHtml4(username));
            root.put("email", StringEscapeUtils.escapeHtml4(email));

            if (validateSignup(username, password, verify, email, root)) {
                // good user
                System.out.println("Signup: Creating user with: " + username + " " + password);
                if (!userDAO.addUser(username, password, email)) {
                    // duplicate user
                    root.put("username_error", "Username already in use, Please choose another");
                    template.process(root, writer);
                } else {
                    // good user, let's start a session
                    String sessionID = sessionDAO.startSession(username);
                    System.out.println("Session ID is" + sessionID);

                    response.raw().addCookie(new Cookie("session", sessionID));
                    response.redirect("/welcome");
                }
            } else {
                // bad signup
                System.out.println("User Registration did not validate");
                template.process(root, writer);
            }
        }
    });

    // present signup form for blog
    get(new FreemarkerBasedRoute("/signup", "signup.ftl") {
        @Override
        protected void doHandle(Request request, Response response, Writer writer)
                throws IOException, TemplateException {

            SimpleHash root = new SimpleHash();

            // initialize values for the form.
            root.put("username", "");
            root.put("password", "");
            root.put("email", "");
            root.put("password_error", "");
            root.put("username_error", "");
            root.put("email_error", "");
            root.put("verify_error", "");

            template.process(root, writer);
        }
    });

    // will present the form used to process new blog posts
    get(new FreemarkerBasedRoute("/newpost", "newpost_template.ftl") {
        @Override
        protected void doHandle(Request request, Response response, Writer writer)
                throws IOException, TemplateException {

            // get cookie
            String username = sessionDAO.findUserNameBySessionId(getSessionCookie(request));

            if (username == null) {
                // looks like a bad request. user is not logged in
                response.redirect("/login");
            } else {
                SimpleHash root = new SimpleHash();
                root.put("username", username);

                template.process(root, writer);
            }
        }
    });

    // handle the new post submission
    post(new FreemarkerBasedRoute("/newpost", "newpost_template.ftl") {
        @Override
        protected void doHandle(Request request, Response response, Writer writer)
                throws IOException, TemplateException {

            String title = StringEscapeUtils.escapeHtml4(request.queryParams("subject"));
            String post = StringEscapeUtils.escapeHtml4(request.queryParams("body"));
            String tags = StringEscapeUtils.escapeHtml4(request.queryParams("tags"));

            String username = sessionDAO.findUserNameBySessionId(getSessionCookie(request));

            if (username == null) {
                response.redirect("/login"); // only logged in users can post to blog
            } else if (title.equals("") || post.equals("")) {
                // redisplay page with errors
                HashMap<String, String> root = new HashMap<String, String>();
                root.put("errors", "post must contain a title and blog entry.");
                root.put("subject", title);
                root.put("username", username);
                root.put("tags", tags);
                root.put("body", post);
                template.process(root, writer);
            } else {
                // extract tags
                ArrayList<String> tagsArray = extractTags(tags);

                // substitute some <p> for the paragraph breaks
                post = post.replaceAll("\\r?\\n", "<p>");

                String permalink = blogPostDAO.addPost(title, post, tagsArray, username);

                // now redirect to the blog permalink
                response.redirect("/post/" + permalink);
            }
        }
    });

    get(new FreemarkerBasedRoute("/welcome", "welcome.ftl") {
        @Override
        protected void doHandle(Request request, Response response, Writer writer)
                throws IOException, TemplateException {

            String cookie = getSessionCookie(request);
            String username = sessionDAO.findUserNameBySessionId(cookie);

            if (username == null) {
                System.out.println("welcome() can't identify the user, redirecting to signup");
                response.redirect("/signup");

            } else {
                SimpleHash root = new SimpleHash();

                root.put("username", username);

                template.process(root, writer);
            }
        }
    });

    // process a new comment
    post(new FreemarkerBasedRoute("/newcomment", "entry_template.ftl") {
        @Override
        protected void doHandle(Request request, Response response, Writer writer)
                throws IOException, TemplateException {
            String name = StringEscapeUtils.escapeHtml4(request.queryParams("commentName"));
            String email = StringEscapeUtils.escapeHtml4(request.queryParams("commentEmail"));
            String body = StringEscapeUtils.escapeHtml4(request.queryParams("commentBody"));
            String permalink = request.queryParams("permalink");

            Document post = blogPostDAO.findByPermalink(permalink);
            if (post == null) {
                response.redirect("/post_not_found");
            }
            // check that comment is good
            else if (name.equals("") || body.equals("")) {
                // bounce this back to the user for correction
                SimpleHash root = new SimpleHash();
                SimpleHash comment = new SimpleHash();

                comment.put("name", name);
                comment.put("email", email);
                comment.put("body", body);
                root.put("comment", comment);
                root.put("post", post);
                root.put("errors", "Post must contain your name and an actual comment");

                template.process(root, writer);
            } else {
                blogPostDAO.addPostComment(name, email, body, permalink);
                response.redirect("/post/" + permalink);
            }
        }
    });

    // present the login page
    get(new FreemarkerBasedRoute("/login", "login.ftl") {
        @Override
        protected void doHandle(Request request, Response response, Writer writer)
                throws IOException, TemplateException {
            SimpleHash root = new SimpleHash();

            root.put("username", "");
            root.put("login_error", "");

            template.process(root, writer);
        }
    });

    // process output coming from login form. On success redirect folks to the welcome page
    // on failure, just return an error and let them try again.
    post(new FreemarkerBasedRoute("/login", "login.ftl") {
        @Override
        protected void doHandle(Request request, Response response, Writer writer)
                throws IOException, TemplateException {

            String username = request.queryParams("username");
            String password = request.queryParams("password");

            System.out.println("Login: User submitted: " + username + "  " + password);

            Document user = userDAO.validateLogin(username, password);

            if (user != null) {

                // valid user, let's log them in
                String sessionID = sessionDAO.startSession(user.get("_id").toString());

                if (sessionID == null) {
                    response.redirect("/internal_error");
                } else {
                    // set the cookie for the user's browser
                    response.raw().addCookie(new Cookie("session", sessionID));

                    response.redirect("/welcome");
                }
            } else {
                SimpleHash root = new SimpleHash();

                root.put("username", StringEscapeUtils.escapeHtml4(username));
                root.put("password", "");
                root.put("login_error", "Invalid Login");
                template.process(root, writer);
            }
        }
    });

    // Show the posts filed under a certain tag
    get(new FreemarkerBasedRoute("/tag/:thetag", "blog_template.ftl") {
        @Override
        protected void doHandle(Request request, Response response, Writer writer)
                throws IOException, TemplateException {

            String username = sessionDAO.findUserNameBySessionId(getSessionCookie(request));
            SimpleHash root = new SimpleHash();

            String tag = StringEscapeUtils.escapeHtml4(request.params(":thetag"));
            List<Document> posts = blogPostDAO.findByTagDateDescending(tag);

            root.put("myposts", posts);
            if (username != null) {
                root.put("username", username);
            }

            template.process(root, writer);
        }
    });

    // will allow a user to click Like on a post
    post(new FreemarkerBasedRoute("/like", "entry_template.ftl") {
        @Override
        protected void doHandle(Request request, Response response, Writer writer)
                throws IOException, TemplateException {

            String permalink = request.queryParams("permalink");
            String commentOrdinalStr = request.queryParams("comment_ordinal");

            // look up the post in question

            int ordinal = Integer.parseInt(commentOrdinalStr);

            // TODO: check return or have checkSession throw
            String username = sessionDAO.findUserNameBySessionId(getSessionCookie(request));
            Document post = blogPostDAO.findByPermalink(permalink);

            //  if post not found, redirect to post not found error
            if (post == null) {
                response.redirect("/post_not_found");
            } else {
                blogPostDAO.likePost(permalink, ordinal);

                response.redirect("/post/" + permalink);
            }
        }
    });

    // tells the user that the URL is dead
    get(new FreemarkerBasedRoute("/post_not_found", "post_not_found.ftl") {
        @Override
        protected void doHandle(Request request, Response response, Writer writer)
                throws IOException, TemplateException {
            SimpleHash root = new SimpleHash();
            template.process(root, writer);
        }
    });

    // allows the user to logout of the blog
    get(new FreemarkerBasedRoute("/logout", "signup.ftl") {
        @Override
        protected void doHandle(Request request, Response response, Writer writer)
                throws IOException, TemplateException {

            String sessionID = getSessionCookie(request);

            if (sessionID == null) {
                // no session to end
                response.redirect("/login");
            } else {
                // deletes from session table
                sessionDAO.endSession(sessionID);

                // this should delete the cookie
                Cookie c = getSessionCookieActual(request);
                c.setMaxAge(0);

                response.raw().addCookie(c);

                response.redirect("/login");
            }
        }
    });

    // used to process internal errors
    get(new FreemarkerBasedRoute("/internal_error", "error_template.ftl") {
        @Override
        protected void doHandle(Request request, Response response, Writer writer)
                throws IOException, TemplateException {
            SimpleHash root = new SimpleHash();

            root.put("error", "System has encountered an error.");
            template.process(root, writer);
        }
    });
}

From source file:com.brsanthu.dataexporter.DataWriter.java

protected void println(String value) {
    out.print(options.isEscapeHtml() ? StringEscapeUtils.escapeHtml4(value) : value);
    println();/*from  w  w  w .ja v a 2 s . co  m*/

    if (autoFlush) {
        out.flush();
    }
}

From source file:com.day.cq.wcm.foundation.forms.FormsHelper.java

/**
 * Signal the start of the form.//from w  ww .j a  v a 2s  . co  m
 * Prepare the request object, write out the client javascript (if the form
 * is configured accordingly) and write out the start form tag and hidden fields:
 * {@link FormsConstants#REQUEST_PROPERTY_FORMID} with the value of the form id.
 * {@link FormsConstants#REQUEST_PROPERTY_FORM_START} with the relative path to the form start par
 * and <code>_charset_</code> with the value <code>UTF-8</code>
 *
 * @param request The current request.
 * @param response The current response.
 * @since 5.3
 */
public static void startForm(final SlingHttpServletRequest request, final SlingHttpServletResponse response)
        throws IOException, ServletException {
    // get resource and properties
    final Resource formResource = request.getResource();
    initialize(request, formResource, response);

    writeJavaScript(request, response, formResource);
    final String formId = getFormId(request);

    // write form element, we post to the same url we came from
    final PrintWriter out = response.getWriter();
    String url = request.getRequestURI();

    final String suffix = getActionSuffix(request);
    if (StringUtils.isNotBlank(suffix)) {
        url += (suffix.startsWith("/")) ? suffix : "/" + suffix;
    }

    out.print("<form method=\"POST\" action=\"");
    out.print(url);
    out.print("\" id=\"");
    out.print(StringEscapeUtils.escapeHtml4(formId));
    out.print("\" name=\"");
    out.print(StringEscapeUtils.escapeHtml4(formId));
    out.print("\" enctype=\"multipart/form-data\">");

    // write form id as hidden field
    out.print("<input type=\"hidden\" name=\"");
    out.print(FormsConstants.REQUEST_PROPERTY_FORMID);
    out.print("\" value=\"");
    out.print(StringEscapeUtils.escapeHtml4(formId));
    out.print("\"/>");
    // write form start as hidden field
    out.print("<input type=\"hidden\" name=\"");
    out.print(FormsConstants.REQUEST_PROPERTY_FORM_START);
    out.print("\" value=\"");
    if (formResource.getPath().startsWith(url)) {
        // relative
        out.print(formResource.getPath().substring(url.length() + 1));
    } else {
        // absolute
        out.print(formResource.getPath());
    }
    out.print("\"/>");
    // write charset as hidden field
    out.print("<input type=\"hidden\" name=\"_charset_\" value=\"UTF-8\"/>");

    // check for redirect configuration
    final ValueMap properties = ResourceUtil.getValueMap(formResource);
    String redirect = properties.get("redirect", "");
    if (redirect.length() > 0) {
        if (redirect.startsWith("/") && request.getContextPath() != null
                && request.getContextPath().length() > 0) {
            if (!redirect.startsWith(request.getContextPath())) {
                redirect = request.getContextPath() + redirect;
            }
        }
        final int lastSlash = redirect.lastIndexOf('/');
        if (redirect.indexOf('.', lastSlash) == -1) {
            redirect = redirect + ".html";
        }
        out.print("<input type=\"hidden\" name=\"" + FormsConstants.REQUEST_PROPERTY_REDIRECT + "\" value=\"");
        out.print(StringEscapeUtils.escapeHtml4(redirect));
        out.print("\"/>");
    }

    // allow action to add form fields
    final String actionType = properties.get(FormsConstants.START_PROPERTY_ACTION_TYPE, "");
    if (actionType.length() > 0) {
        runAction(actionType, "addfields", formResource, request, response);
    }
}

From source file:com.nttec.everychan.chans.chan420.Chan420JsonMapper.java

private static String toHtml(String com, String boardName, String threadNumber) {
    com = StringEscapeUtils.escapeHtml4(com);

    String[] lines = com.split("\n");
    StringBuilder sb = new StringBuilder();
    for (String line : lines) {
        if (line.startsWith("&gt;") && !line.startsWith("&gt;&gt;")) {
            sb.append("<span class=\"unkfunc\">").append(line).append("</span><br/>");
        } else {/*from w  w  w .j  a  va  2 s. com*/
            sb.append(line).append("<br/>");
        }
    }

    if (sb.length() > 5)
        sb.setLength(sb.length() - 5);
    com = sb.toString();
    com = com.replaceAll("(^|[\\n ])(https?://[^ ]*)", "$1<a href=\"$2\">$2</a>");
    com = ("\n" + com + "\n").replaceAll("\n&gt;(.*?)\n", "\n<span class=\"unkfunc\">&gt;$1</span>\n");
    com = com.replace("\r\n", "\n").replace("\n", "<br/>");
    com = com.replaceAll("(?i)\\[b\\](.*?)\\[/b\\]", "<b>$1</b>");
    com = com.replaceAll("(?i)\\[i\\](.*?)\\[/i\\]", "<i>$1</i>");
    com = com.replaceAll("(?i)\\[s\\](.*?)\\[/s\\]", "<s>$1</s>");
    com = com.replaceAll("(?i)\\[spoiler\\](.*?)\\[/spoiler\\]", "<span class=\"spoiler\">$1</span>");
    com = com.replaceAll("\\[\\*\\*\\](.*?)\\[/\\*\\*\\]", "<b>$1</b>");
    com = com.replaceAll("\\[\\*\\](.*?)\\[/\\*\\]", "<i>$1</i>");
    com = com.replaceAll("\\[%\\](.*?)\\[/%\\]", "<span class=\"spoiler\">$1</span>");
    com = com.replaceAll("&gt;&gt;(\\d+)",
            "<a href=\"/" + boardName + "/res/" + threadNumber + ".php#$1\">$0</a>");

    return com;
}

From source file:com.netsteadfast.greenstep.action.CommonSelectItemsDataAction.java

private void queryItems() throws ServiceException, Exception {
    boolean pleaseSelect = YesNo.YES.equals(this.getFields().get("pleaseSelect"));
    if ("SYS".equals(this.getFields().get("type"))) { // ? sys
        Map<String, String> sysMap = this.sysService.findSysMap(super.getBasePath(), pleaseSelect);
        this.resetPleaseSelectDataMapFromLocaleLang(sysMap);
        for (Map.Entry<String, String> entry : sysMap.entrySet()) {
            Map<String, String> dataMap = new HashMap<String, String>();
            dataMap.put("key", entry.getKey());
            dataMap.put("value", entry.getValue());
            this.items.add(dataMap);
        }/*w w  w.j  a v a 2s.  c o  m*/
        this.success = IS_YES;
    }
    if ("SYS_PROG".equals(this.getFields().get("type"))) { // ? sys_prog ITEM_TYPE='FOLDER'
        String sysOid = this.getFields().get("sysOid");
        SysVO sys = this.loadSysValueObj(sysOid);
        Map<String, String> sysProgMap = this.sysProgService.findSysProgFolderMap(super.getBasePath(),
                sys.getSysId(), MenuItemType.FOLDER, pleaseSelect);
        this.resetPleaseSelectDataMapFromLocaleLang(sysProgMap);
        for (Map.Entry<String, String> entry : sysProgMap.entrySet()) {
            Map<String, String> dataMap = new HashMap<String, String>();
            dataMap.put("key", entry.getKey());
            dataMap.put("value", entry.getValue());
            this.items.add(dataMap);
        }
        this.success = IS_YES;
    }
    if ("SYS_PROG_IN_MENU".equals(this.getFields().get("type"))) { // ? sys_prog.prog_id  tb_sys_menu  
        String sysOid = this.getFields().get("sysOid");
        SysVO sys = this.loadSysValueObj(sysOid);
        List<SysProgVO> menuProgList = this.sysProgService.findForInTheFolderMenuItems(sys.getSysId(), null,
                null);
        //this.items.add(super.providedSelectZeroDataMap(true));
        Map<String, String> dataMapFirst = new HashMap<String, String>();
        dataMapFirst.put("key", Constants.HTML_SELECT_NO_SELECT_ID);
        dataMapFirst.put("value", Constants.HTML_SELECT_NO_SELECT_NAME);
        this.resetPleaseSelectDataMapFromLocaleLang(dataMapFirst);
        this.items.add(dataMapFirst);
        if (menuProgList != null) {
            for (SysProgVO sysProg : menuProgList) {
                Map<String, String> dataMap = new HashMap<String, String>();
                dataMap.put("key", sysProg.getOid());
                dataMap.put("value", IconUtils.getMenuIcon(super.getBasePath(), sysProg.getIcon())
                        + StringEscapeUtils.escapeHtml4(sysProg.getName()));
                this.items.add(dataMap);
            }
        }
        this.success = IS_YES;
    }
}

From source file:com.zextras.modules.chat.ConversationBuilder.java

public void addMessage(ChatMessage chatMessage, Date conversationDate, TimeZone timezone) {
    mConversationDate = conversationDate;
    Date messageDate = chatMessage.getCreationDate();

    String sender = chatMessage.getSender().toString();
    String nickname = sender;/*from  www .  jav a 2 s. c  o  m*/

    mSentByMe = sender.equals(mUsername);
    if (!mSentByMe) {
        mSentByMe = sender.equals("Me");
    }
    Boolean isFirstMessage = (!sender.equals(mLastUser) && (mConversation[TEXT_PART].length() > 0));

    if (!mSentByMe) {
        try {
            User user = mOpenUserProvider.getUser(new SpecificAddress(mUsername));
            if (user.hasRelationship(chatMessage.getSender())) {
                Relationship recipient = user.getRelationship(chatMessage.getSender());
                nickname = recipient.getBuddyNickname();
            }
        } catch (ChatDbException ignored) {
        }
    } else {
        nickname = "Me";
    }

    mHourFormatter.setTimeZone(timezone);
    String formattedDate = mHourFormatter.format(messageDate);
    String formattedUser = nickname;

    // remove all [ hour ]. Example: "[ 10:00 ]"
    String conversationText = chatMessage.getBody();
    conversationText = conversationText.replaceFirst("Me:", "");

    // remove all e-mail address + :. Example: "simple@example.com:"
    conversationText = conversationText.replaceFirst("\\[.*?\\] [A-Za-z0-9._%+-]+@[A-Za-z0-9.-]+\\.[A-Za-z]+:",
            "");

    String messageHTML;
    messageHTML = StringEscapeUtils.escapeHtml4(conversationText).replaceAll("\n", "<br>");

    appendMessage(conversationText, messageHTML, isFirstMessage, formattedUser, formattedDate);
    mLastUser = formattedUser;
}

From source file:com.technophobia.substeps.report.DetailedJsonBuilder.java

private String getExceptionMessage(IExecutionNode node) {
    String exceptionMessage = "";

    if (node.getResult().getThrown() != null) {

        final String exceptionMsg = StringEscapeUtils.escapeHtml4(node.getResult().getThrown().getMessage());

        exceptionMessage = replaceNewLines(exceptionMsg);

    }//from w  w w .  j a va 2 s  .c om

    return exceptionMessage;
}