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.sslexplorer.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 .jav  a 2  s. c o  m*/
    request.getSession().setAttribute(Constants.SESSION_INFO, info);
    try {
        String sessionIdentifier = SystemProperties.get("sslexplorer.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;
}

From source file:com.adito.security.DefaultLogonController.java

public void addCookies(RequestHandlerRequest request, RequestHandlerResponse response, String logonTicket,
        SessionInfo session) {//from  w w  w.jav a2s  . co  m

    if (request.getAttribute("sslx.logon.cookie") != null)
        return;

    /**
     * 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.getField("Host");
    if (host != null) {
        HostService hostService = new HostService(host);
        cookie2.setDomain(hostService.getHost());
    }
    cookie2.setSecure(true);
    response.addCookie(cookie2);

    request.setAttribute("sslx.logon.cookie", new Object());

    /**
     * LDP - This code was not setting the domain on the ticket. I've
     * converted to the new format of having two seperate tickets to ensure
     * tickets are sent across domains
     */
    /*
     * Cookie cookie = new Cookie(Constants.LOGON_TICKET, logonTicket); try {
     * cookie.setMaxAge(Integer.parseInt(CoreServlet.getServlet().getPropertyDatabase().getProperty(0,
     * null, "security.session.maxCookieAge"))); if
     * ("true".equals(CoreServlet.getServlet().getPropertyDatabase().getProperty(0,
     * null, "security.session.lockSessionOnBrowserClose"))) { if
     * (log.isInfoEnabled()) log.info("New session - will force the user to
     * authenticate again"); // initialiseSession(request.getSession(),
     * user); // List profiles = //
     * CoreServlet.getServlet().getPropertyDatabase().getPropertyProfiles(user.getUsername(), //
     * false); // request.getSession().setAttribute(Constants.PROFILES, //
     * profiles);
     * request.getSession().setAttribute(Constants.SESSION_LOCKED, user); } }
     * catch (Exception e) { log.error(e); cookie.setMaxAge(900); }
     * cookie.setPath("/"); cookie.setSecure(true);
     * response.addCookie(cookie);
     */
    //
}

From source file:org.slc.sli.dashboard.security.SLIAuthenticationEntryPoint.java

private boolean checkCookiesForToken(HttpServletRequest request, HttpSession session) {
    boolean cookieFound = false;

    // If there is no oauth credential, and the user has a dashboard cookie, add cookie value as
    // oauth session attribute.
    if (session.getAttribute(OAUTH_TOKEN) == null) {
        Cookie[] cookies = request.getCookies();

        if (cookies != null) {

            // Loop through cookies to find dashboard cookie
            for (Cookie c : cookies) {
                if (c.getName().equals(DASHBOARD_COOKIE)) {

                    // DE883. We need to decrypt the cookie value to authenticate the token.
                    String decryptedCookie = null;
                    try {
                        String s = URLDecoder.decode(c.getValue(), "UTF-8");
                        decryptedCookie = propDecryptor.decrypt(s);
                    } catch (Exception e) {
                        LOG.error(e.getMessage());
                    }/*  w  w  w . j a v  a  2  s.c om*/
                    JsonObject json = restClient.sessionCheck(decryptedCookie);

                    // If user is not authenticated, expire the cookie, else set OAUTH_TOKEN to
                    // cookie value and continue
                    JsonElement authElement = json.get(Constants.ATTR_AUTHENTICATED);
                    if ((authElement != null) && (!authElement.getAsBoolean())) {
                        c.setMaxAge(0);
                        LOG.info(LOG_MESSAGE_AUTH_EXPIRING_COOKIE, new Object[] { request.getRemoteAddr() });
                    } else {
                        cookieFound = true;
                        session.setAttribute(OAUTH_TOKEN, decryptedCookie);
                        LOG.info(LOG_MESSAGE_AUTH_USING_COOKIE, new Object[] { request.getRemoteAddr() });
                    }

                }
            }
        }
    }

    return cookieFound;
}

From source file:com.medallia.spider.SpiderServlet.java

private RequestHandler makeRequest(HttpServletRequest req, final HttpServletResponse response) {
    final Map<String, String> m = Empty.hashMap();
    Cookie[] cookies = req.getCookies();
    if (cookies != null) {
        for (Cookie c : cookies) {
            addCookie(m, c);/*from  w  ww .ja  v a2 s . c om*/
        }
    }
    return new RequestHandler() {
        @Implement
        public String getCookieValue(String name) {
            return m.get(name);
        }

        @Implement
        public void setCookieValue(String name, String value) {
            storeCookie(makeCookie(name, value));
        }

        @Implement
        public void setPersistentCookieValue(String name, String value, int expiry) {
            if (expiry <= 0)
                throw new IllegalArgumentException("expiry must be a positive number: " + expiry);

            Cookie c = makeCookie(name, value);
            c.setMaxAge(expiry);
            storeCookie(c);
        }

        @Implement
        public void removeCookieValue(String name) {
            Cookie c = makeCookie(name, null);
            c.setMaxAge(0);
            storeCookie(c);
        }

        private void storeCookie(Cookie c) {
            response.addCookie(c);
            addCookie(m, c);
        }

        private Cookie makeCookie(String name, String value) {
            return new Cookie(name, value);
        }
    };
}

From source file:org.openmhealth.reference.servlet.Version1.java

/**
 * Creates an authentication request, authenticates the user and, if
 * successful, returns the user's credentials.
 * //ww  w. j a  v a 2 s.com
 * @param username
 *        The username of the user attempting to authenticate.
 * 
 * @param password
 *        The password of the user attempting to authenticate.
 * 
 * @param request
 *        The HTTP request object.
 * 
 * @param response
 *        The HTTP response object.
 * 
 * @return The authorization token.
 * 
 * @throws OmhException
 *         There was a problem with the request. This could be any of the
 *         sub-classes of {@link OmhException}.
 */
@RequestMapping(value = "auth", method = RequestMethod.POST)
public @ResponseBody String getAuthentication(
        @RequestParam(value = PARAM_AUTHENTICATION_USERNAME, required = true) final String username,
        @RequestParam(value = PARAM_AUTHENTICATION_PASSWORD, required = true) final String password,
        final HttpServletRequest request, final HttpServletResponse response) throws OmhException {

    // Create the authentication request from parameters.
    AuthenticationToken token = handleRequest(request, response, new AuthenticationRequest(username, password));

    // Add a cookie for the authentication token.
    Cookie cookie = new Cookie(PARAM_AUTHENTICATION_AUTH_TOKEN, token.getToken());
    // Set the expiration on the cookie.
    cookie.setMaxAge(new Long((token.getExpires() - System.currentTimeMillis()) / 1000).intValue());
    // Build the path without the "auth" part.
    String requestUri = request.getRequestURI();
    cookie.setPath(requestUri.substring(0, requestUri.length() - 5));
    // Make sure the cookie is only used with HTTPS.
    cookie.setSecure(true);
    // Add the cookie to the response.
    response.addCookie(cookie);

    // Return the token.
    return token.getToken();
}

From source file:com.konakart.actions.BaseAction.java

/**
 * Utility method to get the CustomerUuid from the browser cookie and create the cookie if it
 * doesn't exist./*from   ww w  .  jav a 2 s.c o m*/
 * 
 * @param request
 * @return Returns the CustomerUuid
 */
private String getCustomerUuidFromBrowserCookie(HttpServletRequest request, HttpServletResponse response) {
    /*
     * Try to find the cookie we are looking for
     */
    Cookie[] cookies = request.getCookies();
    String uuid = null;
    if (cookies != null) {
        for (int i = 0; i < cookies.length; i++) {
            Cookie cookie = cookies[i];
            String cookieName = cookie.getName();
            if (cookieName.equals(CUSTOMER_UUID)) {
                /*
                 * If we find the cookie we get the value and update the max age.
                 */
                uuid = cookie.getValue();
                cookie.setMaxAge(COOKIE_MAX_AGE_IN_SECS);
                cookie.setPath("/");
                response.addCookie(cookie);
            }
        }
    }

    /*
     * If the browser cookie doesn't exist then we have to create it and store a newly created
     * UUID string
     */
    if (uuid == null) {
        UUID uuidObject = UUID.randomUUID();
        uuid = uuidObject.toString();
        /*
         * Create a browser cookie with the UUID
         */
        Cookie uuidCookie = new Cookie(CUSTOMER_UUID, uuid);
        uuidCookie.setMaxAge(COOKIE_MAX_AGE_IN_SECS);
        uuidCookie.setPath("/");
        response.addCookie(uuidCookie);
    }

    return uuid;
}

From source file:com.openvcx.webcall.ConferenceCreateServlet.java

/**
 * <p>Lookup a client conference number stored in a cookie. If no phone number is provided by the client a random SIP URI phone number is automatically generated.</p>
 * <p>A conference definition template file is used to create the conference definition for the phone number.</p>
 * <p>The auto-assigned phone number is then stored in a cookie and returned to the client.</p>
 * @param out standard output Output writer
 * @param request The HTTP request object
 * @param response The HTTP response object
 *//*from w  ww  . j a va  2  s. c om*/
private boolean doCreateNumber(PrintWriter out, HttpServletRequest request, HttpServletResponse response)
        throws IOException {
    String strOutputNumber = null;

    Cookie[] arrCookies = request.getCookies();
    if (null != arrCookies) {
        for (Cookie cookie : arrCookies) {
            //logger.debug("cookie name: " + cookie.getName() + ", path: " + cookie.getPath() + ", domain: " + cookie.getDomain() + ", maxAge: " + cookie.getMaxAge() + ", value: " + cookie.getValue());
            if (COOKIE_NUMBER_KEY.equals(cookie.getName())) {
                if (null != (strOutputNumber = cookie.getValue()) && strOutputNumber.length() == 0) {
                    strOutputNumber = null;
                }
                logger.debug("Using cookie stored conference output number: '" + strOutputNumber + "'.");
                break;
            }
        }
    }

    strOutputNumber = createConferenceDefinition(strOutputNumber);

    if (null != strOutputNumber) {

        int cookieAgeDays = 7;
        Cookie cookie = new Cookie(COOKIE_NUMBER_KEY, strOutputNumber);
        cookie.setMaxAge(cookieAgeDays * SECONDS_IN_DAY);
        cookie.setPath("/" + getUriDirSegment(request.getRequestURI(), 0) + "/");
        logger.debug("Setting cookie " + COOKIE_NUMBER_KEY + "=" + strOutputNumber);
        response.addCookie(cookie);
        out.println("number=" + strOutputNumber);
    }

    return true;
}

From source file:io.restassured.module.mockmvc.internal.MockMvcRequestSenderImpl.java

private MockMvcResponse sendRequest(HttpMethod method, String path, Object[] pathParams) {
    notNull(path, "Path");
    if (requestBody != null && !multiParts.isEmpty()) {
        throw new IllegalStateException(
                "You cannot specify a request body and a multi-part body in the same request. Perhaps you want to change the body to a multi part?");
    }//from   w  w w.j a  v  a2 s . co  m

    String baseUri;
    if (isNotBlank(basePath)) {
        baseUri = mergeAndRemoveDoubleSlash(basePath, path);
    } else {
        baseUri = path;
    }

    final UriComponentsBuilder uriComponentsBuilder = UriComponentsBuilder.fromUriString(baseUri);
    if (!queryParams.isEmpty()) {
        new ParamApplier(queryParams) {
            @Override
            protected void applyParam(String paramName, String[] paramValues) {
                uriComponentsBuilder.queryParam(paramName, paramValues);
            }
        }.applyParams();
    }
    String uri = uriComponentsBuilder.build().toUriString();

    final MockHttpServletRequestBuilder request;
    if (multiParts.isEmpty()) {
        request = MockMvcRequestBuilders.request(method, uri, pathParams);
    } else if (method != POST) {
        throw new IllegalArgumentException("Currently multi-part file data uploading only works for " + POST);
    } else {
        request = MockMvcRequestBuilders.fileUpload(uri, pathParams);
    }

    String requestContentType = findContentType();

    if (!params.isEmpty()) {
        new ParamApplier(params) {
            @Override
            protected void applyParam(String paramName, String[] paramValues) {
                request.param(paramName, paramValues);
            }
        }.applyParams();

        if (StringUtils.isBlank(requestContentType) && method == POST && !isInMultiPartMode(request)) {
            setContentTypeToApplicationFormUrlEncoded(request);
        }
    }

    if (!formParams.isEmpty()) {
        if (method == GET) {
            throw new IllegalArgumentException("Cannot use form parameters in a GET request");
        }
        new ParamApplier(formParams) {
            @Override
            protected void applyParam(String paramName, String[] paramValues) {
                request.param(paramName, paramValues);
            }
        }.applyParams();

        boolean isInMultiPartMode = isInMultiPartMode(request);
        if (StringUtils.isBlank(requestContentType) && !isInMultiPartMode) {
            setContentTypeToApplicationFormUrlEncoded(request);
        }
    }

    if (!attributes.isEmpty()) {
        new ParamApplier(attributes) {
            @Override
            protected void applyParam(String paramName, String[] paramValues) {
                request.requestAttr(paramName, paramValues[0]);
            }
        }.applyParams();
    }

    if (RestDocsClassPathChecker.isSpringRestDocsInClasspath()
            && config.getMockMvcConfig().shouldAutomaticallyApplySpringRestDocsMockMvcSupport()) {
        request.requestAttr(ATTRIBUTE_NAME_URL_TEMPLATE, PathSupport.getPath(uri));
    }

    if (StringUtils.isNotBlank(requestContentType)) {
        request.contentType(MediaType.parseMediaType(requestContentType));
    }

    if (headers.exist()) {
        for (Header header : headers) {
            request.header(header.getName(), header.getValue());
        }
    }

    if (cookies.exist()) {
        for (Cookie cookie : cookies) {
            javax.servlet.http.Cookie servletCookie = new javax.servlet.http.Cookie(cookie.getName(),
                    cookie.getValue());
            if (cookie.hasComment()) {
                servletCookie.setComment(cookie.getComment());
            }
            if (cookie.hasDomain()) {
                servletCookie.setDomain(cookie.getDomain());
            }
            if (cookie.hasMaxAge()) {
                servletCookie.setMaxAge(cookie.getMaxAge());
            }
            if (cookie.hasPath()) {
                servletCookie.setPath(cookie.getPath());
            }
            if (cookie.hasVersion()) {
                servletCookie.setVersion(cookie.getVersion());
            }
            servletCookie.setSecure(cookie.isSecured());
            request.cookie(servletCookie);
        }
    }

    if (!sessionAttributes.isEmpty()) {
        request.sessionAttrs(sessionAttributes);
    }

    if (!multiParts.isEmpty()) {
        MockMultipartHttpServletRequestBuilder multiPartRequest = (MockMultipartHttpServletRequestBuilder) request;
        for (MockMvcMultiPart multiPart : multiParts) {
            MockMultipartFile multipartFile;
            String fileName = multiPart.getFileName();
            String controlName = multiPart.getControlName();
            String mimeType = multiPart.getMimeType();
            if (multiPart.isByteArray()) {
                multipartFile = new MockMultipartFile(controlName, fileName, mimeType,
                        (byte[]) multiPart.getContent());
            } else if (multiPart.isFile() || multiPart.isInputStream()) {
                InputStream inputStream;
                if (multiPart.isFile()) {
                    try {
                        inputStream = new FileInputStream((File) multiPart.getContent());
                    } catch (FileNotFoundException e) {
                        return SafeExceptionRethrower.safeRethrow(e);
                    }
                } else {
                    inputStream = (InputStream) multiPart.getContent();
                }
                try {
                    multipartFile = new MockMultipartFile(controlName, fileName, mimeType, inputStream);
                } catch (IOException e) {
                    return SafeExceptionRethrower.safeRethrow(e);
                }
            } else { // String
                multipartFile = new MockMultipartFile(controlName, fileName, mimeType,
                        ((String) multiPart.getContent()).getBytes());
            }
            multiPartRequest.file(multipartFile);
        }
    }

    if (requestBody != null) {
        if (requestBody instanceof byte[]) {
            request.content((byte[]) requestBody);
        } else if (requestBody instanceof File) {
            byte[] bytes = toByteArray((File) requestBody);
            request.content(bytes);
        } else {
            request.content(requestBody.toString());
        }
    }

    logRequestIfApplicable(method, baseUri, path, pathParams);

    return performRequest(request);
}

From source file:com.adito.security.DefaultLogonController.java

public void logoffSession(HttpServletRequest request, HttpServletResponse response)
        throws SecurityErrorException {
    if (log.isInfoEnabled())
        log.info("Logging off session " + request.getSession().getId());
    if (request.getSession().getAttribute(Constants.LOGON_TICKET) == null) {
        throw new SecurityErrorException(SecurityErrorException.INTERNAL_ERROR,
                "The current session does not contain a logon ticket");
    } else {// www. j a  v  a  2 s.  c om
        String ticket = (String) request.getSession().getAttribute(Constants.LOGON_TICKET);
        SessionInfo session = getSessionInfo(ticket);
        logoff(ticket);

        if (request.getCookies() != null) {
            for (int i = 0; i < request.getCookies().length; i++) {
                Cookie cookie = request.getCookies()[i];
                if (cookie.getName().equals(Constants.LOGON_TICKET)
                        || cookie.getName().equals(Constants.DOMAIN_LOGON_TICKET)) {
                    cookie.setMaxAge(0);
                    response.addCookie(cookie);
                }
            }
        }
        request.getSession().removeAttribute(Constants.LOGON_TICKET);
        session.invalidate();
    }
}

From source file:com.kodemore.servlet.ScServletData.java

public void setTimeoutCookie(String name, String value, int seconds) {
    value = Kmu.encodeUtf8(value);/*  w  ww .j a va 2 s.  c  o m*/

    Cookie c;
    c = new Cookie(name, value);
    c.setMaxAge(seconds);

    _setCookie(c);
}