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.toft.widgets.login.LoginAction.java

/**
 * cookie??//from   w  w w.ja  va  2s.c o  m
 * 
 * @throws Exception
 */
private void addCookie() throws Exception {
    String isChange = (String) this.getContext().getParam("isChange");
    if (isChange == null) {
        return;
    }
    if (!isChange.equals("1")) {
        return;
    }
    String keepUser = (String) this.getContext().getParam("keepUser");
    String keepPassword = (String) this.getContext().getParam("keepPassword");

    if ("1".equals(keepUser)) {
        // cookie???
        String[] keys = new String[] { "userId", "accountSet", "localeSet", "keepUser" };
        for (int i = 0; i < keys.length; i++) {
            String value = (String) getContext().getParam(keys[i]);
            Cookie cookie = new Cookie(keys[i], value);
            cookie.setMaxAge(60 * 60 * 24 * 365);
            cookie.setPath("/");
            getResponse().addCookie(cookie);
        }
        if ("1".equals(keepPassword)) {
            String[] passkeys = new String[] { "keepPassword", "password" };
            for (int i = 0; i < passkeys.length; i++) {
                String value = (String) getContext().getParam(passkeys[i]);
                Cookie cookie = new Cookie(passkeys[i], value);
                cookie.setMaxAge(60 * 60 * 24 * 365);
                cookie.setPath("/");
                getResponse().addCookie(cookie);
            }
        } else {
            String[] passkeys = new String[] { "keepPassword", "password" };
            for (int i = 0; i < passkeys.length; i++) {
                Cookie cookie = new Cookie(passkeys[i], "");
                cookie.setMaxAge(0);
                cookie.setPath("/");
                getResponse().addCookie(cookie);
            }
        }
    } else {
        String[] keys = new String[] { "userId", "accountSet", "localeSet", "keepUser", "keepPassword",
                "password" };
        for (int i = 0; i < keys.length; i++) {
            Cookie cookie = new Cookie(keys[i], "");
            cookie.setMaxAge(0);
            cookie.setPath("/");
            getResponse().addCookie(cookie);
        }
    }

}

From source file:net.lightbody.bmp.proxy.jetty.http.handler.DumpHandler.java

