Example usage for org.apache.commons.httpclient HttpState getCookies

List of usage examples for org.apache.commons.httpclient HttpState getCookies

Introduction

In this page you can find the example usage for org.apache.commons.httpclient HttpState getCookies.

Prototype

public Cookie[] getCookies()

Source Link

Usage

From source file:com.zimbra.cs.servlet.ZimbraServlet.java

private static boolean hasZimbraAuthCookie(HttpState state) {
    Cookie[] cookies = state.getCookies();
    if (cookies == null)
        return false;

    for (Cookie c : cookies) {
        if (c.getName().equals(ZimbraCookie.COOKIE_ZM_AUTH_TOKEN))
            return true;
    }//  www.jav a2 s.  c o  m
    return false;
}

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

/**
 * Process the response data/*from ww w.  j ava  2  s. c  om*/
 */
public static void processResponse(byte[] bResponse, long startTime, long endTime, BaseResponse response,
        String message, int httpCode, Header[] headers, HttpState httpstate) {

    try {
        if (response == null) {
            response = newResponseObject(headers);
        }

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

        // Get response header information
        for (int h = 0; h < headers.length; h++) {
            response.setHeader(headers[h].getName(), headers[h].getValue());
        }

        response.setCookies(httpstate.getCookies());
        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) {
                logger.warn(LogUtil.getLogMessage("cannot decode gzip stream: " + e, LogEventType.System));
            }
        }
        response.setResponseBody(bResponse);

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

From source file:com.dtolabs.client.utils.BaseFormAuthenticator.java

/**
 * Check the http state cookies to see if we have the proper session id cookie
 *
 * @param reqUrl   URL being requested//  www .j a  v  a 2 s.  co  m
 * @param state    HTTP state object
 * @param basePath base path of requests
 *
 * @return true if a cookie matching the basePath, server host and port, and request protocol and appropriate
 *         session cookie name is found
 */
public static boolean hasSessionCookie(final URL reqUrl, final HttpState state, final String basePath) {

    final CookieSpec cookiespec = CookiePolicy.getDefaultSpec();
    final Cookie[] initcookies = cookiespec.match(reqUrl.getHost(),
            reqUrl.getPort() > 0 ? reqUrl.getPort() : 80, basePath.endsWith("/") ? basePath : basePath + "/",
            HTTP_SECURE_PROTOCOL.equalsIgnoreCase(reqUrl.getProtocol()), state.getCookies());
    boolean hasSession = false;
    if (initcookies.length == 0) {
        hasSession = false;
    } else {
        for (final Cookie cookie : initcookies) {
            if (JAVA_SESSION_COOKIE_NAME.equals(cookie.getName())
                    || JAVA_SESSION_COOKIE_PATTERN.matcher(cookie.getName()).matches()) {
                logger.debug("Saw session cookie: " + cookie.getName());
                hasSession = true;
                break;
            }
        }
    }
    return hasSession;
}

From source file:net.sf.antcontrib.net.httpclient.GetCookieTask.java

protected void execute(HttpStateType stateType) throws BuildException {

    if (realm == null || path == null) {
        throw new BuildException("'realm' and 'path' attributes are required");
    }//  w ww  .  java  2 s  . co m

    HttpState state = stateType.getState();
    CookieSpec spec = CookiePolicy.getCookieSpec(cookiePolicy);
    Cookie cookies[] = state.getCookies();
    Cookie matches[] = spec.match(realm, port, path, secure, cookies);

    if (name != null) {
        Cookie c = findCookie(matches, name);
        if (c != null) {
            matches = new Cookie[] { c };
        } else {
            matches = new Cookie[0];
        }
    }

    if (property != null) {
        if (matches != null && matches.length > 0) {
            Property p = (Property) getProject().createTask("property");
            p.setName(property);
            p.setValue(matches[0].getValue());
            p.perform();
        }
    } else if (prefix != null) {
        if (matches != null && matches.length > 0) {
            for (int i = 0; i < matches.length; i++) {
                String propName = prefix + matches[i].getName();
                Property p = (Property) getProject().createTask("property");
                p.setName(propName);
                p.setValue(matches[i].getValue());
                p.perform();
            }
        }
    } else {
        throw new BuildException("Nothing to set");
    }
}

From source file:com.twinsoft.convertigo.beans.statements.CookiesGetStatement.java

