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:com.netspective.sparx.form.DialogContext.java

public void persistValuesToBrowser() {
    // clear the current cookie values -- the fieldStates.persistValues() will make calls to setClientPersistentValue() to set them
    cookieValues = new HashMap();

    fieldStates.persistValues();// w ww.  ja  va2 s . c  o m

    if (cookieValues == null)
        return;

    StringBuffer cookieValue = new StringBuffer();
    for (Iterator i = cookieValues.entrySet().iterator(); i.hasNext();) {
        Map.Entry entry = (Map.Entry) i.next();
        if (cookieValue.length() > 0)
            cookieValue.append("&");
        cookieValue.append(entry.getKey() + "=" + URLEncoder.encode(entry.getValue().toString()));
    }
    Cookie cookie = new Cookie(getDialog().getCookieName(), cookieValue.toString());
    cookie.setMaxAge(60 * 60 * 24 * 365); // 1 year
    getHttpResponse().addCookie(cookie);
}

From source file:seava.j4e.web.controller.ui.extjs.AbstractUiExtjsController.java

/**
 * Resolve the user's current language from the cookie.
 * /*from   ww  w.j  a  v a 2s. com*/
 * @param request
 * @param response
 * @return
 * @throws Exception
 */
private String resolveLang(HttpServletRequest request, HttpServletResponse response) throws Exception {
    Cookie[] cookies = request.getCookies();
    Cookie c = this.getCookie(cookies, Constants.COOKIE_NAME_LANG);
    if (c == null) {

        String value = this.getSettings().getParam(SysParam.CORE_DEFAULT_LANGUAGE.name());

        c = this.createCookie(Constants.COOKIE_NAME_LANG, value, 60 * 60 * 24 * 365);
        response.addCookie(c);
    }

    String lang = request.getParameter(Constants.REQUEST_PARAM_LANG);
    if (lang == null || lang.equals("")) {
        lang = c.getValue();
    } else {
        c.setMaxAge(0);
        c = this.createCookie(Constants.COOKIE_NAME_LANG, lang, 60 * 60 * 24 * 365);
        response.addCookie(c);
    }
    return lang;
}

From source file:seava.j4e.web.controller.ui.extjs.AbstractUiExtjsController.java

/**
 * Resolve the user's current theme from the cookie.
 * //from w  w  w.  j a va2  s  .  co m
 * @param request
 * @param response
 * @return
 * @throws Exception
 */
private String resolveTheme(HttpServletRequest request, HttpServletResponse response) throws Exception {

    Cookie[] cookies = request.getCookies();
    Cookie c = this.getCookie(cookies, Constants.COOKIE_NAME_THEME);

    if (c == null) {

        String value = this.getSettings().getParam(SysParam.CORE_DEFAULT_THEME_EXTJS.name());
        c = this.createCookie(Constants.COOKIE_NAME_THEME, value, 60 * 60 * 24 * 365);
        response.addCookie(c);
    }

    String theme = request.getParameter(Constants.REQUEST_PARAM_THEME);
    if (theme == null || theme.equals("")) {
        theme = c.getValue();
    } else {
        c.setMaxAge(0);
        c = this.createCookie(Constants.COOKIE_NAME_THEME, theme, 60 * 60 * 24 * 365);
        response.addCookie(c);
    }
    return theme;
}

From source file:org.cloudfoundry.identity.uaa.login.LoginInfoEndpoint.java

@RequestMapping(value = { "/delete_saved_account" })
public String deleteSavedAccount(HttpServletRequest request, HttpServletResponse response, String userId) {
    Cookie cookie = new Cookie("Saved-Account-" + userId, "");
    cookie.setMaxAge(0);
    cookie.setPath(request.getContextPath() + "/login");
    response.addCookie(cookie);//from   w ww  .  j a v a2  s .c o m
    return "redirect:/login";
}

From source file:com.tremolosecurity.proxy.filter.PostProcess.java

