Example usage for javax.servlet.http Cookie setMaxAge

List of usage examples for javax.servlet.http Cookie setMaxAge

Introduction

In this page you can find the example usage for javax.servlet.http Cookie setMaxAge.

Prototype

public void setMaxAge(int expiry) 

Source Link

Document

Sets the maximum age in seconds for this Cookie.

Usage

From source file:de.appsolve.padelcampus.utils.LoginUtil.java

public void deleteLoginCookie(HttpServletRequest request, HttpServletResponse response) {
    Cookie[] cookies = request.getCookies();
    if (cookies != null) {
        for (Cookie cookie : cookies) {
            if (cookie.getName().equals(COOKIE_LOGIN_TOKEN)) {
                if (cookie.getValue() != null && cookie.getValue().split(":").length == 2) {
                    LoginCookie loginCookie = loginCookieDAO.findByUUID(cookie.getValue().split(":")[0]);
                    if (loginCookie != null) {
                        loginCookieDAO.deleteById(loginCookie.getId());
                        break;
                    }/* w  ww  . jav  a 2s.c  om*/
                }
            }
        }
    }
    deleteCookie(request, response, null);
    deleteCookie(request, response, "/");
    deleteCookie(request, response, "/page");
    deleteCookie(request, response, "/admin");
    deleteCookie(request, response, "/login");
    deleteCookie(request, response, "/admin/events");
    deleteCookie(request, response, "/admin/events/edit");
    deleteCookie(request, response, "/events/event");
    Cookie cookie = new Cookie(COOKIE_LOGIN_TOKEN, null);
    cookie.setDomain(request.getServerName());
    cookie.setMaxAge(0);
    response.addCookie(cookie);
}

From source file:com.exilant.exility.core.HtmlRequestHandler.java

/***
 * Carry out all rituals of logging the user out
 * /*from   w w  w  . j  ava 2 s  .  co  m*/
 * @param req
 * @param resp
 */
private void doLogout(HttpServletRequest req, HttpServletResponse resp) {
    Cookie cookie = new Cookie(AP.loggedInUserFieldName, "");
    Date now = DateUtility.addDays(new Date(), -2);
    cookie.setMaxAge((int) now.getTime());
    resp.addCookie(cookie);
    req.getSession().invalidate();
    // this.removeGlobalDataFromSession(req);
}

From source file:com.tremolosecurity.proxy.SessionManagerImpl.java

private HttpSession createSession(ApplicationType app, HttpServletRequest req, HttpServletResponse resp,
        ServletContext ctx, SecretKey encKey) throws Exception {

    byte[] idBytes = new byte[20];
    random.nextBytes(idBytes);/*from ww  w .j av  a2  s .c o  m*/

    StringBuffer b = new StringBuffer();
    b.append('f').append(Hex.encodeHexString(idBytes));
    String id = b.toString();

    // HttpSession session = req.getSession(true);
    TremoloHttpSession tsession = new TremoloHttpSession(id);
    tsession.setAppName(app.getName());
    tsession.refresh(this.ctx, this);
    tsession.setOpen(false);
    this.anonMech.createSession(tsession, this.anonChainType);

    AuthController actl = (AuthController) tsession.getAttribute(ProxyConstants.AUTH_CTL);

    AuthInfo auInfo = actl.getAuthInfo();
    auInfo.setAuthComplete(true);

    // session.setAttribute(app.getCookieConfig().getSessionCookieName(),
    // tsession);

    tsession.setAttribute(OpenUnisonConstants.TREMOLO_SESSION_ID, id);
    tsession.setMaxInactiveInterval(app.getCookieConfig().getTimeout());

    Cipher cipher = Cipher.getInstance("AES/CBC/PKCS5Padding");
    cipher.init(Cipher.ENCRYPT_MODE, encKey);

    byte[] encSessionKey = cipher.doFinal(id.getBytes("UTF-8"));
    String base64d = new String(org.bouncycastle.util.encoders.Base64.encode(encSessionKey));

    Token token = new Token();
    token.setEncryptedRequest(base64d);
    token.setIv(new String(org.bouncycastle.util.encoders.Base64.encode(cipher.getIV())));

    Gson gson = new Gson();

    String cookie = gson.toJson(token);

    byte[] btoken = cookie.getBytes("UTF-8");
    String encCookie = new String(org.bouncycastle.util.encoders.Base64.encode(btoken));

    Cookie sessionCookie;

    sessionCookie = new Cookie(app.getCookieConfig().getSessionCookieName(), encCookie);

    // logger.debug("session size : " +
    // org.apache.directory.shared.ldap.util.Base64.encode(encSession).length);
    String domain = ProxyTools.getInstance().getCookieDomain(app.getCookieConfig(), req);
    if (domain != null) {
        sessionCookie.setDomain(domain);
    }
    sessionCookie.setPath("/");
    sessionCookie.setSecure(false);
    sessionCookie.setMaxAge(-1);
    sessionCookie.setSecure(app.getCookieConfig().isSecure());
    sessionCookie.setHttpOnly(app.getCookieConfig().isHttpOnly() != null && app.getCookieConfig().isHttpOnly());
    resp.addCookie(sessionCookie);

    // delete the opensession if it exists
    if (cfg.getCfg().getApplications().getOpenSessionCookieName() != null
            && !cfg.getCfg().getApplications().getOpenSessionCookieName().isEmpty()) {
        Cookie openSessionCookie = new Cookie(cfg.getCfg().getApplications().getOpenSessionCookieName(), id);

        openSessionCookie.setPath("/");
        openSessionCookie.setSecure(cfg.getCfg().getApplications().isOpenSessionSecure());
        openSessionCookie.setHttpOnly(cfg.getCfg().getApplications().isOpenSessionHttpOnly());
        openSessionCookie.setMaxAge(0);
        resp.addCookie(openSessionCookie);
    }

    sessions.put(id, tsession);

    return tsession;
}

