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:cz.incad.Kramerius.views.inc.details.tabs.LoadCustomViewObject.java

public String getContent() throws IOException, ParserConfigurationException, SAXException {
    StringBuilder stringBuilder = new StringBuilder();

    String tab = this.requestProvider.get().getParameter("tab");
    String ds = tab;/*  ww  w  .  ja  va2s.  c om*/
    String xsl = tab;
    if (tab.indexOf('.') >= 0) {
        ds = tab.split("\\.")[0];
        xsl = tab.split("\\.")[1] + ".xsl";
    }

    String pid_path = this.requestProvider.get().getParameter("pid_path");
    List<String> pids = Arrays.asList(pid_path.split("/"));
    if (ds.startsWith("-")) {
        Collections.reverse(pids);
        ds = ds.substring(1);
    }
    for (String pid : pids) {
        if (fedoraAccess.isStreamAvailable(pid, ds)) {

            String mime = fedoraAccess.getMimeTypeForStream(pid, ds);
            if (mime.equals("text/plain")) {
                try {
                    InputStream is = fedoraAccess.getDataStream(pid, ds);
                    byte[] bytes = org.apache.commons.io.IOUtils.toByteArray(is);
                    String enc = UnicodeUtil.getEncoding(bytes);
                    ByteArrayInputStream is2 = new ByteArrayInputStream(bytes);
                    stringBuilder.append("<textarea style=\"width:98%; height:98%; border:0; \">"
                            + IOUtils.readAsString(is2, Charset.forName(enc), true) + "</textarea>");
                } catch (cz.incad.kramerius.security.SecurityException e) {
                    LOGGER.log(Level.INFO, e.getMessage());
                }
            } else if (mime.equals("text/xml") || mime.equals("application/rdf+xml")) {
                try {
                    if (xslService.isAvailable(xsl)) {
                        org.w3c.dom.Document xml = XMLUtils.parseDocument(fedoraAccess.getDataStream(pid, ds),
                                true);
                        String text = xslService.transform(xml, xsl, this.localesProvider.get());
                        stringBuilder.append(text);
                    } else {
                        String xmltext = org.apache.commons.io.IOUtils
                                .toString(fedoraAccess.getDataStream(pid, ds), Charset.forName("UTF-8"));
                        stringBuilder.append(StringEscapeUtils.escapeHtml4(xmltext));
                    }
                } catch (cz.incad.kramerius.security.SecurityException e) {
                    LOGGER.log(Level.INFO, e.getMessage());
                } catch (Exception e) {
                    LOGGER.log(Level.SEVERE, e.getMessage(), e);
                }
            } else if (mime.equals("text/html")) {
                try {
                    String xmltext = org.apache.commons.io.IOUtils.toString(fedoraAccess.getDataStream(pid, ds),
                            Charset.forName("UTF-8"));
                    stringBuilder.append(xmltext);
                } catch (cz.incad.kramerius.security.SecurityException e) {
                    LOGGER.log(Level.INFO, e.getMessage());
                } catch (Exception e) {
                    LOGGER.log(Level.SEVERE, e.getMessage(), e);
                }
            }
        }
    }
    return stringBuilder.toString();
}

From source file:final_exam.BlogController.java