protected void postProcess(HttpFilterRequest req, HttpFilterResponse resp, UrlHolder holder,
        HttpResponse response, String finalURL, HttpFilterChain curChain, HttpRequestBase httpRequest)
        throws IOException, Exception {
    boolean isText;
    HttpEntity entity = null;/*from w w  w . j  av a  2s . co m*/

    try {
        entity = response.getEntity();
        /*if (entity != null) {
            entity = new BufferedHttpEntity(entity);
        }*/
    } catch (Throwable t) {
        throw new Exception(t);
    }

    InputStream ins = null;
    boolean entExists = false;

    if (entity == null) {
        resp.setStatus(response.getStatusLine().getStatusCode(), response.getStatusLine().getReasonPhrase());
        ins = new StringBufferInputStream("");
    } else {
        try {
            ins = entity.getContent();
            resp.setStatus(response.getStatusLine().getStatusCode(),
                    response.getStatusLine().getReasonPhrase());
            entExists = true;
        } catch (IllegalStateException e) {
            //do nothing
        }
    }

    if (entExists) {
        org.apache.http.Header hdr = response.getFirstHeader("Content-Type");
        org.apache.http.Header encoding = response.getFirstHeader("Content-Encoding");

        /*if (hdr == null) {
           isText = false;
        } else {
           isText = response.getFirstHeader("Content-Type").getValue().startsWith("text");
                   
           if (encoding != null ) {
              isText = (! encoding.getValue().startsWith("gzip")) && (! encoding.getValue().startsWith("deflate"));
           }
                   
           if (isText) {
              resp.setContentType(response.getFirstHeader("Content-Type").getValue());
              resp.setLocale(response.getLocale());
           }
        }*/
        isText = false;

        try {
            resp.setCharacterEncoding(null);
        } catch (Throwable t) {
            //we're not doing anything
        }

        StringBuffer stmp = new StringBuffer();
        if (response.getFirstHeader("Content-Type") != null) {
            resp.setContentType(response.getFirstHeader("Content-Type").getValue());
        }

        if (response.getLocale() != null) {
            resp.setLocale(response.getLocale());
        }

        org.apache.http.Header[] headers = response.getAllHeaders();
        for (int i = 0; i < headers.length; i++) {
            org.apache.http.Header header = headers[i];
            if (header.getName().equals("Content-Type")) {

                continue;
            } else if (header.getName().equals("Content-Type")) {

                continue;
            } else if (header.getName().equals("Content-Length")) {
                if (!header.getValue().equals("0")) {
                    continue;
                }
            } else if (header.getName().equals("Transfer-Encoding")) {
                continue;
            } else if (header.getName().equalsIgnoreCase("set-cookie")
                    || header.getName().equalsIgnoreCase("set-cookie2")) {
                //System.out.println(header.getValue());
                String cookieVal = header.getValue();
                /*if (cookieVal.endsWith("HttpOnly")) {
                   cookieVal = cookieVal.substring(0,cookieVal.indexOf("HttpOnly"));
                }
                        
                //System.out.println(cookieVal);*/

                List<HttpCookie> cookies = HttpCookie.parse(cookieVal);
                Iterator<HttpCookie> it = cookies.iterator();
                while (it.hasNext()) {
                    HttpCookie cookie = it.next();
                    String cookieFinalName = cookie.getName();
                    if (cookieFinalName.equalsIgnoreCase("JSESSIONID")) {
                        stmp.setLength(0);
                        stmp.append("JSESSIONID").append('-')
                                .append(holder.getApp().getName().replaceAll(" ", "|"));
                        cookieFinalName = stmp.toString();
                    }
                    Cookie respcookie = new Cookie(cookieFinalName, cookie.getValue());
                    respcookie.setComment(cookie.getComment());
                    if (cookie.getDomain() != null) {
                        respcookie.setDomain(cookie.getDomain());
                    }

                    if (cookie.hasExpired()) {
                        respcookie.setMaxAge(0);
                    } else {
                        respcookie.setMaxAge((int) cookie.getMaxAge());
                    }
                    respcookie.setPath(cookie.getPath());

                    respcookie.setSecure(cookie.getSecure());
                    respcookie.setVersion(cookie.getVersion());
                    resp.addCookie(respcookie);
                }
            } else if (header.getName().equals("Location")) {

                if (holder.isOverrideHost()) {
                    fixRedirect(req, resp, finalURL, header);
                } else {
                    resp.addHeader("Location", header.getValue());
                }
            } else {
                resp.addHeader(header.getName(), header.getValue());
            }

        }

        curChain.setIns(ins);
        curChain.setText(isText);
        curChain.setEntity(entity);
        curChain.setHttpRequestBase(httpRequest);

        //procData(req, resp, holder, isText, entity, ins);

    } else {
        isText = false;
    }
}