From source file:MyServlet.java

public void doGet(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, java.io.IOException {

    Cookie cookie = null;
    //Get an array of Cookies associated with this domain
    Cookie[] cookies = request.getCookies();
    boolean newCookie = false;

    //Get the 'mycookie' Cookie if it exists
    if (cookies != null) {
        for (int i = 0; i < cookies.length; i++) {
            if (cookies[i].getName().equals("mycookie")) {
                cookie = cookies[i];// w w w.  j  a  v  a  2 s. c o m
            }
        } //end for
    } //end if

    if (cookie == null) {
        newCookie = true;
        //Get the cookie's Max-Age from a context-param element
        //If the 'cookie-age' param is not set properly
        //then set the cookie to a default of -1, 'never expires'
        int maxAge;
        try {
            maxAge = new Integer(getServletContext().getInitParameter("cookie-age")).intValue();
        } catch (Exception e) {
            maxAge = -1;
        }

        //Create the Cookie object

        cookie = new Cookie("mycookie", "" + getNextCookieValue());
        cookie.setPath(request.getContextPath());
        cookie.setMaxAge(maxAge);
        response.addCookie(cookie);

    } //end if
      // get some info about the cookie
    response.setContentType("text/html");
    java.io.PrintWriter out = response.getWriter();

    out.println("<html>");
    out.println("<head>");
    out.println("<title>Cookie info</title>");
    out.println("</head>");
    out.println("<body>");

    out.println("<h2> Information about the cookie named \"mycookie\"</h2>");

    out.println("Cookie value: " + cookie.getValue() + "<br>");
    if (newCookie) {
        out.println("Cookie Max-Age: " + cookie.getMaxAge() + "<br>");
        out.println("Cookie Path: " + cookie.getPath() + "<br>");
    }

    out.println("</body>");
    out.println("</html>");

    out.close();
}

From source file:org.workcast.ssoficlient.service.LoginHandler.java

/**
 * create a cookie to last a year, and set on the response
 *///from w  w w  . j a  va 2 s . co m
public void setTenantCookie(String cookieName, String cookieValue) throws Exception {
    // make a tenant-specific cookie name automatically
    if (aa != null && aa.tenant != null) {
        cookieName = cookieName + URLEncoder.encode(aa.tenant, "UTF-8");
    }
    Cookie c = new Cookie(cookieName, cookieValue);
    c.setMaxAge(30000000); // about 1 year from login
    c.setPath("/");
    response.addCookie(c);
}

From source file:com.tremolosecurity.proxy.SessionManagerImpl.java

@Override
public void writeSession(UrlHolder holder, TremoloHttpSession session, HttpServletRequest request,
        HttpServletResponse response) throws IOException {
    /*//  w  ww. j a v  a2 s. c om
     * Enumeration enumer = session.getAttributeNames(); while
     * (enumer.hasMoreElements()) { String name = (String)
     * enumer.nextElement(); String value =
     * session.getAttribute(name).toString(); logger.debug(name + "='" +
     * value + "'"); }
     */

    ByteArrayOutputStream bos = new ByteArrayOutputStream();
    GZIPOutputStream gzip = new GZIPOutputStream(bos);
    ObjectOutputStream oos = new ObjectOutputStream(gzip);
    oos.writeObject(session);
    oos.flush();
    oos.close();

    byte[] encSession = new byte[0];

    try {
        Cipher cipher = Cipher.getInstance("AES");
        cipher.init(Cipher.ENCRYPT_MODE,
                holder.getConfig().getSecretKey(holder.getApp().getCookieConfig().getKeyAlias()));
        encSession = cipher.doFinal(bos.toByteArray());
    } catch (Exception e) {
        e.printStackTrace();
    }
    Cookie sessionCookie;
    sessionCookie = new Cookie(holder.getApp().getCookieConfig().getSessionCookieName(),
            new String(Base64.encodeBase64(encSession)));

    // logger.debug("session size : " +
    // org.apache.directory.shared.ldap.util.Base64.encode(encSession).length);

    String domain = ProxyTools.getInstance().getCookieDomain(holder.getApp().getCookieConfig(), request);
    if (domain != null) {
        sessionCookie.setDomain(domain);
    }
    sessionCookie.setPath("/");
    sessionCookie.setSecure(false);
    sessionCookie.setMaxAge(-1);
    response.addCookie(sessionCookie);
}

From source file:com.exilant.exility.core.HtmlRequestHandler.java

/**
 * Carry out login rituals after a successful execution of login service
 * /*from w  ww .j ava  2  s . c  om*/
 * @param req
 * @param resp
 * @param data
 * @return
 */

private boolean doLogin(HttpServletRequest req, HttpServletResponse resp, ServiceData data) {
    if (data.getErrorStatus() != CommonFieldNames.SEVERITY_SUCCESS) {
        return false;
    }

    req.getSession().setAttribute(AP.loggedInUserFieldName, data.getValue(AP.loggedInUserFieldName));
    // set cookies
    Cookie cookie = new Cookie(AP.loggedInUserFieldName, data.getValue(AP.loggedInUserFieldName));
    Date now = DateUtility.addDays(new Date(), 400);
    cookie.setMaxAge((int) now.getTime());
    resp.addCookie(cookie);
    if (AP.setCookies != null) {
        for (String name : AP.setCookies) {
            cookie = new Cookie(name, data.getValue(name));
            cookie.setPath(req.getContextPath());
            if (data.hasValue(name)) {
                Spit.out(" cookie " + name + " is set with value = " + data.getValue(name));
                cookie.setMaxAge((int) now.getTime());
            } else {
                // we have to remove the cookie
                Spit.out(name + " does not have value and hence cookie is not set");
                cookie.setMaxAge(-12);
            }
            resp.addCookie(cookie);
        }
    }

    data.addValue("*_usersession", req.getSession().getId());

    this.addGlobalDataToSession(req, data);

    // TEXTILE needs the following four lines
    /*
     * ExilityInterface.Bridge br = new ExilityInterface.Bridge();
     * DataCollection dc = new DataCollection(); dc.CopyFrom(data);
     * br.AddoldVersionGlobalValues(dc, ctx);
     */

    if (AP.cleanserName != null) {
        ServiceCleanserInterface serviceCleanser = ServiceCleansers.getCleanser(AP.cleanserName);
        if (serviceCleanser == null) {
            data.addError(AP.cleanserName + " is not a valid cleanser name.");
            return false;
        }
        if (!serviceCleanser.cleanseAfterService(req, data)) {
            {
                data.addMessage("cleanseAfterServiceFailed", AP.cleanserName);
                return false;
            }
        }
    }

    return true;
}

From source file:course.PrivateCloudController.java

private void initializeRoutes() throws IOException {
    // this is the blog home page
    get(new FreemarkerBasedRoute("/", "blog_template.ftl") {
        @Override//from   w  w  w.  j a  va2s. com
        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);
        }
    });

    get(new FreemarkerBasedRoute("/display_vms", "display_vms.ftl") {
        @Override
        public void doHandle(Request request, Response response, Writer writer)
                throws IOException, TemplateException {
            //String username = sessionDAO.findUserNameBySessionId(getSessionCookie(request));
            List<Document> posts = new ArrayList<Document>();// = statsDAO.findByDateDescending(10);
            ManagedEntity[] mes = new InventoryNavigator(Path).searchManagedEntities("VirtualMachine");

            SimpleHash root = new SimpleHash();
            System.out.println("Display VM: VM list");
            BasicDBObject query = new BasicDBObject();
            VMsDBCollection.deleteMany(query);

            //HashMap<String, String> root = new HashMap<String, String>();
            if (!(mes == null || mes.length == 0)) {
                for (int i = 0; i < mes.length; i++) {
                    Document text = new Document();
                    VirtualMachine vm = (VirtualMachine) mes[i];

                    if (!vm.getName().contains("Template")) {
                        String name = vm.getName();
                        text.append("name", name);
                        Document DB_VMs = new Document("_id", name);

                        if (vm.getConfig() != null) {
                            String instanceId = vm.getConfig().getInstanceUuid();
                            text.append("instanceId", instanceId);
                        }

                        System.out.println("VM Name : " + name);

                        String conectionState = vm.getRuntime().getConnectionState().toString();
                        text.append("conectionState", conectionState);
                        DB_VMs.append("conectionState", conectionState);

                        String ip = vm.getGuest().getIpAddress();
                        text.append("ip", ip);
                        DB_VMs.append("ip", ip);

                        String powerState = vm.getRuntime().getPowerState().toString();
                        text.append("powerState", powerState);

                        if (vm.getTriggeredAlarmState() == null) {
                            text.append("alarmState", "notTriggered");
                            DB_VMs.append("powerState", "notTriggered");
                        } else {
                            text.append("alarmState", "Triggered");
                            DB_VMs.append("powerState", "Triggered");
                        }

                        String launchTime = writeActualDate(vm.getRuntime().getBootTime());
                        text.append("launchTime", launchTime);
                        DB_VMs.append("launchTime", launchTime);

                        posts.add(text);
                        VMsDBCollection.insertOne(DB_VMs);

                    }
                }
            }
            root.put("VMs", posts);
            template.process(root, writer);
        }
    });

    get(new FreemarkerBasedRoute("/create_vm", "create_vm.ftl") {
        @Override
        public void doHandle(Request request, Response response, Writer writer)
                throws IOException, TemplateException {
            SimpleHash root = new SimpleHash();
            System.out.println("Inside Create VM backend");

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

    post(new FreemarkerBasedRoute("/create_vm", "/create_vm.ftl") {
        @Override
        public void doHandle(Request request, Response response, Writer writer)
                throws IOException, TemplateException {

            if (request.queryParams("Create") != null) {

                ManagedEntity[] mes = new InventoryNavigator(Path).searchManagedEntities("VirtualMachine");

                //Clone VM
                String vmname = request.queryParams("vmname");
                String vm_template = request.queryParams("OS");

                VirtualMachine vm = (VirtualMachine) new InventoryNavigator(Path)
                        .searchManagedEntity("VirtualMachine", vm_template);

                VirtualMachineRuntimeInfo vmri = vm.getRuntime();

                HostSystem hs = new HostSystem(vm.getServerConnection(), vmri.getHost());

                Datacenter dc = (Datacenter) new InventoryNavigator(Path).searchManagedEntity("Datacenter",
                        "T03-DC");
                ResourcePool rp = (ResourcePool) new InventoryNavigator(dc)
                        .searchManagedEntities("ResourcePool")[0];

                if (vm == null) {
                    System.out.println("No VM found with name " + vm_template);

                    SimpleHash root = new SimpleHash();

                    root.put("login_error", "No template available");
                    template.process(root, writer);
                } else {
                    try {
                        VirtualMachineCloneSpec cloneSpec = new VirtualMachineCloneSpec();

                        VirtualMachineRelocateSpec locateSpec = new VirtualMachineRelocateSpec();
                        locateSpec.setPool(rp.getMOR());
                        cloneSpec.setLocation(locateSpec);
                        cloneSpec.setPowerOn(false);
                        cloneSpec.setTemplate(false);

                        Task task = vm.cloneVM_Task((Folder) vm.getParent(), vmname, cloneSpec);
                        System.out.println("Launching the VM clone task. " + "Please wait ...");
                        /*String status = task.waitForTask();
                        if (status == Task.SUCCESS) {
                        System.out.println("VM got cloned successfully.");
                        } else {
                        System.out.println("Failure -: VM cannot be cloned");
                        }*/
                    } catch (Exception e) {
                        e.printStackTrace();
                    }

                    response.redirect("/display_vms");
                }
            } else if (request.queryParams("Cancel") != null) {

                response.redirect("/display_vms");

            }
        }
    });

    post(new FreemarkerBasedRoute("/display_vms", "display_vms.ftl") {
        @Override
        public void doHandle(Request request, Response response, Writer writer)
                throws IOException, TemplateException {
            //String username = sessionDAO.findUserNameBySessionId(getSessionCookie(request));
            List<Document> posts = new ArrayList<Document>();// = statsDAO.findByDateDescending(10);
            SimpleHash root = new SimpleHash();

            BasicDBObject query = new BasicDBObject();
            ArrayList<String> VM_list = new ArrayList<String>();
            MongoCursor<Document> cursor = VMsDBCollection.find(query).iterator();

            while (cursor.hasNext()) {

                String a = cursor.next().toJson();
                System.out.println(a);

                try {
                    JSONObject jsonObject = new JSONObject(a);
                    String vm_name = jsonObject.getString("_id");
                    VM_list.add(vm_name);
                } catch (JSONException e) {
                    e.printStackTrace();
                }

            }

            //take VM list from DB
            if (request.queryParams("PowerOn") != null) {
                Iterator vm_iterator = VM_list.iterator();
                while (vm_iterator.hasNext()) {
                    String VM_name = vm_iterator.next().toString();
                    boolean myCheckBox = request.queryParams(VM_name) != null;
                    if (myCheckBox) {
                        System.out.println("Power ON VM " + VM_name);
                        powerOn(VM_name);
                    }

                }
                response.redirect("/display_vms");

            } else if (request.queryParams("PowerOff") != null) {
                Iterator vm_iterator = VM_list.iterator();
                while (vm_iterator.hasNext()) {
                    String VM_name = vm_iterator.next().toString();
                    boolean myCheckBox = request.queryParams(VM_name) != null;
                    if (myCheckBox) {
                        System.out.println("Power Off VM " + VM_name);
                        powerOff(VM_name);
                    }
                }
                response.redirect("/display_vms");

            } else if (request.queryParams("Delete") != null) {
                Iterator vm_iterator = VM_list.iterator();
                while (vm_iterator.hasNext()) {
                    String VM_name = vm_iterator.next().toString();
                    boolean myCheckBox = request.queryParams(VM_name) != null;
                    if (myCheckBox) {
                        System.out.println("Delete VM " + VM_name);
                        deleteVM(VM_name);
                    }
                }
                response.redirect("/display_vms");

            } else if (request.queryParams("Get_Chart") != null) {
                Iterator vm_iterator = VM_list.iterator();
                while (vm_iterator.hasNext()) {
                    String VM_name = vm_iterator.next().toString();
                    boolean myCheckBox = request.queryParams(VM_name) != null;
                    if (myCheckBox) {
                        System.out.println("Get VM " + VM_name + " Charts");
                        CurrentSelectedVM = VM_name;
                    }
                }
                response.redirect("/gChart");

            } else if (request.queryParams("Create") != null) {
                response.redirect("/create_vm");

            } else {
                System.out.println("Invalid ");
                response.redirect("/display_vms");
                // ???
            }

        }
    });

    // google chart handler
    get(new FreemarkerBasedRoute("/gChart", "GoogleLine.ftl") {
        @Override
        public void doHandle(Request request, Response response, Writer writer)
                throws IOException, TemplateException {
            String username = sessionDAO.findUserNameBySessionId(getSessionCookie(request));

            if (CurrentSelectedVM != null) {

                ArrayList<ArrayList> gchartMData = statsDAO.getMGchart(CurrentSelectedVM);
                ArrayList<ArrayList> gchartCData = statsDAO.getCGchart(CurrentSelectedVM);
                SimpleHash root = new SimpleHash();
                root.put("VMName", CurrentSelectedVM);

                BasicDBObject query = new BasicDBObject();
                query.put("_id", CurrentSelectedVM);
                MongoCursor<Document> cursor = VMsDBCollection.find(query).iterator();
                while (cursor.hasNext()) {
                    String a = cursor.next().toJson();
                    System.out.println("Json :::: \n" + a);
                    try {
                        JSONObject jsonObject = new JSONObject(a);
                        if (jsonObject.has("ip") && jsonObject.has("_id")) {
                            root.put("IPAD", jsonObject.getString("ip"));
                            System.out.println("IP address for this VM is " + jsonObject.getString("ip"));

                        }
                    } catch (JSONException e) {
                        e.printStackTrace();
                    }

                }
                if (CurrentSelectedVM.contains("Lin"))
                    root.put("vm_type", "Lin");
                else if (CurrentSelectedVM.contains("Win"))
                    root.put("vm_type", "Win");

                CurrentSelectedVM = null;

                root.put("usernameVM", "administrator");
                root.put("passwordVM", "12!@qwQW");

                root.put("gcdata1", gchartMData);
                root.put("gcdata2", gchartCData);
                //System.out.println(gchartData);
                // System.out.println(gchartData.get(0));

                template.process(root, writer);
            }

        }
    });

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

            if (request.queryParams("Home") != null) {
                response.redirect("/display_vms");
            }
        }
    });

    // 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("/login");
                }
            } 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("/display_vms");
                }
            } 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:com.adito.security.DefaultLogonController.java

