Example usage for java.net HttpCookie getMaxAge

List of usage examples for java.net HttpCookie getMaxAge

Introduction

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

Prototype

public long getMaxAge() 

Source Link

Document

Returns the maximum age of the cookie, specified in seconds.

Usage

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./*from ww  w  .j av  a 2s  . c o  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);
    }
}

From source file:com.tremolosecurity.proxy.filters.PreAuthFilter.java

@Override
public void doFilter(HttpFilterRequest request, HttpFilterResponse response, HttpFilterChain chain)
        throws Exception {
    AuthInfo userData = ((AuthController) request.getSession().getAttribute(ProxyConstants.AUTH_CTL))
            .getAuthInfo();//from w  w  w.j  a  v a 2  s .  c  om
    ConfigManager cfg = (ConfigManager) request.getAttribute(ProxyConstants.TREMOLO_CFG_OBJ);

    List<Cookie> cookies = null;

    if (userData.getAuthLevel() > 0 && userData.isAuthComplete()) {
        UrlHolder holder = (UrlHolder) request.getAttribute(ProxyConstants.AUTOIDM_CFG);
        HttpSession session = request.getSession();
        String uid = (String) session.getAttribute("TREMOLO_PRE_AUTH");
        if (uid == null || !uid.equals(userData.getUserDN())) {
            session.setAttribute("TREMOLO_PRE_AUTH", userData.getUserDN());
            HashMap<String, String> uriParams = new HashMap<String, String>();
            uriParams.put("fullURI", this.uri);

            UrlHolder remHolder = cfg.findURL(this.url);

            org.apache.http.client.methods.HttpRequestBase method = null;

            if (this.postSAML) {
                PrivateKey pk = holder.getConfig().getPrivateKey(this.keyAlias);
                java.security.cert.X509Certificate cert = holder.getConfig().getCertificate(this.keyAlias);

                Saml2Assertion assertion = new Saml2Assertion(
                        userData.getAttribs().get(this.nameIDAttribute).getValues().get(0), pk, cert, null,
                        this.issuer, this.assertionConsumerURL, this.audience, this.signAssertion,
                        this.signResponse, false, this.nameIDType, this.authnCtxClassRef);

                String respXML = "";

                try {
                    respXML = assertion.generateSaml2Response();
                } catch (Exception e) {
                    throw new ServletException("Could not generate SAMLResponse", e);
                }

                List<NameValuePair> formparams = new ArrayList<NameValuePair>();
                String base64 = Base64.encodeBase64String(respXML.getBytes("UTF-8"));

                formparams.add(new BasicNameValuePair("SAMLResponse", base64));
                if (this.relayState != null && !this.relayState.isEmpty()) {
                    formparams.add(new BasicNameValuePair("RelayState", this.relayState));
                }

                UrlEncodedFormEntity entity = new UrlEncodedFormEntity(formparams, "UTF-8");
                HttpPost post = new HttpPost(this.assertionConsumerURL);
                post.setEntity(entity);
                method = post;

            } else {
                HttpGet get = new HttpGet(remHolder.getProxyURL(uriParams));
                method = get;
            }

            LastMileUtil.addLastMile(cfg, userData.getAttribs().get(loginAttribute).getValues().get(0),
                    this.loginAttribute, method, lastMileKeyAlias, true);
            BasicHttpClientConnectionManager bhcm = new BasicHttpClientConnectionManager(
                    cfg.getHttpClientSocketRegistry());
            try {
                CloseableHttpClient httpclient = HttpClients.custom().setConnectionManager(bhcm)
                        .setDefaultRequestConfig(cfg.getGlobalHttpClientConfig()).build();

                HttpResponse resp = httpclient.execute(method);

                if (resp.getStatusLine().getStatusCode() == 500) {
                    BufferedReader in = new BufferedReader(
                            new InputStreamReader(resp.getEntity().getContent()));
                    StringBuffer error = new StringBuffer();
                    String line = null;
                    while ((line = in.readLine()) != null) {
                        error.append(line).append('\n');
                    }

                    logger.warn("Pre-Auth Failed : " + error);
                }

                org.apache.http.Header[] headers = resp.getAllHeaders();

                StringBuffer stmp = new StringBuffer();

                cookies = new ArrayList<Cookie>();

                for (org.apache.http.Header header : headers) {
                    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> cookiesx = HttpCookie.parse(cookieVal);
                        for (HttpCookie cookie : cookiesx) {

                            String cookieFinalName = cookie.getName();
                            if (cookieFinalName.equalsIgnoreCase("JSESSIONID")) {
                                stmp.setLength(0);
                                stmp.append("JSESSIONID").append('-')
                                        .append(holder.getApp().getName().replaceAll(" ", "|"));
                                cookieFinalName = stmp.toString();
                            }

                            //logger.info("Adding cookie name '" + cookieFinalName + "'='" + cookie.getValue() + "'");

                            Cookie respcookie = new Cookie(cookieFinalName, cookie.getValue());
                            respcookie.setComment(cookie.getComment());
                            if (cookie.getDomain() != null) {
                                //respcookie.setDomain(cookie.getDomain());
                            }
                            respcookie.setMaxAge((int) cookie.getMaxAge());
                            respcookie.setPath(cookie.getPath());

                            respcookie.setSecure(cookie.getSecure());
                            respcookie.setVersion(cookie.getVersion());
                            cookies.add(respcookie);

                            if (request.getCookieNames().contains(respcookie.getName())) {
                                request.removeCookie(cookieFinalName);
                            }

                            request.addCookie(new Cookie(cookie.getName(), cookie.getValue()));
                        }
                    }
                }

            } finally {
                bhcm.shutdown();
            }
        }
    }

    chain.nextFilter(request, response, chain);
    if (cookies != null) {

        for (Cookie cookie : cookies) {

            response.addCookie(cookie);
        }
    }

}

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;/* www  .  j av a2  s . co m*/

    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:org.mitre.dsmiley.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 w  ww.j  av a 2 s.  c  o  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 = 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);
    }
}

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

