Example usage for org.apache.commons.httpclient Cookie getPath

List of usage examples for org.apache.commons.httpclient Cookie getPath

Introduction

In this page you can find the example usage for org.apache.commons.httpclient Cookie getPath.

Prototype

public String getPath() 

Source Link

Usage

From source file:com.intuit.tank.httpclient3.TankHttpClient3.java

private void sendRequest(BaseRequest request, @Nonnull HttpMethod method, String requestBody) {
    String uri = null;/*from ww  w .ja  v  a  2  s .c om*/
    long waitTime = 0L;

    try {
        uri = method.getURI().toString();
        logger.debug(request.getLogUtil().getLogMessage(
                "About to " + method.getName() + " request to " + uri + " with requestBody  " + requestBody,
                LogEventType.Informational));
        List<String> cookies = new ArrayList<String>();
        if (httpclient != null && httpclient.getState() != null && httpclient.getState().getCookies() != null) {
            for (Cookie cookie : httpclient.getState().getCookies()) {
                cookies.add("REQUEST COOKIE: " + cookie.toExternalForm() + " (domain=" + cookie.getDomain()
                        + " : path=" + cookie.getPath() + ")");
            }
        }
        request.logRequest(uri, requestBody, method.getName(), request.getHeaderInformation(), cookies, false);
        setHeaders(request, method, request.getHeaderInformation());
        long startTime = System.currentTimeMillis();
        request.setTimestamp(new Date(startTime));
        httpclient.executeMethod(method);

        // read response body
        byte[] responseBody = new byte[0];
        // check for no content headers
        if (method.getStatusCode() != 203 && method.getStatusCode() != 202 && method.getStatusCode() != 204) {
            try {
                InputStream httpInputStream = method.getResponseBodyAsStream();
                ByteArrayOutputStream out = new ByteArrayOutputStream();
                int curByte = httpInputStream.read();
                while (curByte >= 0) {
                    out.write(curByte);
                    curByte = httpInputStream.read();
                }
                responseBody = out.toByteArray();
            } catch (Exception e) {
                logger.warn("could not get response body: " + e);
            }
        }
        long endTime = System.currentTimeMillis();
        processResponse(responseBody, startTime, endTime, request, method.getStatusText(),
                method.getStatusCode(), method.getResponseHeaders(), httpclient.getState());
        waitTime = endTime - startTime;
    } catch (Exception ex) {
        logger.error(request.getLogUtil().getLogMessage(
                "Could not do " + method.getName() + " to url " + uri + " |  error: " + ex.toString(),
                LogEventType.IO), ex);
        throw new RuntimeException(ex);
    } finally {
        try {
            method.releaseConnection();
        } catch (Exception e) {
            logger.warn("Could not release connection: " + e, e);
        }
        if (method.getName().equalsIgnoreCase("post")
                && request.getLogUtil().getAgentConfig().getLogPostResponse()) {
            logger.info(request.getLogUtil()
                    .getLogMessage("Response from POST to " + request.getRequestUrl() + " got status code "
                            + request.getResponse().getHttpCode() + " BODY { " + request.getResponse().getBody()
                            + " }", LogEventType.Informational));
        }
    }
    if (waitTime != 0) {
        doWaitDueToLongResponse(request, waitTime, uri);
    }
}

From source file:com.intuit.tank.http.BaseRequest.java

