Example usage for java.net HttpCookie getValue

List of usage examples for java.net HttpCookie getValue

Introduction

In this page you can find the example usage for java.net HttpCookie getValue.

Prototype

public String getValue() 

Source Link

Document

Returns the value of the cookie.

Usage

From source file:org.openhab.binding.amazonechocontrol.internal.WebSocketConnection.java

public WebSocketConnection(String amazonSite, List<HttpCookie> sessionCookies,
        IWebSocketCommandHandler webSocketCommandHandler) throws IOException {
    this.webSocketCommandHandler = webSocketCommandHandler;
    listener = new Listener();

    SslContextFactory sslContextFactory = new SslContextFactory();
    webSocketClient = new WebSocketClient(sslContextFactory);

    try {//from  w w w. j a v  a2 s.  co m
        String host;
        if (StringUtils.equalsIgnoreCase(amazonSite, "amazon.com")) {
            host = "dp-gw-na-js." + amazonSite;
        } else {
            host = "dp-gw-na." + amazonSite;
        }

        String deviceSerial = "";
        List<HttpCookie> cookiesForWs = new ArrayList<HttpCookie>();
        for (HttpCookie cookie : sessionCookies) {
            if (cookie.getName().equals("ubid-acbde")) {
                deviceSerial = cookie.getValue();
            }
            // Clone the cookie without the security attribute, because the web socket implementation ignore secure
            // cookies
            String value = cookie.getValue().replaceAll("^\"|\"$", "");
            HttpCookie cookieForWs = new HttpCookie(cookie.getName(), value);
            cookiesForWs.add(cookieForWs);
        }
        deviceSerial += "-" + new Date().getTime();
        URI uri;

        uri = new URI(
                "wss://" + host + "/?x-amz-device-type=ALEGCNGL9K0HM&x-amz-device-serial=" + deviceSerial);

        try {
            webSocketClient.start();
        } catch (Exception e) {
            logger.warn("Web socket start failed: {}", e);
            throw new IOException("Web socket start failed");
        }

        ClientUpgradeRequest request = new ClientUpgradeRequest();
        request.setHeader("host", host);
        request.setHeader("Cache-Control", "no-cache");
        request.setHeader("Pragma", "no-cache");
        request.setHeader("Origin", "alexa." + amazonSite);

        request.setCookies(cookiesForWs);

        initPongTimeoutTimer();
        webSocketClient.connect(listener, uri, request);

    } catch (URISyntaxException e) {
        logger.debug("Initialize web socket failed: {}", e);
    }
}

From source file:org.bonitasoft.connectors.rest.RESTConnector.java

/**
 * Set the cookies to the builder based on the request cookies
 * //w w  w .  j  av a  2 s . c om
 * @param requestConfigurationBuilder The request builder
 * @param httpClientBuilder The request builder
 * @param list The cookies
 * @param urlHost The URL host
 */
private void setCookies(final Builder requestConfigurationBuilder, final HttpClientBuilder httpClientBuilder,
        final List<HttpCookie> list, final String urlHost) {
    final CookieStore cookieStore = new BasicCookieStore();
    final List<HttpCookie> cookies = list;
    for (final HttpCookie cookie : cookies) {
        final BasicClientCookie c = new BasicClientCookie(cookie.getName(), cookie.getValue());
        c.setPath("/");
        c.setVersion(0);
        c.setDomain(urlHost);
        cookieStore.addCookie(c);
    }
    httpClientBuilder.setDefaultCookieStore(cookieStore);
    requestConfigurationBuilder.setCookieSpec(CookieSpecs.BEST_MATCH);
}

From source file:com.intuit.tank.okhttpclient.TankOkHttpClient.java

/**
 * Process the response data/*from  www  .  j  ava2s  . c  o  m*/
 */
