Example usage for java.net HttpCookie getName

List of usage examples for java.net HttpCookie getName

Introduction

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

Prototype

public String getName() 

Source Link

Document

Returns the name of the cookie.

Usage

From source file:com.tremolosecurity.proxy.filter.PostProcess.java

protected void postProcess(HttpFilterRequest req, HttpFilterResponse resp, UrlHolder holder,
        HttpResponse response, String finalURL, HttpFilterChain curChain, HttpRequestBase httpRequest)
        throws IOException, Exception {
    boolean isText;
    HttpEntity entity = null;/*from w  ww  .  j  ava 2  s .c  om*/

    try {
        entity = response.getEntity();
        /*if (entity != null) {
            entity = new BufferedHttpEntity(entity);
        }*/
    } catch (Throwable t) {
        throw new Exception(t);
    }

    InputStream ins = null;
    boolean entExists = false;

    if (entity == null) {
        resp.setStatus(response.getStatusLine().getStatusCode(), response.getStatusLine().getReasonPhrase());
        ins = new StringBufferInputStream("");
    } else {
        try {
            ins = entity.getContent();
            resp.setStatus(response.getStatusLine().getStatusCode(),
                    response.getStatusLine().getReasonPhrase());
            entExists = true;
        } catch (IllegalStateException e) {
            //do nothing
        }
    }

    if (entExists) {
        org.apache.http.Header hdr = response.getFirstHeader("Content-Type");
        org.apache.http.Header encoding = response.getFirstHeader("Content-Encoding");

        /*if (hdr == null) {
           isText = false;
        } else {
           isText = response.getFirstHeader("Content-Type").getValue().startsWith("text");
                   
           if (encoding != null ) {
              isText = (! encoding.getValue().startsWith("gzip")) && (! encoding.getValue().startsWith("deflate"));
           }
                   
           if (isText) {
              resp.setContentType(response.getFirstHeader("Content-Type").getValue());
              resp.setLocale(response.getLocale());
           }
        }*/
        isText = false;

        try {
            resp.setCharacterEncoding(null);
        } catch (Throwable t) {
            //we're not doing anything
        }

        StringBuffer stmp = new StringBuffer();
        if (response.getFirstHeader("Content-Type") != null) {
            resp.setContentType(response.getFirstHeader("Content-Type").getValue());
        }

        if (response.getLocale() != null) {
            resp.setLocale(response.getLocale());
        }

        org.apache.http.Header[] headers = response.getAllHeaders();
        for (int i = 0; i < headers.length; i++) {
            org.apache.http.Header header = headers[i];
            if (header.getName().equals("Content-Type")) {

                continue;
            } else if (header.getName().equals("Content-Type")) {

                continue;
            } else if (header.getName().equals("Content-Length")) {
                if (!header.getValue().equals("0")) {
                    continue;
                }
            } else if (header.getName().equals("Transfer-Encoding")) {
                continue;
            } else if (header.getName().equalsIgnoreCase("set-cookie")
                    || header.getName().equalsIgnoreCase("set-cookie2")) {
                //System.out.println(header.getValue());
                String cookieVal = header.getValue();
                /*if (cookieVal.endsWith("HttpOnly")) {
                   cookieVal = cookieVal.substring(0,cookieVal.indexOf("HttpOnly"));
                }
                        
                //System.out.println(cookieVal);*/

                List<HttpCookie> cookies = HttpCookie.parse(cookieVal);
                Iterator<HttpCookie> it = cookies.iterator();
                while (it.hasNext()) {
                    HttpCookie cookie = it.next();
                    String cookieFinalName = cookie.getName();
                    if (cookieFinalName.equalsIgnoreCase("JSESSIONID")) {
                        stmp.setLength(0);
                        stmp.append("JSESSIONID").append('-')
                                .append(holder.getApp().getName().replaceAll(" ", "|"));
                        cookieFinalName = stmp.toString();
                    }
                    Cookie respcookie = new Cookie(cookieFinalName, cookie.getValue());
                    respcookie.setComment(cookie.getComment());
                    if (cookie.getDomain() != null) {
                        respcookie.setDomain(cookie.getDomain());
                    }

                    if (cookie.hasExpired()) {
                        respcookie.setMaxAge(0);
                    } else {
                        respcookie.setMaxAge((int) cookie.getMaxAge());
                    }
                    respcookie.setPath(cookie.getPath());

                    respcookie.setSecure(cookie.getSecure());
                    respcookie.setVersion(cookie.getVersion());
                    resp.addCookie(respcookie);
                }
            } else if (header.getName().equals("Location")) {

                if (holder.isOverrideHost()) {
                    fixRedirect(req, resp, finalURL, header);
                } else {
                    resp.addHeader("Location", header.getValue());
                }
            } else {
                resp.addHeader(header.getName(), header.getValue());
            }

        }

        curChain.setIns(ins);
        curChain.setText(isText);
        curChain.setEntity(entity);
        curChain.setHttpRequestBase(httpRequest);

        //procData(req, resp, holder, isText, entity, ins);

    } else {
        isText = false;
    }
}

From source file:cn.knet.showcase.demos.servletproxy.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 .  jav  a 2  s .c  om*/
protected void copyProxyCookie(HttpServletRequest servletRequest, HttpServletResponse servletResponse,
        Header header) {
    List<HttpCookie> cookies = HttpCookie.parse(header.getValue());
    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: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 {//  w w w  . ja  v  a2s .com
        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.zaproxy.zap.extension.httpsessions.HttpSessionsSite.java

/**
 * Process the http response message received after a request.
 * //www.  j  a v  a 2s.c  o  m
 * @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: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 .ja v a 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:java.net.HttpCookie.java

/**
 * Returns true if {@code object} is a cookie with the same domain, name and
 * path. Domain and name use case-insensitive comparison; path uses a
 * case-sensitive comparison.//from  w w  w .j a  v  a  2 s  .c  o  m
 */
@Override
public boolean equals(Object object) {
    if (object == this) {
        return true;
    }
    if (object instanceof HttpCookie) {
        HttpCookie that = (HttpCookie) object;
        return name.equalsIgnoreCase(that.getName())
                && (domain != null ? domain.equalsIgnoreCase(that.domain) : that.domain == null)
                && Objects.equal(path, that.path);
    }
    return false;
}

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

/**
 * Set the cookies to the builder based on the request cookies
 * //from   w  w w . j a va  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  w  ww.j a  v  a 2s  .  c om*/
 */
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: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 ww w. j  av  a2s .  co  m
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.
 *//*from w  ww  . j a va2s  .  c  o m*/
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);
    }
}