private void initializeRoutes() throws IOException {

    final Configuration configuration = new Configuration();
    configuration.setClassForTemplateLoading(BlogController.class, "/final_exam/freemarker");

    // this is the blog home page
    get("/", (request, response) -> {
        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);
        }/*from  ww w.  j a  v  a2s .c o m*/

        return new ModelAndView(root, "blog_template.ftl");
    }, new FreeMarkerEngine(configuration));

    // used to display actual blog post detail page
    get("/post/:permalink", (request, response) -> {
        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);

            return new ModelAndView(root, "entry_template.ftl");
        }
        return null;
    }, new FreeMarkerEngine(configuration));

    // handle the signup post
    post("/signup", (request, response) -> {
        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");
                return new ModelAndView(root, "signup.ftl");
            } 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");
            return new ModelAndView(root, "signup.ftl");
        }
        return null;
    }, new FreeMarkerEngine(configuration));

    // present signup form for blog
    get("/signup", (request, response) -> {
        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", "");

        return new ModelAndView(root, "signup.ftl");
    }, new FreeMarkerEngine(configuration));

    // will present the form used to process new blog posts
    get("/newpost", (request, response) -> {
        // 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);

            return new ModelAndView(root, "newpost_template.ftl");
        }
        return null;
    }, new FreeMarkerEngine(configuration));

    // handle the new post submission
    post("/newpost", (request, response) -> {

        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);
            return new ModelAndView(root, "newpost_template.ftl");
        } 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);
        }
        return null;
    }, new FreeMarkerEngine(configuration));

    get("/welcome", (request, response) -> {

        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);

            return new ModelAndView(root, "welcome.ftl");
        }
        return null;
    }, new FreeMarkerEngine(configuration));

    // process a new comment
    post("/newcomment", (request, response) -> {

        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");

            return new ModelAndView(root, "entry_template.ftl");
        } else {
            blogPostDAO.addPostComment(name, email, body, permalink);
            response.redirect("/post/" + permalink);
        }
        return null;
    }, new FreeMarkerEngine(configuration));

    // present the login page
    get("/login", (request, response) -> {
        SimpleHash root = new SimpleHash();

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

        return new ModelAndView(root, "login.ftl");

    }, new FreeMarkerEngine(configuration));

    // 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("/login", (request, response) -> {

        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");
            return new ModelAndView(root, "login.ftl");
        }
        return null;

    }, new FreeMarkerEngine(configuration));

    // Show the posts filed under a certain tag
    get("/tag/:thetag", (request, response) -> {

        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);
        }

        return new ModelAndView(root, "blog_template.ftl");

    }, new FreeMarkerEngine(configuration));

    // will allow a user to click Like on a post
    post("/like", (request, response) -> {

        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);
        }
        return null;
    }, new FreeMarkerEngine(configuration));

    // tells the user that the URL is dead
    get("/post_not_found", (request, response) -> {
        SimpleHash root = new SimpleHash();
        return new ModelAndView(root, "post_not_found.ftl");
    }, new FreeMarkerEngine(configuration));

    // allows the user to logout of the blog
    get("/logout", (request, response) -> {

        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");
        }
        return null;
    }, new FreeMarkerEngine(configuration));

    // used to process internal errors
    get("/internal_error", (request, response) -> {

        SimpleHash root = new SimpleHash();

        root.put("error", "System has encountered an error.");
        return new ModelAndView(root, "error_template.ftl");

    }, new FreeMarkerEngine(configuration));
}

From source file:course.BlogController.java

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

            // this is where we would normally load up the blog data
            // but this week, we just display a placeholder.
            HashMap<String, String> root = new HashMap<String, String>();

            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);
            }
        }
    });

    // 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);
            }
        }
    });

    // 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:cloudlens.notebook.JSInterpreter.java

public InterpreterResult interpret(Callable<BlockObject> task, CL cl) {
    if (cl.out instanceof ByteArrayOutputStream) {
        ((ByteArrayOutputStream) cl.out).reset();
    }//w w w.  jav a  2 s . c o m
    if (cl.err instanceof ByteArrayOutputStream) {
        ((ByteArrayOutputStream) cl.err).reset();
    }
    final ExecutorService executor = Executors.newCachedThreadPool(new ThreadFactory() {
        @Override
        public Thread newThread(Runnable r) {
            return new Thread(r) {
                @Override
                public void interrupt() {
                    stop();
                }
            };
        }
    });
    cl.future = executor.submit(task);
    final Gson gson = new GsonBuilder().create();
    try {
        final BlockObject obj = cl.future.get();
        cl.outWriter.flush();
        cl.errWriter.flush();
        if (obj instanceof InterpreterResult) {
            return (InterpreterResult) obj;
        }
        if (cl.out instanceof ByteArrayOutputStream && ((ByteArrayOutputStream) cl.out).size() == 0) {
            if (null != obj && obj.isMapArray()) {
                final Map<String, Map<String, Object>> entries = obj.asMapArray();
                cl.outWriter.print("%table\n");
                int i = 0;
                for (final Map<?, ?> entry : entries.values()) {
                    cl.outWriter.print("\n");
                    if (++i > maxResult) {
                        cl.outWriter.println(
                                "%html <font color=red>Results are limited by zeppelin.cloudlens.maxResult = "
                                        + maxResult + ".</font>");
                        break;
                    }
                    for (final Map.Entry<?, ?> field : entry.entrySet()) {
                        cl.outWriter.print("%html <font color=blue>"
                                + StringEscapeUtils.escapeHtml4(field.getKey().toString()) + "</font>:"
                                + StringEscapeUtils.escapeHtml4(gson.toJson(field.getValue()).toString())
                                + "\t");
                    }
                }
            } else {
                cl.engine.bind("__Result__", obj);
                cl.engine.eval(
                        "print(JSON.stringify(__Result__, function(key, val) { if (typeof val === 'function') return val + ''; return val; }, 2))");
            }
        }
        // }
    } catch (final InterruptedException |

            ExecutionException e) {
        return new InterpreterResult(Code.ERROR, InterpreterUtils.getMostRelevantMessage(e));
    } finally {
        cl.outWriter.flush();
        cl.errWriter.flush();
        executor.shutdownNow();
    }
    return new InterpreterResult(Code.SUCCESS, cl.out.toString());
}