private void processResponse(byte[] bResponse, long startTime, long endTime, BaseRequest request,
        String message, int httpCode, Headers headers) {
    BaseResponse response = request.getResponse();
    try {
        if (response == null) {
            // Get response header information
            String contentType = headers.get("ContentType");
            if (StringUtils.isBlank(contentType)) {
                contentType = "";
            }
            response = TankHttpUtil.newResponseObject(contentType);
            request.setResponse(response);
        }

        // Get response detail information
        response.setHttpMessage(message);
        response.setHttpCode(httpCode);

        // Get response header information
        for (String key : headers.names()) {
            response.setHeader(key, headers.get(key));
        }

        if (((CookieManager) okHttpClient.getCookieHandler()).getCookieStore().getCookies() != null) {
            for (HttpCookie cookie : ((CookieManager) okHttpClient.getCookieHandler()).getCookieStore()
                    .getCookies()) {
                // System.out.println("in processResponse-getCookies");
                // System.out.println(cookie.toString());
                response.setCookie(cookie.getName(), cookie.getValue());
            }
        }

        response.setResponseTime(endTime - startTime);
        String contentType = response.getHttpHeader("Content-Type");
        String contentEncode = response.getHttpHeader("Content-Encoding");
        if (BaseResponse.isDataType(contentType) && contentEncode != null
                && contentEncode.toLowerCase().contains("gzip")) {
            // decode gzip for data types
            try {
                GZIPInputStream in = new GZIPInputStream(new ByteArrayInputStream(bResponse));
                ByteArrayOutputStream out = new ByteArrayOutputStream();
                IOUtils.copy(in, out);
                bResponse = out.toByteArray();
            } catch (Exception e) {
                LOG.warn(request.getLogUtil().getLogMessage("cannot decode gzip stream: " + e,
                        LogEventType.System));
            }
        }
        response.setResponseBody(bResponse);

    } catch (Exception ex) {
        LOG.warn("Unable to get response: " + ex.getMessage());
    } finally {
        response.logResponse();
    }
}

From source file:org.parosproxy.paros.network.HttpRequestHeader.java

/**
 * Construct new "Cookie:" line in request header based on HttpCookies.
 *
 * @param cookies the new cookies//from w  w w  . j  a va 2  s  .c  om
 */
public void setCookies(List<HttpCookie> cookies) {
    if (cookies.isEmpty()) {
        setHeader(HttpHeader.COOKIE, null);
    }

    StringBuilder sbData = new StringBuilder();

    for (HttpCookie c : cookies) {
        sbData.append(c.getName());
        sbData.append('=');
        sbData.append(c.getValue());
        sbData.append("; ");
    }

    if (sbData.length() <= 3) {
        setHeader(HttpHeader.COOKIE, null);
        return;
    }

    final String data = sbData.substring(0, sbData.length() - 2);
    setHeader(HttpHeader.COOKIE, data);
}

From source file:org.zaproxy.zap.extension.httpsessions.HttpSessionsSite.java

/**
 * Process the http response message received after a request.
 * //  w w w. j a  v a  2 s. c om
 * @param message the message
 */