@SuppressWarnings("rawtypes")
protected void logRequest(String url, String body, String method, HashMap<String, String> headerInformation,
        HttpClient httpclient, boolean force) {
    try {/*from   w  ww  .j av  a 2  s  . co  m*/
        StringBuilder sb = new StringBuilder();

        sb.append("REQUEST URL: " + method + " " + url).append(NEWLINE);
        // Header Information
        for (Map.Entry mapEntry : headerInformation.entrySet()) {
            sb.append("REQUEST HEADER: " + (String) mapEntry.getKey() + " = " + (String) mapEntry.getValue())
                    .append(NEWLINE);
        }
        // Cookies Information
        if (httpclient != null && httpclient.getState() != null && httpclient.getState().getCookies() != null) {
            for (Cookie cookie : httpclient.getState().getCookies()) {
                sb.append("REQUEST COOKIE: " + cookie.toExternalForm() + " (domain=" + cookie.getDomain()
                        + " : path=" + cookie.getPath() + ")").append(NEWLINE);
            }
        }
        if (null != body) {
            sb.append("REQUEST SIZE: " + body.getBytes().length).append(NEWLINE);
            sb.append("REQUEST BODY: " + body).append(NEWLINE);
        }
        this.logMsg = sb.toString();
        if (APITestHarness.getInstance().isDebug()) {
            System.out.println("******** REQUEST *********");
            System.out.println(this.logMsg);
        }
        logger.debug("******** REQUEST *********");
        logger.debug(this.logMsg);

    } catch (Exception ex) {
        logger.error("Unable to log request", ex);
    }
}

From source file:com.hp.alm.ali.rest.client.AliRestClient.java

private void addTenantCookie(Cookie ssoCookie) {
    if (ssoCookie != null) {
        Cookie tenant_id_cookie = new Cookie(ssoCookie.getDomain(), "TENANT_ID_COOKIE", "0");
        tenant_id_cookie.setDomainAttributeSpecified(true);
        tenant_id_cookie.setPath(ssoCookie.getPath());
        tenant_id_cookie.setPathAttributeSpecified(true);
        httpClient.getState().addCookie(tenant_id_cookie);
    }//from  w  w w . j  a  va  2s. c  o m
}

From source file:at.ait.dme.yuma.server.annotation.ImageAnnotationManager.java

private EuropeanaAnnotationService getAnnotationService(MultivaluedMap<String, String> headers) {

    List<String> cookieHeaders = (headers != null) ? headers.get("Set-Cookie") : new ArrayList<String>();

    HttpClient client = new HttpClient();
    // make sure to forward all cookies             
    javax.servlet.http.Cookie[] cookies = clientRequest.getCookies();
    for (javax.servlet.http.Cookie c : cookies) {
        c.setDomain(clientRequest.getServerName());
        c.setPath("/");

        String value = c.getValue();
        for (String cookieHeader : cookieHeaders) {
            if (cookieHeader.startsWith(c.getName())) {
                String cookieHeaderParts[] = cookieHeader.split("=");
                if (cookieHeaderParts.length >= 2)
                    value = cookieHeaderParts[1];
            }/*from www.  j  a  v a  2  s .c  om*/
        }
        Cookie apacheCookie = new Cookie(c.getDomain(), c.getName(), value, c.getPath(), c.getMaxAge(),
                c.getSecure());
        client.getState().addCookie(apacheCookie);
    }
    client.getParams().setCookiePolicy(CookiePolicy.BROWSER_COMPATIBILITY);

    return ProxyFactory.create(EuropeanaAnnotationService.class, annotationServiceBaseUrl,
            new ApacheHttpClientExecutor(client));
}

From source file:com.twinsoft.convertigo.engine.Context.java