From source file:com.github.pemapmodder.pocketminegui.utils.TerminalCode.java

public static String toHTML(String ansi) {
    //      for(TerminalCode code : values()){
    //         ansi = code.replace(ansi);
    //      }//from ww w .  j  a  va 2  s  .  c o  m
    //      return "<font>" + ansi + "</font>";
    StringBuilder output = new StringBuilder(ansi.length());
    for (int i = 0; i < ansi.length(); ++i) {
        if (ansi.charAt(i) == '\u001b') {
            TerminalCode code = startsWithCode(ansi.substring(i));
            if (code != null) {
                i += code.ansi.length() // skip the ANSI code
                        - 1; // to cancel effect of ++i
                output.append(code.html);
                continue;
            }
        }
        output.append(StringEscapeUtils.escapeHtml4(String.valueOf(ansi.charAt(i))));
    }
    return output.toString();
}

From source file:mobac.program.model.Map.java

public String getToolTip() {
    MapSpace mapSpace = mapSource.getMapSpace();
    EastNorthCoordinate tl = new EastNorthCoordinate(mapSpace, zoom, minTileCoordinate.x, minTileCoordinate.y);
    EastNorthCoordinate br = new EastNorthCoordinate(mapSpace, zoom, maxTileCoordinate.x, maxTileCoordinate.y);

    StringWriter sw = new StringWriter(1024);
    sw.write("<html>");
    sw.write(I18nUtils.localizedStringForKey("lp_atlas_info_map_title"));
    sw.write(I18nUtils.localizedStringForKey("lp_atlas_info_map_source",
            StringEscapeUtils.escapeHtml4(mapSource.toString()),
            StringEscapeUtils.escapeHtml4(mapSource.getName())));
    sw.write(I18nUtils.localizedStringForKey("lp_atlas_info_map_zoom_lv", zoom));
    sw.write(I18nUtils.localizedStringForKey("lp_atlas_info_map_area_start", tl.toString(), minTileCoordinate.x,
            minTileCoordinate.y));//from w  w  w .j  a  v  a2 s  . co m
    sw.write(I18nUtils.localizedStringForKey("lp_atlas_info_map_area_end", br.toString(), maxTileCoordinate.x,
            maxTileCoordinate.y));
    sw.write(I18nUtils.localizedStringForKey("lp_atlas_info_map_size",
            (maxTileCoordinate.x - minTileCoordinate.x + 1), (maxTileCoordinate.y - minTileCoordinate.y + 1)));
    if (parameters != null) {
        sw.write(String.format(I18nUtils.localizedStringForKey("lp_atlas_info_tile_size"),
                parameters.getWidth(), parameters.getHeight()));
        sw.write(String.format(I18nUtils.localizedStringForKey("lp_atlas_info_tile_format"),
                parameters.getFormat().toString()));
    } else {
        sw.write(I18nUtils.localizedStringForKey("lp_atlas_info_tile_format_origin"));
    }

    sw.write(String.format(I18nUtils.localizedStringForKey("lp_atlas_info_max_tile"),
            calculateTilesToDownload()));
    sw.write("</html>");
    return sw.toString();
}

From source file:io.hightide.handlers.ErrorHandler.java

private String htmlify(String str) {
    return StringEscapeUtils.escapeHtml4(str).replaceAll("\\n", "<br/>").replaceAll("\\t",
            "&nbsp;&nbsp;&nbsp;&nbsp;");
}

From source file:baggage.hypertoolkit.html.Html.java

public static Tag passwordInput(String name) {
    Tag tag = input();//from   w  w w. ja va 2  s  .  com
    tag.attr("type", "password");
    tag.attr("name", StringEscapeUtils.escapeHtml4(name));
    return tag;
}

From source file:com.geeksanon.AppController.java

/**
 * Initialise the routes with get and post.
 * /*from w ww  . j a  v a2  s  . co m*/
 * @throws IOException
 *             when not found
 */