public void processHttpResponseMessage(HttpMessage message) {

    // Get the session tokens for this site
    HttpSessionTokensSet siteTokensSet = extension.getHttpSessionTokensSet(getSite());

    // No tokens for this site, so no processing
    if (siteTokensSet == null) {
        log.debug("No session tokens for: " + this.getSite());
        return;
    }
    // Create an auxiliary map of token values and insert keys for every token
    Map<String, Cookie> tokenValues = new HashMap<>();

    // Get new values that were set for tokens (e.g. using SET-COOKIE headers), if any

    List<HttpCookie> cookiesToSet = message.getResponseHeader()
            .getHttpCookies(message.getRequestHeader().getHostName());
    for (HttpCookie cookie : cookiesToSet) {
        String lcCookieName = cookie.getName();
        if (siteTokensSet.isSessionToken(lcCookieName)) {
            Cookie ck = new Cookie(cookie.getDomain(), lcCookieName, cookie.getValue(), cookie.getPath(),
                    (int) cookie.getMaxAge(), cookie.getSecure());
            tokenValues.put(lcCookieName, ck);
        }
    }

    // Get the cookies present in the request
    List<HttpCookie> requestCookies = message.getRequestHeader().getHttpCookies();

    // XXX When an empty HttpSession is set in the message and the response
    // contains session cookies, the empty HttpSession is reused which
    // causes the number of messages matched to be incorrect.

    // Get the session, based on the request header
    HttpSession session = message.getHttpSession();
    if (session == null || !session.isValid()) {
        session = getMatchingHttpSession(requestCookies, siteTokensSet);
        if (log.isDebugEnabled()) {
            log.debug("Matching session for response message (from site " + getSite() + "): " + session);
        }
    } else {
        if (log.isDebugEnabled()) {
            log.debug("Matching cached session for response message (from site " + getSite() + "): " + session);
        }
    }

    // If the session didn't exist, create it now
    if (session == null) {
        session = new HttpSession(generateUniqueSessionName(), extension.getHttpSessionTokensSet(getSite()));
        this.addHttpSession(session);

        // Add all the existing tokens from the request, if they don't replace one in the
        // response
        for (HttpCookie cookie : requestCookies) {
            String cookieName = cookie.getName();
            if (siteTokensSet.isSessionToken(cookieName)) {
                if (!tokenValues.containsKey(cookieName)) {

                    // We must ensure that a cookie as always a valid domain and path in order to be able to reuse it.
                    // HttpClient will discard invalid cookies

                    String domain = cookie.getDomain();
                    if (domain == null) {
                        domain = message.getRequestHeader().getHostName();
                    }

                    String path = cookie.getPath();
                    if (path == null) {
                        path = "/"; // Default path
                    }

                    Cookie ck = new Cookie(domain, cookieName, cookie.getValue(), path,
                            (int) cookie.getMaxAge(), cookie.getSecure());
                    tokenValues.put(cookieName, ck);
                }
            }
        }
        log.info("Created a new session as no match was found: " + session);
    }

    // Update the session
    if (!tokenValues.isEmpty()) {
        for (Entry<String, Cookie> tv : tokenValues.entrySet()) {
            session.setTokenValue(tv.getKey(), tv.getValue());
        }
    }

    // Update the count of messages matched
    session.setMessagesMatched(session.getMessagesMatched() + 1);

    this.model.fireHttpSessionUpdated(session);

    // Store the session in the HttpMessage for caching purpose
    message.setHttpSession(session);
}

From source file:cn.tiup.httpproxy.ProxyServlet.java

/** Copy cookie from the proxy to the servlet client.
 *  Replaces cookie path to local path and renames cookie to avoid collisions.
 *//*from www.  j  a v  a 2 s  . c om*/
protected void copyProxyCookie(HttpServletRequest servletRequest, HttpServletResponse servletResponse,
        String headerValue) {
    List<HttpCookie> cookies = HttpCookie.parse(headerValue);

    for (HttpCookie cookie : cookies) {
        //set cookie name prefixed w/ a proxy value so it won't collide w/ other cookies
        String proxyCookieName = getCookieNamePrefix(cookie.getName()) + cookie.getName();
        Cookie servletCookie = new Cookie(proxyCookieName, cookie.getValue());
        servletCookie.setComment(cookie.getComment());
        servletCookie.setMaxAge((int) cookie.getMaxAge());
        servletCookie.setPath(cookie.getPath()); //set to the path of the proxy servlet
        // don't set cookie domain
        servletCookie.setSecure(cookie.getSecure());
        servletCookie.setVersion(cookie.getVersion());
        servletResponse.addCookie(servletCookie);
    }
}

From source file:io.hops.hopsworks.api.kibana.ProxyServlet.java

/**
 * Copy cookie from the proxy to the servlet client.
 * Replaces cookie path to local path and renames cookie to avoid collisions.
 *///w  w w . j a v a  2s  .c om