public void handle(String pathInContext, String pathParams, HttpRequest request, HttpResponse response)
        throws HttpException, IOException {
    if (!isStarted())
        return;/*from w  w w. j a  v a  2 s. co  m*/

    // Only handle GET, HEAD and POST
    if (!HttpRequest.__GET.equals(request.getMethod()) && !HttpRequest.__HEAD.equals(request.getMethod())
            && !HttpRequest.__POST.equals(request.getMethod()))
        return;

    log.debug("Dump");

    response.setField(HttpFields.__ContentType, HttpFields.__TextHtml);
    OutputStream out = response.getOutputStream();
    ByteArrayOutputStream buf = new ByteArrayOutputStream(2048);
    Writer writer = new OutputStreamWriter(buf, StringUtil.__ISO_8859_1);
    writer.write("<HTML><H1>Dump HttpHandler</H1>");
    writer.write("<PRE>\npath=" + request.getPath() + "\ncontextPath=" + getHttpContext().getContextPath()
            + "\npathInContext=" + pathInContext + "\n</PRE>\n");
    writer.write("<H3>Header:</H3><PRE>");
    writer.write(request.toString());
    writer.write("</PRE>\n<H3>Parameters:</H3>\n<PRE>");
    Set names = request.getParameterNames();
    Iterator iter = names.iterator();
    while (iter.hasNext()) {
        String name = iter.next().toString();
        List values = request.getParameterValues(name);
        if (values == null || values.size() == 0) {
            writer.write(name);
            writer.write("=\n");
        } else if (values.size() == 1) {
            writer.write(name);
            writer.write("=");
            writer.write((String) values.get(0));
            writer.write("\n");
        } else {
            for (int i = 0; i < values.size(); i++) {
                writer.write(name);
                writer.write("[" + i + "]=");
                writer.write((String) values.get(i));
                writer.write("\n");
            }
        }
    }

    String cookie_name = request.getParameter("CookieName");
    if (cookie_name != null && cookie_name.trim().length() > 0) {
        String cookie_action = request.getParameter("Button");
        try {
            Cookie cookie = new Cookie(cookie_name.trim(), request.getParameter("CookieVal"));
            if ("Clear Cookie".equals(cookie_action))
                cookie.setMaxAge(0);
            response.addSetCookie(cookie);
        } catch (IllegalArgumentException e) {
            writer.write("</PRE>\n<H3>BAD Set-Cookie:</H3>\n<PRE>");
            writer.write(e.toString());
            LogSupport.ignore(log, e);
        }
    }

    writer.write("</PRE>\n<H3>Cookies:</H3>\n<PRE>");
    Cookie[] cookies = request.getCookies();
    if (cookies != null && cookies.length > 0) {
        for (int c = 0; c < cookies.length; c++) {
            Cookie cookie = cookies[c];
            writer.write(cookie.getName());
            writer.write("=");
            writer.write(cookie.getValue());
            writer.write("\n");
        }
    }

    writer.write("</PRE>\n<H3>Attributes:</H3>\n<PRE>");
    Enumeration attributes = request.getAttributeNames();
    if (attributes != null && attributes.hasMoreElements()) {
        while (attributes.hasMoreElements()) {
            String attr = attributes.nextElement().toString();
            writer.write(attr);
            writer.write("=");
            writer.write(request.getAttribute(attr).toString());
            writer.write("\n");
        }
    }

    writer.write("</PRE>\n<H3>Content:</H3>\n<PRE>");
    byte[] content = new byte[4096];
    int len;
    try {
        InputStream in = request.getInputStream();
        while ((len = in.read(content)) >= 0)
            writer.write(new String(content, 0, len));
    } catch (IOException e) {
        LogSupport.ignore(log, e);
        writer.write(e.toString());
    }

    // You wouldn't normally set a trailer like this, but
    // we don't want to commit the output to force trailers as
    // it makes test harness messy
    request.getAcceptableTransferCodings();

    // commit now
    writer.flush();
    response.setIntField(HttpFields.__ContentLength, buf.size() + 1000);
    buf.writeTo(out);
    out.flush();

    // Now add the response
    buf.reset();
    writer.write("</PRE>\n<H3>Response:</H3>\n<PRE>");
    writer.write(response.toString());
    writer.write("</PRE></HTML>");
    writer.flush();
    for (int pad = 998 - buf.size(); pad-- > 0;)
        writer.write(" ");
    writer.write("\015\012");
    writer.flush();
    buf.writeTo(out);

    request.setHandled(true);
}

From source file:org.apache.archiva.redback.integration.util.AutoLoginCookies.java

public void setRememberMeCookie(String principal, HttpServletResponse httpServletResponse,
        HttpServletRequest httpServletRequest) {
    if (!isRememberMeEnabled()) {
        return;//from w w w .j  a  v a  2 s  .c  om
    }

    try {
        CookieSettings settings = securitySystem.getPolicy().getRememberMeCookieSettings();
        int timeout = settings.getCookieTimeout();
        KeyManager keyManager = securitySystem.getKeyManager();
        AuthenticationKey authkey = keyManager.createKey(principal, "Remember Me Key", timeout);

        Cookie cookie = createCookie(REMEMBER_ME_KEY, authkey.getKey(), settings.getDomain(),
                settings.getPath(), httpServletRequest);
        if (timeout > 0) {
            cookie.setMaxAge(timeout);
        }
        httpServletResponse.addCookie(cookie);

    } catch (KeyManagerException e) {
        log.warn("Unable to set remember me cookie.");
    }
}

From source file:com.haulmont.idp.controllers.IdpController.java

