Example usage for java.net HttpCookie getPath

List of usage examples for java.net HttpCookie getPath

Introduction

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

Prototype

public String getPath() 

Source Link

Document

Returns the path on the server to which the browser returns this cookie.

Usage

From source file:com.jaspersoft.android.jaspermobile.network.cookie.CookieMapper.java

@Nullable
public org.apache.http.cookie.Cookie toApacheCookie(@Nullable HttpCookie cookie) {
    if (cookie == null) {
        return null;
    }// w w w  .  j a  v  a  2  s .c  o  m

    BasicClientCookie clientCookie = new BasicClientCookie(cookie.getName(), cookie.getValue());
    clientCookie.setDomain(cookie.getDomain());
    clientCookie.setPath(cookie.getPath());
    clientCookie.setVersion(cookie.getVersion());

    Date expiryDate = new Date(new Date().getTime() + cookie.getMaxAge());
    clientCookie.setExpiryDate(expiryDate);

    return clientCookie;
}

From source file:at.becast.youploader.youtube.data.Cookie.java

public Cookie(final HttpCookie cookie) {
    name = cookie.getName();//w  ww .  j a  va  2s.  c o  m
    value = cookie.getValue();
    comment = cookie.getComment();
    commentUrl = cookie.getCommentURL();
    domain = cookie.getDomain();
    discard = cookie.getDiscard();
    maxAge = cookie.getMaxAge();
    path = cookie.getPath();
    portList = cookie.getPortlist();
    secure = cookie.getSecure();
    version = cookie.getVersion();
}

From source file:ai.eve.volley.stack.HurlStack.java

@Override
public HttpResponse performRequest(Request<?> request) throws IOException, AuthFailureError {
    HashMap<String, String> map = new HashMap<String, String>();
    if (!TextUtils.isEmpty(mUserAgent)) {
        map.put(HTTP.USER_AGENT, mUserAgent);
    }/*from  w  w w .j a  v a2  s.  c  om*/
    if (!TextUtils.isEmpty(mSignInfo)) {
        map.put("SIGN", ESecurity.Encrypt(mSignInfo));
    }
    map.putAll(request.getHeaders());

    URL parsedUrl = new URL(request.getUrl());
    HttpURLConnection connection = openConnection(parsedUrl, request);

    for (String headerName : map.keySet()) {
        connection.addRequestProperty(headerName, map.get(headerName));
    }
    if (EApplication.getCookies() != null) {
        ELog.I("cookie", EApplication.getCookies().toString());
        connection.addRequestProperty("Cookie", EApplication.getReqCookies());
    } else {
        ELog.I("cookie", "null");
    }
    setConnectionParametersForRequest(connection, request);
    int responseCode = connection.getResponseCode();
    if (responseCode == -1) {
        // -1 is returned by getResponseCode() if the response code could not be retrieved.
        // Signal to the caller that something was wrong with the connection.
        throw new IOException("Could not retrieve response code from HttpUrlConnection.");
    }

    StatusLine responseStatus = new BasicStatusLine(new ProtocolVersion("HTTP", 1, 1),
            connection.getResponseCode(), connection.getResponseMessage());
    BasicHttpResponse response = new BasicHttpResponse(responseStatus);
    response.setEntity(entityFromConnection(connection));
    for (Entry<String, List<String>> header : connection.getHeaderFields().entrySet()) {
        if (header.getKey() != null) {
            if (header.getKey().equalsIgnoreCase("Set-Cookie")) {
                List<String> cookies = header.getValue();
                HashMap<String, HttpCookie> cookieMap = new HashMap<String, HttpCookie>();
                for (String string : cookies) {
                    List<HttpCookie> cookie = HttpCookie.parse(string);
                    for (HttpCookie httpCookie : cookie) {
                        if (httpCookie.getDomain() != null && httpCookie.getPath() != null) {
                            cookieMap.put(httpCookie.getName() + httpCookie.getDomain() + httpCookie.getPath(),
                                    httpCookie);
                        } else if (httpCookie.getDomain() == null && httpCookie.getPath() != null) {
                            cookieMap.put(httpCookie.getName() + httpCookie.getPath(), httpCookie);
                        } else if (httpCookie.getDomain() != null && httpCookie.getPath() == null) {
                            cookieMap.put(httpCookie.getName() + httpCookie.getDomain(), httpCookie);
                        } else {
                            cookieMap.put(httpCookie.getName(), httpCookie);
                        }
                    }
                }

                EApplication.setCookies(cookieMap);
                if (EApplication.getCookies() != null) {
                    ELog.I("?cookie", EApplication.getCookies().toString());
                }
            } else {
                Header h = new BasicHeader(header.getKey(), header.getValue().get(0));
                response.addHeader(h);
            }
        }
    }

    return response;
}