private void intialiseRoutes() throws IOException {

    /**
     * Handle the login of the user.
     */
    Spark.get(new Routes("/login", "login.ftl") {

        @Override
        protected void doHandle(Request request, Response response, StringWriter writer)
                throws IOException, TemplateException {
            HashMap<String, String> rootMap = new HashMap<String, String>();
            rootMap.put("username", "");
            rootMap.put("login_error", "");
            template.process(rootMap, writer);
        }
    });

    Spark.post(new Routes("/login", "login.ftl") {

        @Override
        protected void doHandle(Request request, Response response, StringWriter writer)
                throws IOException, TemplateException {
            String username = request.queryParams("username");
            String password = request.queryParams("password");
            LOGGER.info("Username:" + username + "\n" + "Password: " + password);

            DBObject user = userDAO.validateLoginCred(username, password);

            if (user != null) {
                LOGGER.info("Valid user: " + username);
                String sessionID = sessionDAO.startSession(user.get("_id").toString());
                if (sessionID == null) {
                    LOGGER.error("SessionID is null");
                    response.redirect("/_error");
                } else {
                    LOGGER.info("Session ID added to cookie for user:" + username);
                    response.raw().addCookie(new Cookie("session", sessionID));
                    response.redirect("/welcome");
                }
            } else {
                HashMap<String, String> rootMap = new HashMap<String, String>();
                rootMap.put("username", StringEscapeUtils.escapeHtml4(username));
                rootMap.put("password", "");
                rootMap.put("login_error", "Invalid Login! Try Again.");
                template.process(rootMap, writer);
            }
        }
    });

    /**
     * Handle the signup of the user to create an account.
     */
    Spark.get(new Routes("/signup", "signup.ftl") {

        @Override
        protected void doHandle(Request request, Response response, StringWriter writer)
                throws IOException, TemplateException {
            HashMap<String, String> rootMap = new HashMap<String, String>();
            rootMap.put("username", "");
            rootMap.put("password", "");
            rootMap.put("email", "");
            rootMap.put("username_error", "");
            rootMap.put("password_error", "");
            rootMap.put("verify_error", "");
            rootMap.put("email_error", "");
            template.process(rootMap, writer);
        }
    });

    Spark.post(new Routes("/signup", "signup.ftl") {

        @Override
        protected void doHandle(Request request, Response response, StringWriter writer)
                throws IOException, TemplateException {
            String username = request.queryParams("username");
            String password = request.queryParams("password");
            String verifyPassword = request.queryParams("verify");
            String email = request.queryParams("email");

            HashMap<String, String> rootMap = new HashMap<String, String>();
            rootMap.put("username", StringEscapeUtils.escapeHtml4(username));
            rootMap.put("email", StringEscapeUtils.escapeHtml4(email));
            boolean isValid = Helper.validateForm(username, password, verifyPassword, email, rootMap);
            if (isValid) {
                LOGGER.info("Creating user with Username : " + username + "and Password :" + password);
                boolean isAdded = userDAO.addUser(username, password, email);
                if (!isAdded) {
                    rootMap.put("username_error", "Username already exist! Please try another");
                    template.process(rootMap, writer);
                } else {
                    String sessionID = sessionDAO.startSession(username);
                    LOGGER.info("Session ID : " + sessionID);
                    response.raw().addCookie(new Cookie("session", sessionID));
                    response.redirect("/welcome");
                }
            } else {
                LOGGER.error("Validation failed!!");
                template.process(rootMap, writer);
            }
        }
    });

    /**
     * Welcome note to either ask a question, go-home or logout! Handle
     * welcome page.
     */
    Spark.get(new Routes("/welcome", "/welcome_note.ftl") {

        @Override
        protected void doHandle(Request request, Response response, StringWriter writer)
                throws IOException, TemplateException {
            String cookie = Helper.getSessionCookie(request);
            String username = sessionDAO.getUserSessionID(cookie);
            if (username == null) {
                LOGGER.error("Username not found. May be Signup?");
                response.redirect("/signup");
            } else {
                HashMap<String, String> rootMap = new HashMap<String, String>();
                rootMap.put("username", username);
                template.process(rootMap, writer);
            }
        }
    });

    /**
     * Logout from the current session.
     */
    Spark.get(new Routes("/logout", "/login.ftl") {

        @Override
        protected void doHandle(Request request, Response response, StringWriter writer)
                throws IOException, TemplateException {
            String sessionID = Helper.getSessionCookie(request);
            if (sessionID == null) {
                response.redirect("/login");
            } else {
                sessionDAO.stopSession(sessionID);
                Cookie cookie = Helper.getSessionCookieActual(request);
                cookie.setMaxAge(0);
                response.raw().addCookie(cookie);
                response.redirect("/login");
            }
        }
    });

}

From source file:com.opendesign.vo.DesignWorkVO.java

public String getTitle() {
    return StringEscapeUtils.escapeHtml4(title);
}