@PostMapping(value = "/auth", produces = "application/json; charset=UTF-8")
@ResponseBody/*from  w  ww  .j av a  2 s  . co m*/
public AuthResponse authenticate(@RequestBody AuthRequest auth,
        @CookieValue(value = CUBA_IDP_COOKIE_NAME, defaultValue = "") String idpSessionCookie,
        HttpServletResponse response) {
    String serviceProviderUrl = auth.getServiceProviderUrl();

    if (!Strings.isNullOrEmpty(serviceProviderUrl)
            && !idpConfig.getServiceProviderUrls().contains(serviceProviderUrl)) {
        log.warn("Incorrect serviceProviderUrl {} passed, will be used default", serviceProviderUrl);
        serviceProviderUrl = null;
    }

    if (Strings.isNullOrEmpty(serviceProviderUrl)) {
        if (!idpConfig.getServiceProviderUrls().isEmpty()) {
            serviceProviderUrl = idpConfig.getServiceProviderUrls().get(0);
        } else {
            log.error("IDP property cuba.idp.serviceProviderUrls is not set");
            response.setStatus(HttpStatus.INTERNAL_SERVER_ERROR.value());
            return null;
        }
    }

    Locale sessionLocale = null;
    if (globalConfig.getLocaleSelectVisible() && auth.getLocale() != null) {
        Map<String, Locale> availableLocales = globalConfig.getAvailableLocales();
        Locale requestedLocale = Locale.forLanguageTag(auth.getLocale());

        if (availableLocales.containsValue(requestedLocale)) {
            sessionLocale = requestedLocale;
        }
    }
    if (sessionLocale == null) {
        sessionLocale = messageTools.getDefaultLocale();
    }

    if (!Strings.isNullOrEmpty(idpSessionCookie)) {
        boolean loggedOut = idpService.logout(idpSessionCookie);

        if (loggedOut) {
            log.info("Logged out IDP session {}", idpSessionCookie);

            logoutCallbackInvoker.performLogoutOnServiceProviders(idpSessionCookie);
        }
    }

    IdpService.IdpLoginResult loginResult;
    try {
        loginResult = idpService.login(auth.getUsername(), passwordEncryption.getPlainHash(auth.getPassword()),
                sessionLocale, ImmutableMap.of(ClientType.class.getName(), ClientType.WEB.name()));
    } catch (LoginException e) {
        // remove auth cookie
        Cookie cookie = new Cookie(CUBA_IDP_COOKIE_NAME, "");
        cookie.setMaxAge(0);
        response.addCookie(cookie);

        log.warn("Unable to login user {}", auth.getUsername());
        return AuthResponse.failed("invalid_credentials");
    }

    if (loginResult.getSessionId() != null) {
        Cookie idpCookie = new Cookie(CUBA_IDP_COOKIE_NAME, loginResult.getSessionId());
        idpCookie.setMaxAge(idpConfig.getIdpCookieMaxAge());
        idpCookie.setHttpOnly(idpConfig.getIdpCookieHttpOnly());
        response.addCookie(idpCookie);
    }

    String serviceProviderRedirectUrl;
    try {
        URIBuilder uriBuilder = new URIBuilder(serviceProviderUrl);

        if ("client-ticket".equals(auth.getResponseType())) {
            uriBuilder.setFragment(CUBA_IDP_TICKET_PARAMETER + "=" + loginResult.getServiceProviderTicket());
        } else {
            uriBuilder.setParameter(CUBA_IDP_TICKET_PARAMETER, loginResult.getServiceProviderTicket());
        }

        serviceProviderRedirectUrl = uriBuilder.build().toString();
    } catch (URISyntaxException e) {
        return AuthResponse.failed("invalid_params");
    }

    log.info("Logged in IDP session with ticket {}, user: {}", loginResult.getServiceProviderTicket(),
            auth.getUsername());

    return AuthResponse.authenticated(serviceProviderRedirectUrl);
}

From source file:de.metas.procurement.webui.service.impl.LoginRememberMeService.java

private void removeRememberMeCookie() {
    try {//  ww w .j a  v  a 2 s.  co m
        Cookie cookie = getRememberMeCookie();
        if (cookie == null) {
            return;
        }

        cookie = new Cookie(COOKIENAME_RememberMe, null);
        cookie.setValue(null);
        cookie.setMaxAge(0); // by setting the cookie maxAge to 0 it will deleted immediately
        cookie.setPath("/");
        VaadinService.getCurrentResponse().addCookie(cookie);

        logger.debug("Cookie removed");
    } catch (final Exception e) {
        logger.warn("Failed removing the cookie", e);
    }
}

From source file:com.shenit.commons.utils.HttpUtils.java

/**
 * ?cookie/*  www . j  a v  a  2s.  c  o m*/
 * 
 * @param req
 *            
 * @param names
 *            cookie??
 */