@Override
public boolean execute(Context javascriptContext, Scriptable scope) throws EngineException {
    if (isEnable()) {
        if (super.execute(javascriptContext, scope)) {
            if (this.getConnector().handleCookie) {
                HttpState httpState = this.getParentTransaction().context.httpState;
                if (httpState != null) {
                    Cookie[] cookies = httpState.getCookies();
                    String code = variable + "=";
                    boolean array = separator.length() == 0;
                    if (cookies.length == 0) {
                        code += array ? "[]" : "''";
                    } else {
                        String sep = array ? "\",\"" : separator;
                        code += (array ? "[\"" : "\"")
                                + CookiesUtils.formatCookie(cookies[0]).replace("\"", "\\\"");
                        for (int i = 1; i < cookies.length; i++) {
                            code += sep + CookiesUtils.formatCookie(cookies[i]).replace("\"", "\\\"");
                        }//from ww  w.jav a 2s .com
                        code += (array ? "\"]" : "\"");
                    }
                    evaluate(javascriptContext, scope, code, "CookiesGet", true);
                } else {
                    Engine.logBeans.debug("(CookiesGetStatement) No httpState for cookies");
                }
            }
            return true;
        }
    }
    return false;
}

From source file:com.gargoylesoftware.htmlunit.CookieManagerTest.java

/**
 * Verifies the basic cookie manager behavior.
 * @throws Exception if an error occurs/*from www.j  a  v  a 2 s.  co m*/
 */
@Test
public void basicBehavior() throws Exception {
    // Create a new cookie manager.
    final CookieManager mgr = new CookieManager();
    assertTrue(mgr.isCookiesEnabled());
    assertTrue(mgr.getCookies().isEmpty());

    // Add a cookie to the manager.
    final Cookie cookie = new Cookie("a", "b");
    mgr.addCookie(cookie);
    assertFalse(mgr.getCookies().isEmpty());

    // Update an HTTP state.
    final HttpState state = new HttpState();
    mgr.updateState(state);
    assertEquals(1, state.getCookies().length);

    // Remove the cookie from the manager.
    mgr.removeCookie(cookie);
    assertTrue(mgr.getCookies().isEmpty());

    // Update an HTTP state after removing the cookie.
    mgr.updateState(state);
    assertEquals(0, state.getCookies().length);

    // Add the cookie back to the manager.
    mgr.addCookie(cookie);
    assertFalse(mgr.getCookies().isEmpty());

    // Update an HTTP state after adding the cookie back to the manager.
    mgr.updateState(state);
    assertEquals(1, state.getCookies().length);

    // Clear all cookies from the manager.
    mgr.clearCookies();
    assertTrue(mgr.getCookies().isEmpty());

    // Update an HTTP state after clearing all cookies from the manager.
    mgr.updateState(state);
    assertEquals(0, state.getCookies().length);

    // Disable cookies.
    mgr.setCookiesEnabled(false);
    assertFalse(mgr.isCookiesEnabled());

    // Add a cookie after disabling cookies.
    mgr.addCookie(cookie);
    assertFalse(mgr.getCookies().isEmpty());

    // Update an HTTP state after adding a cookie while cookies are disabled.
    mgr.updateState(state);
    assertEquals(0, state.getCookies().length);

    // Enable cookies again.
    mgr.setCookiesEnabled(true);
    assertTrue(mgr.isCookiesEnabled());

    // Update an HTTP state after enabling cookies again.
    mgr.updateState(state);
    assertEquals(1, state.getCookies().length);

    // Update the manager with a new state.
    final Cookie cookie2 = new Cookie("x", "y");
    final HttpState state2 = new HttpState();
    state2.addCookie(cookie2.toHttpClient());
    mgr.updateFromState(state2);
    assertEquals(1, mgr.getCookies().size());
    assertEquals(cookie2, mgr.getCookies().iterator().next());
}

From source file:com.celamanzi.liferay.portlets.rails286.OnlineClient.java

/** Returns a HttpState fixed with cookies.
 *
 * @since 0.8.0/*from  ww  w  .  j  av a2 s . co m*/
 */
protected HttpState preparedHttpState() {
    HttpState state = new HttpState();

    if (cookies != null) {
        // Add cookies to the state
        state.addCookies(cookies);
    }

    if (log.isDebugEnabled()) {
        Cookie[] _cookies = state.getCookies();
        debugCookies(_cookies);
    }

    return state;
}

From source file:com.zimbra.common.soap.SoapHttpTransport.java