From source file:org.syncope.console.commons.PreferenceManager.java

public void set(final Request request, final Response response, final String key, final String value) {

    Cookie prefCookie = ((WebRequest) request).getCookie(Constants.PREFS_COOKIE_NAME);

    final Map<String, String> prefs = new HashMap<String, String>();

    if (prefCookie == null || !StringUtils.hasText(prefCookie.getValue())) {
        prefCookie = new Cookie(Constants.PREFS_COOKIE_NAME, null);
    } else {/* w w w  . ja v a2s  .co  m*/
        prefs.putAll(getPrefs(new String(Base64.decodeBase64(prefCookie.getValue().getBytes()))));
    }

    // after retrieved previous setting in order to overwrite the key ...
    prefs.put(key, value);

    try {
        prefCookie.setValue(new String(Base64.encodeBase64(setPrefs(prefs).getBytes())));
    } catch (IOException e) {
        LOG.error("Could not set preferences " + prefs, e);
    }

    prefCookie.setMaxAge(ONE_YEAR_TIME);
    ((WebResponse) response).addCookie(prefCookie);
}

From source file:neu.edu.lab08.HomeController.java

@RequestMapping(value = "/login", method = RequestMethod.POST)
public String submitForm(Model model, @Validated User user, BindingResult result, HttpServletRequest request,
        HttpServletResponse response) {/*from  w ww .  ja v a 2  s.co m*/
    model.addAttribute("user", user);
    String returnVal = "menu";
    String remember = request.getParameter("remember");
    if (result.hasErrors()) {

        return "home";
    } else {
        try {
            User u = userDao.queryUserByNameAndPassword(user.getUsername(), user.getPassword());
            //            ArrayList<Message> messageList = messageDao.listMessagesByUsername(u.getUsername());
            //            ArrayList<Contacts> contactsList = contactsDao.listContactsByUsername(u.getUsername());
            //            int messageSize = messageList.size();
            //            int contactsSize = contactsList.size();
            if (u != null) {
                if (remember != null) {
                    Cookie usernameCookie = new Cookie("usernameCookie", u.getUsername());
                    Cookie passwordCookie = new Cookie("passwordCookie", u.getPassword());
                    usernameCookie.setMaxAge(604000);
                    passwordCookie.setMaxAge(604000);
                    response.addCookie(usernameCookie);
                    response.addCookie(passwordCookie);
                }

                if (u.getRole().equals("admin")) {
                    model.addAttribute("user", u);
                    HttpSession session = request.getSession();
                    session.setAttribute("username", u.getUsername());
                    //                        HttpSession useridsession = request.getSession();
                    //                        useridsession.setAttribute("userid", u.getId());
                    return "createUser";
                } else if (u.getRole().equals("CDC")) {
                    HttpSession session = request.getSession();
                    session.setAttribute("username", u.getUsername());
                    //                        HttpSession useridsession = request.getSession();
                    //                        useridsession.setAttribute("userid", u.getId());
                    model.addAttribute("user", u);
                    ArrayList<Vaccine> vaccineList = vaccineDao.listVaccineByUsername(u.getUsername());
                    ArrayList<Request> requestList = requestDao.listRequest();
                    model.addAttribute("producedvaccineList", vaccineList);
                    model.addAttribute("requestList", requestList);
                    return "cdcMenu";
                } else if (u.getRole().equals("Hospital")) {
                    HttpSession session = request.getSession();
                    session.setAttribute("username", u.getUsername());
                    //                        HttpSession useridsession = request.getSession();
                    //                        useridsession.setAttribute("userid", u.getId());
                    model.addAttribute("user", u);
                    ArrayList<Vaccine> vaccineList = vaccineDao.listVaccine();
                    ArrayList<InsuredPatient> insuredPatientList = patientDao
                            .listInsuredPatientByUsername(u.getUsername());
                    ArrayList<UninsuredPatient> uninsuredPatientList = patientDao
                            .listUninsuredPatientByUsername(u.getUsername());
                    ArrayList<Inventory> inventoryList = inventoryDao.listInventoryByUser(u.getUsername());
                    model.addAttribute("insuredPatientList", insuredPatientList);
                    model.addAttribute("uninsuredPatientList", uninsuredPatientList);
                    model.addAttribute("vaccineList", vaccineList);
                    model.addAttribute("inventoryList", inventoryList);
                    HttpSession inventorysession = request.getSession();
                    inventorysession.setAttribute("inventoryList", inventoryList);
                    ArrayList<UsedVaccine> usedvaccineList = vaccineDao
                            .listUsedVaccineByUsername(u.getUsername());
                    model.addAttribute("usedvaccineList", usedvaccineList);
                    return "hospitalMenu";
                }
            }
        } catch (Exception e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }

    }

    return "home";

}