protected void copyProxyCookie(HttpServletRequest servletRequest, HttpServletResponse servletResponse,
        String header) {
    List<HttpCookie> cookies = HttpCookie.parse(header);
    String path = servletRequest.getContextPath(); // path starts with / or is empty string
    path += servletRequest.getServletPath(); // servlet path starts with / or is empty string

    for (HttpCookie cookie : cookies) {
        //set cookie name prefixed w/ a proxy value so it won't collide w/ other cookies
        String proxyCookieName = getCookieNamePrefix() + cookie.getName();
        Cookie servletCookie = new Cookie(proxyCookieName, cookie.getValue());
        servletCookie.setComment(cookie.getComment());
        servletCookie.setMaxAge((int) cookie.getMaxAge());
        servletCookie.setPath(path); //set to the path of the proxy servlet
        // don't set cookie domain
        servletCookie.setSecure(cookie.getSecure());
        servletCookie.setVersion(cookie.getVersion());
        servletResponse.addCookie(servletCookie);
    }
}

From source file:com.yanzhenjie.nohttp.BasicRequest.java

@Override
public IBasicRequest addHeader(HttpCookie cookie) {
    if (cookie != null)
        mHeaders.add(Headers.HEAD_KEY_COOKIE, cookie.getName() + "=" + cookie.getValue());
    return this;
}

From source file:com.google.gwt.jolokia.server.servlet.ProxyServlet.java

/**
 * Copy cookie from the proxy to the servlet client. Replaces cookie path to
 * local path and renames cookie to avoid collisions.
 *///from   w ww .j  a v  a2s  .  c  o  m
protected void copyProxyCookie(HttpServletRequest servletRequest, HttpServletResponse servletResponse,
        Header header) {
    List<HttpCookie> cookies = HttpCookie.parse(header.getValue());
    String path = getServletContext().getServletContextName();
    if (path == null) {
        path = "";
    }
    path += servletRequest.getServletPath();

    for (HttpCookie cookie : cookies) {
        // set cookie name prefixed w/ a proxy value so it won't collide w/
        // other cookies
        String proxyCookieName = getCookieNamePrefix() + cookie.getName();
        Cookie servletCookie = new Cookie(proxyCookieName, cookie.getValue());
        servletCookie.setComment(cookie.getComment());
        servletCookie.setMaxAge((int) cookie.getMaxAge());
        servletCookie.setPath(path); // set to the path of the proxy servlet
        // don't set cookie domain
        servletCookie.setSecure(cookie.getSecure());
        servletCookie.setVersion(cookie.getVersion());
        servletResponse.addCookie(servletCookie);
    }
}

From source file:com.fuseim.webapp.ProxyServlet.java

/**
 * Copy cookie from the proxy to the servlet client. Replaces cookie path to local path and
 * renames cookie to avoid collisions./*  w  w  w.j  av  a 2s.  co m*/
 */
protected void copyProxyCookie(HttpServletRequest servletRequest, HttpServletResponse servletResponse,
        String headerValue) {
    List<HttpCookie> cookies = HttpCookie.parse(headerValue);
    String path = servletRequest.getContextPath(); // path starts with / or is empty string
    path += servletRequest.getServletPath(); // servlet path starts with / or is empty string

    for (HttpCookie cookie : cookies) {
        //set cookie name prefixed w/ a proxy value so it won't collide w/ other cookies
        String proxyCookieName = doPreserveCookies ? cookie.getName()
                : getCookieNamePrefix(cookie.getName()) + cookie.getName();
        Cookie servletCookie = new Cookie(proxyCookieName, cookie.getValue());
        servletCookie.setComment(cookie.getComment());
        servletCookie.setMaxAge((int) cookie.getMaxAge());
        servletCookie.setPath(path); //set to the path of the proxy servlet
        // don't set cookie domain
        servletCookie.setSecure(cookie.getSecure());
        servletCookie.setVersion(cookie.getVersion());
        servletResponse.addCookie(servletCookie);
    }
}