public Element invoke(Element document, boolean raw, boolean noSession, String requestedAccountId,
        String changeToken, String tokenType, ResponseHandler respHandler)
        throws IOException, HttpException, ServiceException {
    PostMethod method = null;//  ww w .  j a  v  a 2s . co m

    try {
        // Assemble post method.  Append document name, so that the request
        // type is written to the access log.
        String uri, query;
        int i = mUri.indexOf('?');
        if (i >= 0) {
            uri = mUri.substring(0, i);
            query = mUri.substring(i);
        } else {
            uri = mUri;
            query = "";
        }
        if (!uri.endsWith("/"))
            uri += '/';
        uri += getDocumentName(document);
        method = new PostMethod(uri + query);

        // Set user agent if it's specified.
        String agentName = getUserAgentName();
        if (agentName != null) {
            String agentVersion = getUserAgentVersion();
            if (agentVersion != null)
                agentName += " " + agentVersion;
            method.setRequestHeader(new Header("User-Agent", agentName));
        }

        // the content-type charset will determine encoding used
        // when we set the request body
        method.setRequestHeader("Content-Type", getRequestProtocol().getContentType());
        if (getClientIp() != null) {
            method.setRequestHeader(RemoteIP.X_ORIGINATING_IP_HEADER, getClientIp());
            if (ZimbraLog.misc.isDebugEnabled()) {
                ZimbraLog.misc.debug("set remote IP header [%s] to [%s]", RemoteIP.X_ORIGINATING_IP_HEADER,
                        getClientIp());
            }
        }
        Element soapReq = generateSoapMessage(document, raw, noSession, requestedAccountId, changeToken,
                tokenType);
        String soapMessage = SoapProtocol.toString(soapReq, getPrettyPrint());
        HttpMethodParams params = method.getParams();

        method.setRequestEntity(new StringRequestEntity(soapMessage, null, "UTF-8"));

        if (getRequestProtocol().hasSOAPActionHeader())
            method.setRequestHeader("SOAPAction", mUri);

        if (mCustomHeaders != null) {
            for (Map.Entry<String, String> entry : mCustomHeaders.entrySet())
                method.setRequestHeader(entry.getKey(), entry.getValue());
        }

        String host = method.getURI().getHost();
        HttpState state = HttpClientUtil.newHttpState(getAuthToken(), host, this.isAdmin());
        String trustedToken = getTrustedToken();
        if (trustedToken != null) {
            state.addCookie(
                    new Cookie(host, ZimbraCookie.COOKIE_ZM_TRUST_TOKEN, trustedToken, "/", null, false));
        }
        params.setCookiePolicy(state.getCookies().length == 0 ? CookiePolicy.IGNORE_COOKIES
                : CookiePolicy.BROWSER_COMPATIBILITY);
        params.setParameter(HttpMethodParams.RETRY_HANDLER,
                new DefaultHttpMethodRetryHandler(mRetryCount - 1, true));
        params.setSoTimeout(mTimeout);
        params.setVersion(HttpVersion.HTTP_1_1);
        method.setRequestHeader("Connection", mKeepAlive ? "Keep-alive" : "Close");

        if (mHostConfig != null && mHostConfig.getUsername() != null && mHostConfig.getPassword() != null) {
            state.setProxyCredentials(new AuthScope(null, -1),
                    new UsernamePasswordCredentials(mHostConfig.getUsername(), mHostConfig.getPassword()));
        }

        if (mHttpDebugListener != null) {
            mHttpDebugListener.sendSoapMessage(method, soapReq, state);
        }

        int responseCode = mClient.executeMethod(mHostConfig, method, state);
        // SOAP allows for "200" on success and "500" on failure;
        //   real server issues will probably be "503" or "404"
        if (responseCode != HttpServletResponse.SC_OK
                && responseCode != HttpServletResponse.SC_INTERNAL_SERVER_ERROR)
            throw ServiceException.PROXY_ERROR(method.getStatusLine().toString(), uri);

        // Read the response body.  Use the stream API instead of the byte[]
        // version to avoid HTTPClient whining about a large response.
        InputStreamReader reader = new InputStreamReader(method.getResponseBodyAsStream(),
                SoapProtocol.getCharset());
        String responseStr = "";

        try {
            if (respHandler != null) {
                respHandler.process(reader);
                return null;
            } else {
                responseStr = ByteUtil.getContent(reader, (int) method.getResponseContentLength(), false);
                Element soapResp = parseSoapResponse(responseStr, raw);

                if (mHttpDebugListener != null) {
                    mHttpDebugListener.receiveSoapMessage(method, soapResp);
                }
                return soapResp;
            }
        } catch (SoapFaultException x) {
            // attach request/response to the exception and rethrow
            x.setFaultRequest(soapMessage);
            x.setFaultResponse(responseStr.substring(0, Math.min(10240, responseStr.length())));
            throw x;
        }
    } finally {
        // Release the connection to the connection manager
        if (method != null)
            method.releaseConnection();

        // really not necessary if running in the server because the reaper thread
        // of our connection manager will take care it.
        // if called from CLI, all connections will be closed when the CLI
        // exits.  Leave it here anyway.
        if (!mKeepAlive)
            mClient.getHttpConnectionManager().closeIdleConnections(0);
    }
}

