Example usage for javax.servlet.http Cookie setVersion

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

Introduction

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

Prototype

public void setVersion(int v) 

Source Link

Document

Sets the version of the cookie protocol that this Cookie complies with.

Usage

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

protected org.apache.commons.httpclient.Cookie toCommonsCookie(Cookie cookie) {

    org.apache.commons.httpclient.Cookie commonsCookie = new org.apache.commons.httpclient.Cookie(
            cookie.getDomain(), cookie.getName(), cookie.getValue(), cookie.getPath(), cookie.getMaxAge(),
            cookie.getSecure());//  w w w . ja va2  s  . c  om

    commonsCookie.setVersion(cookie.getVersion());

    return commonsCookie;
}

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?");
    }//  w w w. j a v  a  2 s. com

    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.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   www .jav 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;
}

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);/*from  w w  w. j av  a 2s.  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:net.lightbody.bmp.proxy.jetty.http.HttpRequest.java

/**
 * Extract received cookies from a header.
 * /*w  w  w  . j  ava2 s  .  c om*/
 * @return Array of Cookies.
 */
public Cookie[] getCookies() {
    if (_cookies != null && _cookiesExtracted)
        return _cookies;

    try {
        // Handle no cookies
        if (!_header.containsKey(HttpFields.__Cookie)) {
            _cookies = __noCookies;
            _cookiesExtracted = true;
            _lastCookies = null;
            return _cookies;
        }

        // Check if cookie headers match last cookies
        if (_lastCookies != null) {
            int last = 0;
            Enumeration enm = _header.getValues(HttpFields.__Cookie);
            while (enm.hasMoreElements()) {
                String c = (String) enm.nextElement();
                if (last >= _lastCookies.length || !c.equals(_lastCookies[last])) {
                    _lastCookies = null;
                    break;
                }
                last++;
            }
            if (_lastCookies != null) {
                _cookiesExtracted = true;
                return _cookies;
            }
        }

        // Get ready to parse cookies (Expensive!!!)
        Object cookies = null;
        Object lastCookies = null;

        int version = 0;
        Cookie cookie = null;

        // For each cookie header
        Enumeration enm = _header.getValues(HttpFields.__Cookie);
        while (enm.hasMoreElements()) {
            // Save a copy of the unparsed header as cache.
            String hdr = enm.nextElement().toString();
            lastCookies = LazyList.add(lastCookies, hdr);

            // Parse the header
            QuotedStringTokenizer tok = new QuotedStringTokenizer(hdr, ",;", false, false);
            tok.setSingle(false);
            while (tok.hasMoreElements()) {
                String c = (String) tok.nextElement();
                if (c == null)
                    continue;
                c = c.trim();

                try {
                    String n;
                    String v;
                    int e = c.indexOf('=');
                    if (e > 0) {
                        n = c.substring(0, e);
                        v = c.substring(e + 1);
                    } else {
                        n = c;
                        v = "";
                    }

                    // Handle quoted values
                    if (version > 0)
                        v = StringUtil.unquote(v);

                    // Ignore $ names
                    if (n.startsWith("$")) {
                        if ("$version".equalsIgnoreCase(n))
                            version = Integer.parseInt(QuotedStringTokenizer.unquoteDouble(v));
                        else if ("$path".equalsIgnoreCase(n) && cookie != null)
                            cookie.setPath(v);
                        else if ("$domain".equalsIgnoreCase(n) && cookie != null)
                            cookie.setDomain(v);
                        continue;
                    }

                    v = URI.decodePath(v);
                    cookie = new Cookie(n, v);
                    if (version > 0)
                        cookie.setVersion(version);
                    cookies = LazyList.add(cookies, cookie);
                } catch (Exception ex) {
                    LogSupport.ignore(log, ex);
                }
            }
        }

        int l = LazyList.size(cookies);
        if (_cookies == null || _cookies.length != l)
            _cookies = new Cookie[l];
        for (int i = 0; i < l; i++)
            _cookies[i] = (Cookie) LazyList.get(cookies, i);
        _cookiesExtracted = true;

        l = LazyList.size(lastCookies);
        _lastCookies = new String[l];
        for (int i = 0; i < l; i++)
            _lastCookies[i] = (String) LazyList.get(lastCookies, i);

    } catch (Exception e) {
        log.warn(LogSupport.EXCEPTION, e);
    }

    return _cookies;
}