private SessionInfo addLogonTicket(HttpServletRequest request, HttpServletResponse response, User user,
        InetAddress address, int sessionType) {
    String logonTicket = TicketGenerator.getInstance().generateUniqueTicket("SLX");
    if (log.isInfoEnabled())
        log.info("Adding logon ticket to session " + request.getSession().getId());
    request.getSession().setAttribute(Constants.LOGON_TICKET, logonTicket);
    request.setAttribute(Constants.LOGON_TICKET, logonTicket);
    String userAgent = request.getHeader("User-Agent");
    SessionInfo info = SessionInfo.nextSession(request.getSession(), logonTicket, user, address, sessionType,
            userAgent);/*from w  w w  .j  a  v a2 s .com*/
    request.getSession().setAttribute(Constants.SESSION_INFO, info);
    try {
        String sessionIdentifier = SystemProperties.get("adito.cookie", "JSESSIONID");
        String sessionId = null;
        Cookie[] cookies = request.getCookies();
        for (int i = 0; cookies != null && i < cookies.length; i++) {
            if (cookies[i].getName().equalsIgnoreCase(sessionIdentifier)) {
                sessionId = cookies[i].getValue();
                break;
            }
        }
        if (sessionId != null) {
            logonsBySessionId.put(sessionId, info);
        } else
            log.warn("Could not find session id using identifier " + sessionIdentifier + " in HTTP request");
    } catch (Exception ex) {
        log.warn("Failed to determine HTTP session id", ex);
    }
    logons.put(logonTicket, info);
    /**
     * Set the normal logon ticket without a domain - this works in almost
     * all circumstances
     */
    Cookie cookie = new Cookie(Constants.LOGON_TICKET, logonTicket);
    cookie.setMaxAge(Property.getPropertyInt(new SystemConfigKey("security.session.maxCookieAge")));
    cookie.setPath("/");
    cookie.setSecure(true);
    response.addCookie(cookie);
    /**
     * Set a logon ticket for the domain - this is require to make active
     * dns work.
     */
    Cookie cookie2 = new Cookie(Constants.DOMAIN_LOGON_TICKET, logonTicket);
    cookie2.setMaxAge(Property.getPropertyInt(new SystemConfigKey("security.session.maxCookieAge")));
    cookie2.setPath("/");
    // We now set the domain on the cookie so the new Active DNS feature for
    // Reverse Proxy works correctly
    String host = request.getHeader("Host");
    if (host != null) {
        HostService hostService = new HostService(host);
        cookie2.setDomain(hostService.getHost());
    }
    cookie.setSecure(true);
    response.addCookie(cookie2);
    return info;
}