public Vector<String> getCookieStrings() {
    // Use the HandleCookie Property of the transaction to return or not the cookies.
    ///*from   ww w.  j  av  a  2  s  .  c o  m*/
    // We noticed a Bug in tomcat when too much cookies where set in the response to the client. This causes a 
    // IndexOutOfBoundException:  4096 in coyote.
    // To overcome this situation, now you can configure HandleCookies to false in the transaction to prevent cookies to be reflected
    // to the client.
    if (requestedObject instanceof AbstractHttpTransaction) {
        if (!((AbstractHttpTransaction) requestedObject).isHandleCookie())
            return new Vector<String>();
    }

    Vector<String> cookies = new Vector<String>();
    if (httpState != null) {
        Cookie[] httpCookies = httpState.getCookies();
        int len = httpCookies.length;
        Cookie cookie = null;
        String sCookie;

        DateFormat df = new SimpleDateFormat("EEE, dd-MMM-yyyy HH:mm:ss z", Locale.US);
        df.setTimeZone(TimeZone.getTimeZone("GMT"));
        for (int i = 0; i < len; i++) {
            cookie = httpCookies[i];
            sCookie = cookie.getName() + "=" + cookie.getValue() + ";";
            sCookie += (cookie.getExpiryDate() != null) ? "expires=" + df.format(cookie.getExpiryDate()) + ";"
                    : "";
            sCookie += "path=" + cookie.getPath() + ";";
            sCookie += "domain=" + cookie.getDomain() + ";";
            sCookie += cookie.getSecure() ? "secure" : "";
            cookies.add(sCookie);
        }
    }
    return cookies;
}

From source file:com.cyberway.issue.crawler.fetcher.FetchHTTP.java

/**
 * Saves cookies to a file./*ww  w  . j  a  v  a  2s.c  o  m*/
 *
 * Output file is in the Netscape 'cookies.txt' format.
 *
 * @param saveCookiesFile output file.
 */