public String serializeLoginData() {
    Date loginTime = this.loginTime;
    if (refreshToken == null || loginTime == null) {
        return "";
    }/* w  ww  .  jav a  2s  . c o m*/
    StringBuilder builder = new StringBuilder();
    builder.append("6\n"); // version
    builder.append(frc);
    builder.append("\n");
    builder.append(serial);
    builder.append("\n");
    builder.append(deviceId);
    builder.append("\n");
    builder.append(refreshToken);
    builder.append("\n");
    builder.append(amazonSite);
    builder.append("\n");
    builder.append(deviceName);
    builder.append("\n");
    builder.append(accountCustomerId);
    builder.append("\n");
    builder.append(loginTime.getTime());
    builder.append("\n");
    List<HttpCookie> cookies = cookieManager.getCookieStore().getCookies();
    builder.append(cookies.size());
    builder.append("\n");
    for (HttpCookie cookie : cookies) {
        writeValue(builder, cookie.getName());
        writeValue(builder, cookie.getValue());
        writeValue(builder, cookie.getComment());
        writeValue(builder, cookie.getCommentURL());
        writeValue(builder, cookie.getDomain());
        writeValue(builder, cookie.getMaxAge());
        writeValue(builder, cookie.getPath());
        writeValue(builder, cookie.getPortlist());
        writeValue(builder, cookie.getVersion());
        writeValue(builder, cookie.getSecure());
        writeValue(builder, cookie.getDiscard());
    }
    return builder.toString();
}

From source file:org.piwik.ResponseData.java

public List<Cookie> getCookies() {
    List<Cookie> cookies = new ArrayList<Cookie>();

    for (String key : headerData.keySet()) {
        List<String> headerParts = headerData.get(key);

        StringBuilder cookieInfo = new StringBuilder();
        for (String part : headerParts) {
            cookieInfo.append(part);//w ww. jav a2 s .  c o  m
        }

        if (key == null && cookieInfo.toString().equals("")) {
            LOGGER.debug("No more headers, not proceeding");
            return null;
        }

        if (key == null) {
            LOGGER.debug("The header value contains the server's HTTP version, not proceeding");
        } else if (key.equals("Set-Cookie")) {
            List<HttpCookie> httpCookies = HttpCookie.parse(cookieInfo.toString());
            for (HttpCookie h : httpCookies) {
                Cookie c = new Cookie(h.getName(), h.getValue());
                c.setComment(h.getComment());
                if (h.getDomain() != null) {
                    c.setDomain(h.getDomain());
                }
                c.setMaxAge(Long.valueOf(h.getMaxAge()).intValue());
                c.setPath(h.getPath());
                c.setSecure(h.getSecure());
                c.setVersion(h.getVersion());
                cookies.add(c);
            }
        } else {
            LOGGER.debug("The provided key (" + key + ") with value (" + cookieInfo
                    + ") were not processed because the key is unknown");
        }
    }
    return cookies;
}

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

/**
 * Process the http response message received after a request.
 * /*from   w  ww  . ja  v a 2  s. 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.zaproxy.zap.utils.HarUtils.java

public static HarResponse createHarResponse(HttpMessage httpMessage) {
    HttpResponseHeader responseHeader = httpMessage.getResponseHeader();
    HarCookies harCookies = new HarCookies();

    long whenCreated = System.currentTimeMillis();
    for (HttpCookie cookie : responseHeader.getHttpCookies()) {
        Date expires;/*w  w  w.ja va2 s. co m*/
        if (cookie.getVersion() == 0) {
            expires = new Date(whenCreated + (cookie.getMaxAge() * 1000));
        } else {
            expires = new Date(httpMessage.getTimeSentMillis() + httpMessage.getTimeElapsedMillis()
                    + (cookie.getMaxAge() * 1000));
        }

        harCookies.addCookie(new HarCookie(cookie.getName(), cookie.getValue(), cookie.getPath(),
                cookie.getDomain(), expires, cookie.isHttpOnly(), cookie.getSecure(), null));
    }

    String text = null;
    String encoding = null;
    String contentType = responseHeader.getHeader(HttpHeader.CONTENT_TYPE);
    if (contentType == null) {
        contentType = "";
    } else if (!contentType.isEmpty()) {
        String lcContentType = contentType.toLowerCase(Locale.ROOT);
        final int pos = lcContentType.indexOf(';');
        if (pos != -1) {
            lcContentType = lcContentType.substring(0, pos).trim();
        }

        if (!lcContentType.startsWith("text")) {
            encoding = "base64";
            text = Base64.encodeBytes(httpMessage.getResponseBody().getBytes());
        } else {
            text = httpMessage.getResponseBody().toString();
        }
    }

    HarContent harContent = new HarContent(httpMessage.getResponseBody().length(), 0, contentType, text,
            encoding, null);

    String redirectUrl = responseHeader.getHeader(HttpHeader.LOCATION);

    return new HarResponse(responseHeader.getStatusCode(), responseHeader.getReasonPhrase(),
            responseHeader.getVersion(), harCookies, createHarHeaders(responseHeader), harContent,
            redirectUrl == null ? "" : redirectUrl, responseHeader.toString().length(),
            httpMessage.getResponseBody().length(), null);
}