From source file:com.nominanuda.web.http.ServletHelper.java

public Cookie servletCookie(HttpCookie c) {
    Cookie _c = new Cookie(c.getName(), c.getValue());
    if (c.getComment() != null) {
        _c.setComment(c.getComment());//  w w  w  . ja  va  2 s .com
    }
    if (c.getDomain() != null) {
        _c.setDomain(c.getDomain());
    }
    if (c.getPath() != null) {
        _c.setPath(c.getPath());
    }
    _c.setSecure(c.getSecure());
    _c.setVersion(c.getVersion());
    _c.setHttpOnly(c.getDiscard());
    _c.setMaxAge((int) c.getMaxAge());
    return _c;
}

From source file:com.muk.services.security.DefaultUaaLoginService.java

private String httpCookieToString(HttpCookie cookie) {
    final OffsetDateTime now = OffsetDateTime.now(ZoneOffset.UTC).plusSeconds(cookie.getMaxAge());
    final String cookieExpires = DateTimeFormatter.RFC_1123_DATE_TIME.format(now);
    final StringBuilder cookieBuilder = new StringBuilder();
    cookieBuilder.append(cookie.getName()).append("=").append(cookie.getValue()).append(";path=")
            .append(cookie.getPath()).append(";max-age=").append(cookie.getMaxAge()).append(";expires=")
            .append(cookieExpires);//from www.  ja v a2 s  .c  o  m

    if (cookie.isHttpOnly()) {
        cookieBuilder.append(";HttpOnly");
    }

    return cookieBuilder.toString();
}

From source file:org.nextlets.erc.defaults.http.ERCHttpInvokerImpl.java

private Cookie toCookie(URI uri, HttpCookie httpCookie) {
    SetCookie cookie = new BasicClientCookie(httpCookie.getName(), httpCookie.getValue());
    cookie.setComment(httpCookie.getComment());
    if (httpCookie.getDomain() != null) {
        cookie.setDomain(httpCookie.getDomain());
    } else {//from  w  w  w  . jav a 2 s  .com
        cookie.setDomain(uri.getHost());
    }
    if (httpCookie.getMaxAge() != -1) {
        cookie.setExpiryDate(new Date(httpCookie.getMaxAge() * 1000));
    }
    if (httpCookie.getPath() != null) {
        cookie.setPath(httpCookie.getPath());
    } else {
        cookie.setPath(uri.getPath());
    }
    cookie.setSecure(httpCookie.getSecure());
    cookie.setVersion(httpCookie.getVersion());
    return cookie;
}

From source file:com.subgraph.vega.ui.scanner.ScanExecutor.java

private List<Cookie> getCookieList(List<String> cookieStringList, URI uri) {
    if (cookieStringList.size() != 0) {
        ArrayList<Cookie> cookieList = new ArrayList<Cookie>(cookieStringList.size());
        for (String cookieString : cookieStringList) {
            List<HttpCookie> parseList = HttpCookie.parse(cookieString);
            for (HttpCookie cookie : parseList) {
                BasicClientCookie cp = new BasicClientCookie(cookie.getName(), cookie.getValue());
                cp.setComment(cookie.getComment());
                if (cookie.getDomain() != null) {
                    cp.setDomain(cookie.getDomain());
                } else {
                    // just set it to the target host for now - may need something slightly less specific
                    cp.setDomain(uri.getHost());
                }/*from w ww. j a  v a  2 s  . c o m*/
                long maxAge = cookie.getMaxAge();
                if (maxAge > 0) {
                    Calendar calendar = Calendar.getInstance();
                    calendar.add(Calendar.SECOND, (int) maxAge);
                    cp.setExpiryDate(calendar.getTime());
                }
                cp.setPath(cookie.getPath());
                cp.setSecure(cookie.getSecure());
                cp.setVersion(cookie.getVersion());
                cookieList.add(cp);
            }
        }
        return cookieList;
    }
    return null;
}

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.
 */// w  ww. 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: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  .  com*/
    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;/*from  w w  w. ja  v a 2s  .  c  o  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;
    }
}