From source file:fedora.server.security.servletfilters.pubcookie.ConnectPubcookie.java

public final void connect(String urlString, Map requestParameters, Cookie[] requestCookies,
        String truststoreLocation, String truststorePassword) {
    log.debug(this.getClass().getName() + ".connect() " + " url==" + urlString + " requestParameters=="
            + requestParameters + " requestCookies==" + requestCookies);
    responseCookies2 = null;/*w  w w.j av  a2 s .  c  om*/
    URL url = null;
    try {
        url = new URL(urlString);
    } catch (MalformedURLException mue) {
        log.error(this.getClass().getName() + ".connect() " + "bad configured url==" + urlString);
    }

    if (urlString.startsWith("https:") && null != truststoreLocation && !"".equals(truststoreLocation)
            && null != truststorePassword && !"".equals(truststorePassword)) {
        log.debug("setting " + FilterPubcookie.TRUSTSTORE_LOCATION_KEY + " to " + truststoreLocation);
        System.setProperty(FilterPubcookie.TRUSTSTORE_LOCATION_KEY, truststoreLocation);
        log.debug("setting " + FilterPubcookie.TRUSTSTORE_PASSWORD_KEY + " to " + truststorePassword);
        System.setProperty(FilterPubcookie.TRUSTSTORE_PASSWORD_KEY, truststorePassword);

        log.debug("setting " + FilterPubcookie.KEYSTORE_LOCATION_KEY + " to " + truststoreLocation);
        System.setProperty(FilterPubcookie.KEYSTORE_LOCATION_KEY, truststoreLocation);
        log.debug("setting " + FilterPubcookie.KEYSTORE_PASSWORD_KEY + " to " + truststorePassword);
        System.setProperty(FilterPubcookie.KEYSTORE_PASSWORD_KEY, truststorePassword);

        System.setProperty("javax.net.debug", "ssl,handshake,data,trustmanager");

    } else {
        log.debug("DIAGNOSTIC urlString==" + urlString);
        log.debug("didn't set " + FilterPubcookie.TRUSTSTORE_LOCATION_KEY + " to " + truststoreLocation);
        log.debug("didn't set " + FilterPubcookie.TRUSTSTORE_PASSWORD_KEY + " to " + truststorePassword);
    }

    /*
     * log.debug("\n-a-"); Protocol easyhttps = null; try { easyhttps = new
     * Protocol("https", (ProtocolSocketFactory) new
     * EasySSLProtocolSocketFactory(), 443); } catch (Throwable t) {
     * log.debug(t); log.debug(t.getMessage()); if (t.getCause() != null)
     * log.debug(t.getCause().getMessage()); } log.debug("\n-b-");
     * Protocol.registerProtocol("https", easyhttps); log.debug("\n-c-");
     */

    HttpClient client = new HttpClient();
    log.debug(this.getClass().getName() + ".connect() " + " b4 calling setup");
    log.debug(this.getClass().getName() + ".connect() requestCookies==" + requestCookies);
    HttpMethodBase method = setup(client, url, requestParameters, requestCookies);
    log.debug(this.getClass().getName() + ".connect() " + " after calling setup");
    int statusCode = 0;
    try {
        log.debug(this.getClass().getName() + ".connect() " + " b4 calling executeMethod");
        client.executeMethod(method);
        log.debug(this.getClass().getName() + ".connect() " + " after calling executeMethod");
        statusCode = method.getStatusCode();
        log.debug(
                this.getClass().getName() + ".connect() " + "(with configured url) statusCode==" + statusCode);
    } catch (Exception e) {
        log.error(this.getClass().getName() + ".connect() " + "failed original connect, url==" + urlString);
        log.error(e);
        log.error(e.getMessage());
        if (e.getCause() != null) {
            log.error(e.getCause().getMessage());
        }
        e.printStackTrace();
    }

    log.debug(this.getClass().getName() + ".connect() " + " status code==" + statusCode);

    if (302 == statusCode) {
        Header redirectHeader = method.getResponseHeader("Location");
        if (redirectHeader != null) {
            String redirectString = redirectHeader.getValue();
            if (redirectString != null) {
                URL redirectURL = null;
                try {
                    redirectURL = new URL(redirectString);
                    method = setup(client, redirectURL, requestParameters, requestCookies);
                } catch (MalformedURLException mue) {
                    log.error(this.getClass().getName() + ".connect() " + "bad redirect, url==" + urlString);
                }
                statusCode = 0;
                try {
                    client.executeMethod(method);
                    statusCode = method.getStatusCode();
                    log.debug(this.getClass().getName() + ".connect() " + "(on redirect) statusCode=="
                            + statusCode);
                } catch (Exception e) {
                    log.error(this.getClass().getName() + ".connect() " + "failed redirect connect");
                }
            }
        }
    }
    if (statusCode == 200) { // this is either the original, non-302, status code or the status code after redirect
        log.debug(this.getClass().getName() + ".connect() " + "status code 200");
        String content = null;
        try {
            log.debug(this.getClass().getName() + ".connect() " + "b4 gRBAS()");
            content = method.getResponseBodyAsString();
            log.debug(this.getClass().getName() + ".connect() " + "after gRBAS() content==" + content);
        } catch (IOException e) {
            log.error(this.getClass().getName() + ".connect() " + "couldn't get content");
            return;
        }
        if (content == null) {
            log.error(this.getClass().getName() + ".connect() content==null");
            return;
        } else {
            log.debug(this.getClass().getName() + ".connect() content != null, about to new Tidy");
            Tidy tidy = null;
            try {
                tidy = new Tidy();
            } catch (Throwable t) {
                log.debug("new Tidy didn't");
                log.debug(t);
                log.debug(t.getMessage());
                if (t != null) {
                    log.debug(t.getCause().getMessage());
                }
            }
            log.debug(this.getClass().getName() + ".connect() after newing Tidy, tidy==" + tidy);
            byte[] inputBytes = content.getBytes();
            log.debug(this.getClass().getName() + ".connect() A1");
            ByteArrayInputStream inputStream = new ByteArrayInputStream(inputBytes);
            log.debug(this.getClass().getName() + ".connect() A2");
            responseDocument = tidy.parseDOM(inputStream, null); //use returned root node as only output
            log.debug(this.getClass().getName() + ".connect() A3");
        }
        log.debug(this.getClass().getName() + ".connect() " + "b4 getState()");
        HttpState state = client.getState();
        log.debug(this.getClass().getName() + ".connect() state==" + state);
        try {
            responseCookies2 = method.getRequestHeaders();
            log.debug(this.getClass().getName() + ".connect() just got headers");
            for (Header element : responseCookies2) {
                log.debug(this.getClass().getName() + ".connect() header==" + element);
            }
            responseCookies = state.getCookies();
            log.debug(this.getClass().getName() + ".connect() responseCookies==" + responseCookies);
        } catch (Throwable t) {
            log.error(this.getClass().getName() + ".connect() exception==" + t.getMessage());
            if (t.getCause() != null) {
                log.error(this.getClass().getName() + ".connect() cause==" + t.getCause().getMessage());
            }
        }
        completedFully = true;
        log.debug(this.getClass().getName() + ".connect() completedFully==" + completedFully);
    }
}

From source file:com.zimbra.qa.unittest.prov.soap.SoapDebugListener.java

@Override
public void sendSoapMessage(PostMethod postMethod, Element envelope, HttpState httpState) {
    if (level == Level.OFF) {
        return;/* ww  w. j  a v  a 2s .  c  o m*/
    }

    System.out.println();
    System.out.println("=== Request ===");

    if (Level.needsHeader(level)) {
        try {
            URI uri = postMethod.getURI();
            System.out.println(uri.toString());
        } catch (URIException e) {
            e.printStackTrace();
        }

        // headers
        Header[] headers = postMethod.getRequestHeaders();
        for (Header header : headers) {
            System.out.println(header.toString().trim()); // trim the ending crlf
        }
        System.out.println();

        //cookies
        if (httpState != null) {
            Cookie[] cookies = httpState.getCookies();
            for (Cookie cookie : cookies) {
                System.out.println("Cookie: " + cookie.toString());
            }
        }
        System.out.println();
    }

    if (Level.needsBody(level)) {
        System.out.println(envelope.prettyPrint());
    }
}