Example usage for javax.servlet.http Cookie setDomain

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

Introduction

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

Prototype

public void setDomain(String domain) 

Source Link

Document

Specifies the domain within which this cookie should be presented.

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 w w . j  a va  2  s.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.tremolosecurity.proxy.SessionManagerImpl.java

@Override
public void writeSession(UrlHolder holder, TremoloHttpSession session, HttpServletRequest request,
        HttpServletResponse response) throws IOException {
    /*//from  ww  w .  ja  v a 2 s  .c  o m
     * 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:axiom.servlet.AbstractServletClient.java

/**
 * Create a new session cookie.//  ww w  .  j av a2s.co m
 *
 * @param b
 * @param reqtrans
 * @param domain
 * @return the session cookie
 */
private Cookie createSessionCookie(StringBuffer b, RequestTrans reqtrans, String domain) {
    b.append(Long.toString(Math.round(Math.random() * Long.MAX_VALUE) - System.currentTimeMillis(), 36));

    reqtrans.setSession(b.toString());
    Cookie cookie = new Cookie(sessionCookieName, reqtrans.getSession());

    cookie.setPath("/");

    if (domain != null) {
        cookie.setDomain(domain);
    }

    return cookie;
}

From source file:com.liferay.portal.util.HttpImpl.java

protected Cookie toServletCookie(org.apache.commons.httpclient.Cookie commonsCookie) {

    Cookie cookie = new Cookie(commonsCookie.getName(), commonsCookie.getValue());

    String domain = commonsCookie.getDomain();

    if (Validator.isNotNull(domain)) {
        cookie.setDomain(domain);
    }//from   w  w w.  ja va2s.c  o m

    Date expiryDate = commonsCookie.getExpiryDate();

    if (expiryDate != null) {
        int maxAge = (int) (expiryDate.getTime() - System.currentTimeMillis());

        maxAge = maxAge / 1000;

        if (maxAge > -1) {
            cookie.setMaxAge(maxAge);
        }
    }

    String path = commonsCookie.getPath();

    if (Validator.isNotNull(path)) {
        cookie.setPath(path);
    }

    cookie.setSecure(commonsCookie.getSecure());
    cookie.setVersion(commonsCookie.getVersion());

    return cookie;
}

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  ww .j  av a2s . c o  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.google.gsa.valve.modules.httpbasic.HTTPBasicAuthenticationProcess.java

/**
 * This is the main method that does the authentication and should be 
 * invoked by the classes that would like to open a new authentication 
 * process against an HTTP Basic protected source.
 * <p>/*w  w  w .ja v a 2  s .  co m*/
 * The username and password for the source are assumed to be the ones 
 * captured during the authentication. These are stored in creds and in 
 * this case the root parameters. creds is an array of credentials for 
 * all external sources. The first element is 'root' which contains the 
 * credentials captured from the login page. This method reviews if there 
 * is a credential id identical to the name associated to this module 
 * in the config file. If so, these credentials are used to authenticate 
 * against this HTTP Basic source, and if not 'root' one will be used 
 * instead.
 * <p>
 * If the HTTP Basic authentication result is OK, it creates an 
 * authentication cookie containing the HTTP Basic credentials 
 * to be reused during authorization. The content returned back from the 
 * remote secure backend system is sent as well. Anyway, the HTTP 
 * response code is returned in this method to inform the caller on the 
 * status.
 * 
 * @param request HTTP request
 * @param response HTTP response
 * @param authCookies vector that contains the authentication cookies
 * @param url the document url
 * @param creds an array of credentials for all external sources
 * @param id the default credential id to be retrieved from creds
        
 * @return the HTTP error code
        
 * @throws HttpException
 * @throws IOException
 */
public int authenticate(HttpServletRequest request, HttpServletResponse response, Vector<Cookie> authCookies,
        String url, Credentials creds, String id) throws HttpException, IOException {

    Cookie[] cookies = null;

    //Credentials                     
    UsernamePasswordCredentials credentials = null;

    // Initialize status code
    int statusCode = HttpServletResponse.SC_UNAUTHORIZED;

    // Read cookies
    cookies = request.getCookies();

    // Debug
    logger.debug("HTTP Basic authentication start");

    //First read the u/p the credentails store, in this case using the same as the root login
    logger.debug("HttpBasic: trying to get creds from repository ID: " + id);
    Credential httpBasicCred = null;
    try {
        httpBasicCred = creds.getCredential(id);
    } catch (NullPointerException npe) {
        logger.error("NPE while reading credentials of ID: " + id);
    }
    if (httpBasicCred != null) {
        credentials = new UsernamePasswordCredentials(httpBasicCred.getUsername(), httpBasicCred.getPassword());
    } else {
        logger.debug("HttpBasic: trying to get creds from repository \"root\"");
        httpBasicCred = creds.getCredential("root");
        if (httpBasicCred != null) {
            logger.info("Trying with root credentails");
            credentials = new UsernamePasswordCredentials(httpBasicCred.getUsername(),
                    httpBasicCred.getPassword());
        }
    }

    logger.debug("Authenticating");
    Header[] headers = null;
    HttpMethodBase method = null;

    //Get Max connections
    int maxConnectionsPerHost = 30;
    int maxTotalConnections = 100;

    //Cookie Max Age
    int authMaxAge = -1;

    try {
        maxConnectionsPerHost = new Integer(valveConf.getMaxConnectionsPerHost()).intValue();
        maxTotalConnections = (new Integer(valveConf.getMaxTotalConnections())).intValue();
        authMaxAge = Integer.parseInt(valveConf.getAuthMaxAge());
    } catch (NumberFormatException nfe) {
        logger.error(
                "Configuration error: chack the configuration file as the numbers set for any of the following parameters are not OK:");
        logger.error("  * maxConnectionsPerHost    * maxTotalConnections    * authMaxAge");
    }

    // Protection
    if (webProcessor == null) {
        // Instantiate Web processor
        if ((maxConnectionsPerHost != -1) && (maxTotalConnections != -1)) {
            webProcessor = new WebProcessor(maxConnectionsPerHost, maxTotalConnections);
        } else {
            webProcessor = new WebProcessor();
        }
    }

    //
    // Launch the authentication process
    //

    // A fixed URL in the repository that all users have access to which can be used to authN a user
    // and capture the HTTP Authorization Header
    String authURL = valveConf.getRepository(id).getParameterValue("HTTPAuthPage");

    try {

        // Set HTTP headers
        headers = new Header[1];

        // Set User-Agent
        headers[0] = new Header("User-Agent",
                "Mozilla/5.0 (Windows; U; Windows NT 5.1; en-US; rv:1.8) Gecko/20051111 Firefox/1.5");

        // Request page, testing if credentials are valid
        if (credentials != null) {
            logger.debug("Username: " + credentials.getUserName());
            logger.debug("URL: " + authURL);
        }

        //HTTP request
        method = webProcessor.sendRequest(credentials, RequestType.GET_REQUEST, headers, null, authURL);

        //Read the auth header and store in the cookie, the authZ class will use this later
        headers = method.getRequestHeaders();

        Header authHeader = null;
        authHeader = method.getRequestHeader("Authorization");

        // Cache status code
        if (method != null)
            statusCode = method.getStatusCode();

        if (statusCode == HttpServletResponse.SC_OK) {
            //Authentication worked, so create the auth cookie to indicate it has worked
            Cookie extAuthCookie = null;
            extAuthCookie = new Cookie(BASIC_COOKIE, "");

            if (authHeader != null) {

                String basicCookie = null;

                try {
                    basicCookie = URLEncoder.encode(getBasicAuthNChain(authHeader.getValue()), encoder);
                    if (basicCookie == null) {
                        basicCookie = "";
                    }
                } catch (Exception ex) {
                    logger.error("Error when setting Basic cookie value: " + ex.getMessage(), ex);
                    basicCookie = "";
                }

                extAuthCookie.setValue(basicCookie);

            }
            String authCookieDomain = null;
            String authCookiePath = null;

            // Cache cookie properties
            authCookieDomain = valveConf.getAuthCookieDomain();
            authCookiePath = valveConf.getAuthCookiePath();

            // Set extra cookie parameters
            extAuthCookie.setDomain(authCookieDomain);
            extAuthCookie.setPath(authCookiePath);
            extAuthCookie.setMaxAge(authMaxAge);

            // Log info
            if (logger.isDebugEnabled())
                logger.debug("Adding " + BASIC_COOKIE + " cookie: " + extAuthCookie.getName() + ":"
                        + extAuthCookie.getValue() + ":" + extAuthCookie.getPath() + ":"
                        + extAuthCookie.getDomain() + ":" + extAuthCookie.getSecure());

            //sendCookies support                        
            boolean isSessionEnabled = new Boolean(valveConf.getSessionConfig().isSessionEnabled())
                    .booleanValue();
            boolean sendCookies = false;
            if (isSessionEnabled) {
                sendCookies = new Boolean(valveConf.getSessionConfig().getSendCookies()).booleanValue();
            }
            if ((!isSessionEnabled) || ((isSessionEnabled) && (sendCookies))) {
                logger.debug("Adding cookie to response");
                response.addCookie(extAuthCookie);
            }

            //Add cookies to the Cookie array to support sessions
            authCookies.add(extAuthCookie);
            logger.debug("Cookie added to the array");

        }

        // Clear webProcessor cookies
        webProcessor.clearCookies();

    } catch (Exception e) {

        // Log error
        logger.error("HTTP Basic authentication failure: " + e.getMessage(), e);

        // Garbagge collect
        method = null;

        // Update status code
        statusCode = HttpServletResponse.SC_UNAUTHORIZED;

    }

    // End of the authentication process
    logger.debug("HTTP Basic Authentication completed (" + statusCode + ")");

    // Return status code
    return statusCode;

}

From source file:net.lightbody.bmp.proxy.jetty.jetty.servlet.AbstractSessionManager.java

public Cookie getSessionCookie(HttpSession session, boolean requestIsSecure) {
    if (_handler.isUsingCookies()) {
        Cookie cookie = _handler.getSessionManager().getHttpOnly()
                ? new HttpOnlyCookie(SessionManager.__SessionCookie, session.getId())
                : new Cookie(SessionManager.__SessionCookie, session.getId());
        String domain = _handler.getServletContext().getInitParameter(SessionManager.__SessionDomain);
        String maxAge = _handler.getServletContext().getInitParameter(SessionManager.__MaxAge);
        String path = _handler.getServletContext().getInitParameter(SessionManager.__SessionPath);
        if (path == null)
            path = getCrossContextSessionIDs() ? "/" : _handler.getHttpContext().getContextPath();
        if (path == null || path.length() == 0)
            path = "/";

        if (domain != null)
            cookie.setDomain(domain);
        if (maxAge != null)
            cookie.setMaxAge(Integer.parseInt(maxAge));
        else//www.  j a v  a 2 s . co m
            cookie.setMaxAge(-1);

        cookie.setSecure(requestIsSecure && getSecureCookies());
        cookie.setPath(path);

        return cookie;
    }
    return null;
}

From source file:com.google.gsa.Kerberos.java

/**
 * Creates the referer cookie/*w w  w. ja  v a2  s  .  c  o m*/
 * 
 */
private void createRefererCookie(Cookie gsaRefererCookie) {
    // Instantiate authentication cookie with default value
    gsaRefererCookie = new Cookie(refererCookieName, valveConf.getTestFormsCrawlUrl());

    // Set cookie domain
    gsaRefererCookie.setDomain(authCookieDomain);

    // Set cookie path
    gsaRefererCookie.setPath(authCookiePath);

    // Set expiration time
    gsaRefererCookie.setMaxAge(authMaxAge);
}

From source file:org.sakaiproject.util.RequestFilter.java

/**
 * This is called when a request is made to a node that is in the process of closing down
 * and so we don't want to allow new session to be created.
 * @param req The servlet request.// w w  w  .j ava  2  s.c o  m
 * @param res The servlet response.
 */
protected void closingRedirect(HttpServletRequest req, HttpServletResponse res) throws IOException {
    // We should avoid redirecting on non get methods as the body will be lost.
    if (!"GET".equals(req.getMethod())) {
        M_log.warn("Non GET request for " + req.getPathInfo());
    }

    // We could check that we aren't in a redirect loop here, but if the load balancer doesn't know that
    // a node is no longer responding to new sessions it may still be sending it new clients, and so after
    // a couple of redirects it should hop off this node.
    String value = getRedirectNode();
    // set the cookie
    Cookie c = new Cookie(cookieName, value);
    c.setPath("/");
    // Delete the cookie
    c.setMaxAge(0);
    if (cookieDomain != null) {
        c.setDomain(cookieDomain);
    }
    if (req.isSecure() == true) {
        c.setSecure(true);
    }
    addCookie(res, c);

    // We want the non-decoded ones so we don't have to re-encode.
    StringBuilder url = new StringBuilder(req.getRequestURI());
    if (req.getQueryString() != null) {
        url.append("?").append(req.getQueryString());
    }
    res.sendRedirect(url.toString());
}

From source file:com.twelve.capital.external.feed.util.HttpImpl.java

protected Cookie toServletCookie(org.apache.commons.httpclient.Cookie commonsCookie) {

    Cookie cookie = new Cookie(commonsCookie.getName(), commonsCookie.getValue());

    if (!PropsValues.SESSION_COOKIE_USE_FULL_HOSTNAME) {
        String domain = commonsCookie.getDomain();

        if (Validator.isNotNull(domain)) {
            cookie.setDomain(domain);
        }//www  . j  a v a  2 s  . c  o m
    }

    Date expiryDate = commonsCookie.getExpiryDate();

    if (expiryDate != null) {
        int maxAge = (int) (expiryDate.getTime() - System.currentTimeMillis());

        maxAge = maxAge / 1000;

        if (maxAge > -1) {
            cookie.setMaxAge(maxAge);
        }
    }

    String path = commonsCookie.getPath();

    if (Validator.isNotNull(path)) {
        cookie.setPath(path);
    }

    cookie.setSecure(commonsCookie.getSecure());
    cookie.setVersion(commonsCookie.getVersion());

    return cookie;
}