From source file:com.sjc.cc.login.action.LoginAction.java

/**
 * CookieID//www  .ja  v  a 2 s  .c om
 * 
 * @param userId
 */
private void setCloudUserIdCookie(Long userId) {
    HttpServletResponse response = ServletActionContext.getResponse();
    Cookie loginInfo = new Cookie(COOKIE_CC_USER_ID, userId + "");
    loginInfo.setMaxAge(-1);
    if (logger.isDebugEnabled()) {
        logger.debug("The Cookie Cloud is :" + loginInfo + "," + loginInfo.getValue());
    }
    response.addCookie(loginInfo);
}

From source file:es.pode.soporte.seguridad.openId.ui.openid.OpenIDAuthenticationProcessingFilter.java

private void setCookieAutenticado(HttpServletResponse response, String claimedIdentity) throws IOException {

    Cookie cookieOpenId = new Cookie(nombreCookieOpenId, claimedIdentity);
    cookieOpenId.setPath("/");
    //El tiempo de expiracin de la cookie se recoger del Agrega.properties

    int caducidadCookie = new Long(((System.currentTimeMillis()) * 1000)).intValue()
            + (new Integer(this.getAgregaPropertyValue(AgregaProperties.TIMEOUTCOOKIEOPENID))).intValue();
    if (log.isDebugEnabled())
        log.debug("caducidadCookie " + caducidadCookie);
    cookieOpenId.setMaxAge(caducidadCookie);
    //cookieOpenId.setMaxAge(-1);
    response.addCookie(cookieOpenId);//from www  . j a v a  2 s .c o  m

}

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

private HttpSession createOpenSession(HttpServletRequest req, HttpServletResponse resp, ServletContext ctx)
        throws Exception {

    byte[] idBytes = new byte[20];
    random.nextBytes(idBytes);/*from   ww w  . j a  v  a2 s.  c om*/
    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.setOpen(true);
    tsession.refresh(this.ctx, this);
    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);

    // TODO add global session timeout
    // tsession.setMaxInactiveInterval(app.getCookieConfig().getTimeout());

    // TODO add global open session name
    Cookie sessionCookie = new Cookie(cfg.getCfg().getApplications().getOpenSessionCookieName(), id);

    sessionCookie.setPath("/");
    sessionCookie.setSecure(cfg.getCfg().getApplications().isOpenSessionSecure());
    sessionCookie.setHttpOnly(cfg.getCfg().getApplications().isOpenSessionHttpOnly());
    sessionCookie.setMaxAge(-1);
    // TODO add secure?
    // sessionCookie.setSecure(app.getCookieConfig().isSecure());
    resp.addCookie(sessionCookie);

    sessions.put(id, tsession);

    return tsession;
}