From source file:org.apache.coyote.tomcat5.CoyoteAdapter.java

/**
 * Parse cookies.//  www. ja  v  a  2  s .c om
 */
protected void parseCookies(Request req, CoyoteRequest request) {

    Cookies serverCookies = req.getCookies();
    int count = serverCookies.getCookieCount();
    if (count <= 0)
        return;

    Cookie[] cookies = new Cookie[count];

    int idx = 0;
    for (int i = 0; i < count; i++) {
        ServerCookie scookie = serverCookies.getCookie(i);
        if (scookie.getName().equals(Globals.SESSION_COOKIE_NAME)) {
            // Override anything requested in the URL
            if (!request.isRequestedSessionIdFromCookie()) {
                // Accept only the first session id cookie
                request.setRequestedSessionId(scookie.getValue().toString());
                request.setRequestedSessionCookie(true);
                request.setRequestedSessionURL(false);
                if (log.isDebugEnabled())
                    log.debug(" Requested cookie session id is "
                            + ((HttpServletRequest) request.getRequest()).getRequestedSessionId());
            }
        }
        try {
            Cookie cookie = new Cookie(scookie.getName().toString(), scookie.getValue().toString());
            cookie.setPath(scookie.getPath().toString());
            cookie.setVersion(scookie.getVersion());
            String domain = scookie.getDomain().toString();
            if (domain != null) {
                cookie.setDomain(scookie.getDomain().toString());
            }
            cookies[idx++] = cookie;
        } catch (Exception ex) {
            log.error("Bad Cookie Name: " + scookie.getName() + " /Value: " + scookie.getValue(), ex);
        }
    }
    if (idx < count) {
        Cookie[] ncookies = new Cookie[idx];
        System.arraycopy(cookies, 0, ncookies, 0, idx);
        cookies = ncookies;
    }

    request.setCookies(cookies);

}

From source file:org.ireland.jnetty.http.HttpServletRequestImpl.java

/**
 * Extracte cookies./*  w  w w  . j  a  v  a2s .c o  m*/
 */
protected void extracteCookie() {
    _cookiesExtracted = true;

    // Decode the cookie.
    String cookieString = headers.get(HttpHeaders.Names.COOKIE);
    if (cookieString != null) {
        Set<io.netty.handler.codec.http.Cookie> _cookies = CookieDecoder.decode(cookieString);

        this.cookies = new Cookie[_cookies.size()];

        int i = 0;

        // Convent netty's Cookie to Servlet's Cookie
        for (io.netty.handler.codec.http.Cookie c : _cookies) {
            Cookie cookie = new Cookie(c.getName(), c.getValue());

            cookie.setComment(c.getComment());

            if (c.getDomain() != null)
                cookie.setDomain(c.getDomain());

            cookie.setHttpOnly(c.isHttpOnly());
            cookie.setMaxAge((int) c.getMaxAge());
            cookie.setPath(c.getPath());
            cookie.setSecure(c.isSecure());
            cookie.setVersion(c.getVersion());

            this.cookies[i] = cookie;
            i++;
        }
    }
}

From source file:org.ireland.jnetty.server.session.SessionManager.java

/**
 * ?JSESSIONID  Cookie//from   ww w .j  a  va  2 s. com
 * @param session
 * @param contextPath
 * @param secure
 * @return
 */
public Cookie getSessionCookie(HttpSessionImpl session, String contextPath, boolean secure) {

    String sessionPath = contextPath;

    sessionPath = (sessionPath == null || sessionPath.length() == 0) ? "/" : sessionPath;

    String id = session.getId();

    Cookie cookie = null;

    cookie = new Cookie(_cookieName, id);

    cookie.setComment(_cookieComment);

    if (_cookieDomain != null)
        cookie.setDomain(_cookieDomain);

    cookie.setHttpOnly(isHttpOnly());
    cookie.setMaxAge((int) _cookieMaxAge);

    cookie.setPath(sessionPath);

    cookie.setSecure(secure);
    cookie.setVersion(_cookieVersion);

    return cookie;

}