public static void purgeCookies(HttpServletRequest req, HttpServletResponse resp, String... names) {
    Set<String> nameSet = ValidationUtils.isEmpty(names) ? null : new HashSet<String>(Arrays.asList(names));
    boolean removeAll = ValidationUtils.isEmpty(nameSet);
    for (Cookie cookie : req.getCookies()) {
        if (removeAll || nameSet.contains(cookie.getName())) {
            cookie.setMaxAge(0);
            cookie.setValue(null);
            resp.addCookie(cookie);
            if (!removeAll)
                nameSet.remove(cookie.getName());
            ;
        }
    }
}

From source file:org.sakaiproject.metaobj.utils.mvc.impl.servlet.FormControllerImpl.java

protected ModelAndView onSubmit(HttpServletRequest request, HttpServletResponse response, Object command,
        BindException errors) throws Exception {

    Map requestMap = HttpServletHelper.getInstance().createRequestMap(request);
    Map session = HttpServletHelper.getInstance().createSessionMap(request);
    Map application = HttpServletHelper.getInstance().createApplicationMap(request);

    ModelAndView returnedMv;/*w w  w. j  a  v  a  2s  .c om*/

    if (controller instanceof CancelableController
            && ((CancelableController) controller).isCancel(requestMap)) {
        returnedMv = ((CancelableController) controller).processCancel(requestMap, session, application,
                command, errors);
    } else {
        returnedMv = controller.handleRequest(command, requestMap, session, application, errors);
    }

    boolean saveCookies = ServerConfigurationService.getBoolean(PROP_SAVE_COOKIES, false);

    if (errors.hasErrors()) {
        logger.debug("Form submission errors: " + errors.getErrorCount());
        HttpServletHelper.getInstance().reloadApplicationMap(request, application);
        HttpServletHelper.getInstance().reloadSessionMap(request, session);
        HttpServletHelper.getInstance().reloadRequestMap(request, requestMap);
        if (saveCookies) {
            Cookie cookie = new Cookie(FormHelper.FORM_SAVE_ATTEMPT, "yes");
            cookie.setMaxAge(30);
            cookie.setPath("/");
            response.addCookie(cookie);
        }
        return showForm(request, response, errors);
    }

    if (returnedMv.getViewName() != null) {
        // should get from mappings
        String mappedView = (String) screenMappings.get(returnedMv.getViewName());

        if (mappedView == null) {
            mappedView = returnedMv.getViewName();
        }

        //getControllerFilterManager().processFilters(requestMap, session, application, returnedMv, mappedView);

        returnedMv = new ModelAndView(mappedView, returnedMv.getModel());
    }

    //We have a successful save coming back, so we set/append to a cookie
    String savedForm = (String) session.get(FormHelper.FORM_SAVE_SUCCESS);
    if (savedForm != null && saveCookies) {
        Cookie cookie = null;
        if (request.getCookies() != null) {
            for (Cookie c : request.getCookies()) {
                if (FormHelper.FORM_SAVE_SUCCESS.equals(c.getName())) {
                    String[] forms = c.getValue().split(",");
                    StringBuilder value = new StringBuilder();
                    boolean alreadyIncluded = false;
                    for (String form : forms) {
                        if (form.equals(savedForm)) {
                            alreadyIncluded = true;
                        }
                        value.append(",").append(form);
                    }
                    if (!alreadyIncluded) {
                        value.append(",").append(savedForm);
                    }
                    cookie = new Cookie(FormHelper.FORM_SAVE_SUCCESS, value.substring(1));
                }
            }
        }
        if (cookie == null) {
            cookie = new Cookie(FormHelper.FORM_SAVE_SUCCESS, savedForm);
        }
        cookie.setMaxAge(2000000);
        cookie.setPath("/");
        response.addCookie(cookie);
    }

    HttpServletHelper.getInstance().reloadApplicationMap(request, application);
    HttpServletHelper.getInstance().reloadSessionMap(request, session);
    HttpServletHelper.getInstance().reloadRequestMap(request, requestMap);

    return returnedMv;
}

From source file:com.swdouglass.joid.consumer.OpenIdFilter.java