public void saveCookies(String saveCookiesFile) {
    // Do nothing if cookiesFile is not specified.
    if (saveCookiesFile == null || saveCookiesFile.length() <= 0) {
        return;
    }

    FileOutputStream out = null;
    try {
        out = new FileOutputStream(new File(saveCookiesFile));
        @SuppressWarnings("unchecked")
        Map<String, Cookie> cookies = http.getState().getCookiesMap();
        String tab = "\t";
        out.write("# Heritrix Cookie File\n".getBytes());
        out.write("# This file is the Netscape cookies.txt format\n\n".getBytes());
        for (Cookie cookie : cookies.values()) {
            MutableString line = new MutableString(1024 * 2 /*Guess an initial size*/);
            line.append(cookie.getDomain());
            line.append(tab);
            line.append(cookie.isDomainAttributeSpecified() == true ? "TRUE" : "FALSE");
            line.append(tab);
            line.append(cookie.getPath());
            line.append(tab);
            line.append(cookie.getSecure() == true ? "TRUE" : "FALSE");
            line.append(tab);
            line.append(cookie.getName());
            line.append(tab);
            line.append((null == cookie.getValue()) ? "" : cookie.getValue());
            line.append("\n");
            out.write(line.toString().getBytes());
        }
    } catch (FileNotFoundException e) {
        // We should probably throw FatalConfigurationException.
        System.out.println("Could not find file: " + saveCookiesFile + " (Element: " + ATTR_SAVE_COOKIES + ")");
    } catch (IOException e) {
        e.printStackTrace();
    } finally {
        try {
            if (out != null) {
                out.close();
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}

From source file:com.gargoylesoftware.htmlunit.javascript.host.DocumentTest.java

private void checkCookie(final Cookie cookie, final String name, final String value, final String path,
        final String domain, final boolean secure, final Date date) {
    assertEquals(name, cookie.getName());
    assertEquals(value, cookie.getValue());
    assertNull(cookie.getComment());//ww w .j a v a2s . com
    assertEquals(path, cookie.getPath());
    assertEquals(domain, cookie.getDomain());
    assertEquals(secure, cookie.getSecure());
    assertEquals(date, cookie.getExpiryDate());
}

From source file:nl.nn.adapterframework.util.SsoUtil.java

public static void addSsoCredential(HttpMethod method, HttpState state, String defaultForwardHost) {
    try {//  ww  w  .j a v  a 2 s .com
        String name = SsoUtil.getSsoTokenName();
        String value = SsoUtil.getSsoToken();
        if (StringUtils.isEmpty(value)) {
            if (log.isDebugEnabled())
                log.debug("no value for SsoCredential [" + name + "]");
        } else {
            if (log.isDebugEnabled())
                log.debug("constructing SsoCredentialCookie [" + name + "]");
            Cookie ssoCookie = new Cookie();
            ssoCookie.setName(name);

            ssoCookie.setValue(value);
            String forwardHost;
            try {
                URI uri = method.getURI();
                forwardHost = uri.getHost();
                if (StringUtils.isEmpty(forwardHost)) {
                    if (log.isDebugEnabled())
                        log.debug("did not find host from URI [" + uri.getURI() + "], will use default ["
                                + defaultForwardHost + "] for SSO credential cookie");
                    forwardHost = defaultForwardHost;
                }
            } catch (Throwable t) {
                log.warn("could not extract host from URI", t);
                forwardHost = defaultForwardHost;
            }
            ssoCookie.setDomain(forwardHost);
            // path must have a value, otherwise cookie is not appended to request
            ssoCookie.setPath("/");
            if (log.isDebugEnabled())
                log.debug("set SSOcookie attributes: domain [" + ssoCookie.getDomain() + "] path ["
                        + ssoCookie.getPath() + "]");
            state.addCookie(ssoCookie);
        }

    } catch (Exception e) {
        log.warn("could not obtain SsoToken: " + e.getMessage());
    }
}

From source file:org.apache.abdera.protocol.client.AbderaClient.java

/**
 * Get the cookies for a specific domain and path
 *//*from w  w w .ja  va2  s .  com*/
public Cookie[] getCookies(String domain, String path) {
    Cookie[] cookies = getCookies();
    List<Cookie> list = new ArrayList<Cookie>();
    for (Cookie cookie : cookies) {
        String test = cookie.getDomain();
        if (test.startsWith("."))
            test = test.substring(1);
        if ((domain.endsWith(test) || test.endsWith(domain))
                && (path == null || cookie.getPath().startsWith(path))) {
            list.add(cookie);
        }
    }
    return list.toArray(new Cookie[list.size()]);
}

From source file:org.archive.crawler.fetcher.OptimizeFetchHTTP.java

/**
 * Saves cookies to a file.//  www .java 2  s . c o  m
 *
 * Output file is in the Netscape 'cookies.txt' format.
 *
 * @param saveCookiesFile output file.
 */
public void saveCookies(String saveCookiesFile) {
    // Do nothing if cookiesFile is not specified.
    if (saveCookiesFile == null || saveCookiesFile.length() <= 0) {
        return;
    }

    FileOutputStream out = null;
    try {
        out = new FileOutputStream(new File(saveCookiesFile));
        @SuppressWarnings("unchecked")
        HttpClient http = this.getClient();
        Map<String, Cookie> cookies = http.getState().getCookiesMap();
        String tab = "\t";
        out.write("# Heritrix Cookie File\n".getBytes());
        out.write("# This file is the Netscape cookies.txt format\n\n".getBytes());
        for (Cookie cookie : cookies.values()) {
            MutableString line = new MutableString(1024 * 2 /*Guess an initial size*/);
            line.append(cookie.getDomain());
            line.append(tab);
            line.append(cookie.isDomainAttributeSpecified() == true ? "TRUE" : "FALSE");
            line.append(tab);
            line.append(cookie.getPath());
            line.append(tab);
            line.append(cookie.getSecure() == true ? "TRUE" : "FALSE");
            line.append(tab);
            line.append(cookie.getName());
            line.append(tab);
            line.append((null == cookie.getValue()) ? "" : cookie.getValue());
            line.append("\n");
            out.write(line.toString().getBytes());
        }
    } catch (FileNotFoundException e) {
        // We should probably throw FatalConfigurationException.
        System.out.println("Could not find file: " + saveCookiesFile + " (Element: " + ATTR_SAVE_COOKIES + ")");
    } catch (IOException e) {
        e.printStackTrace();
    } finally {
        try {
            if (out != null) {
                out.close();
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}