@Override
public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain)
        throws IOException, ServletException {
    // basically just check for openId parameters
    HttpServletRequest request = (HttpServletRequest) servletRequest;
    if (servletRequest.getParameter(OPENID_ATTRIBUTE) != null && !ignored(request)) {
        try {//from  w  w w. ja v  a 2s.  com
            @SuppressWarnings("unchecked")
            AuthenticationResult result = joid
                    .authenticate(convertToStringValueMap(servletRequest.getParameterMap()));
            String identity = result.getIdentity();
            if (identity != null) {
                HttpServletRequest req = (HttpServletRequest) servletRequest;
                req.getSession(true).setAttribute(OpenIdFilter.OPENID_ATTRIBUTE, identity);
                HttpServletResponse resp = (HttpServletResponse) servletResponse; // could check this before setting
                Cookie cookie = new Cookie(OPENID_ATTRIBUTE, identity);
                if (cookieDomain != null) {
                    cookie.setDomain(cookieDomain);
                }
                if (cookieMaxAge != null) {
                    cookie.setMaxAge(cookieMaxAge);
                }
                resp.addCookie(cookie);
                // redirect to get rid of the long url
                resp.sendRedirect(result.getResponse().getReturnTo());
                return;
            }
        } catch (AuthenticationException e) {
            e.printStackTrace();
            log.info("auth failed: " + e.getMessage());
            // should this be handled differently?
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
    filterChain.doFilter(servletRequest, servletResponse);
}

From source file:com.byd.test.actions.OrderAction.java

License:asdf

@RequestMapping("createCookie")
public void createCookie(HttpServletResponse response) {
    System.out.println("cookie start");
    Cookie cookie = new Cookie("cookie_name", "whatisthis");
    cookie.setHttpOnly(Boolean.TRUE);
    cookie.setDomain("chengangxiong");
    cookie.setVersion(1);// w  w w. jav  a2  s .  co  m
    cookie.setMaxAge(15);//15
    response.addCookie(cookie);

}

From source file:gr.abiss.calipso.userDetails.util.SecurityUtil.java

/**
 * Writes a cookie to the response. In case of a blank value the method will 
 * set the max age to zero, effectively marking the cookie for immediate 
 * deletion by the client if the <code>allowClear</code> is true or throw an exception if false.
 * Blank value strings mark cookie deletion. If 
 * @param response/*w  w  w .  ja va2  s.com*/
 * @param cookieName
 * @param cookieValue
 * @param allowClear
 */
private static void addCookie(HttpServletRequest request, HttpServletResponse response, String cookieName,
        String cookieValue, boolean allowClear, UserDetailsConfig userDetailsConfig) {
    if (StringUtils.isBlank(cookieValue) && !allowClear) {
        throw new RuntimeException(
                "Was given a blank cookie value but allowClear is false for cookie name: " + cookieName);
    }

    if (LOGGER.isDebugEnabled()) {
        LOGGER.debug("addCookie, cookieName: " + cookieName + ", cookie value: " + cookieValue + ", domain: "
                + userDetailsConfig.getCookiesDomain() + ", secure: " + userDetailsConfig.isCookiesSecure()
                + ", http-only: " + userDetailsConfig.isCookiesHttpOnly() + ", path: "
                + userDetailsConfig.getCookiesContextPath());
    }
    Cookie cookie = new Cookie(cookieName, cookieValue);

    // set the cookie domain
    if (StringUtils.isNotBlank(userDetailsConfig.getCookiesDomain())) {
        cookie.setDomain('.' + userDetailsConfig.getCookiesDomain());
    }
    // maybe not a good idea unless you can trust the proxy
    //      else if (StringUtils.isNotBlank(request.getHeader("X-Forwarded-Host"))) {
    //         cookie.setDomain('.' + request.getHeader("X-Forwarded-Host"));
    //      }
    //      else{
    //         cookie.setDomain('.' + request.getLocalName());
    //         
    //      }
    // set the cookie path
    if (StringUtils.isNotBlank(userDetailsConfig.getCookiesContextPath())) {
        cookie.setPath(userDetailsConfig.getCookiesContextPath());
    }
    //      else {
    //         cookie.setPath("/");
    //      }

    cookie.setSecure(userDetailsConfig.isCookiesSecure());
    cookie.setHttpOnly(userDetailsConfig.isCookiesHttpOnly());

    if (StringUtils.isBlank(cookieValue)) {
        if (LOGGER.isDebugEnabled()) {
            LOGGER.debug("addCookie, setting max-age to 0 to clear cookie: " + cookieName);
        }
        cookie.setMaxAge(0);
    }
    response.addCookie(cookie);
}