Example usage for org.apache.commons.httpclient HttpClient setHostConfiguration

List of usage examples for org.apache.commons.httpclient HttpClient setHostConfiguration

Introduction

In this page you can find the example usage for org.apache.commons.httpclient HttpClient setHostConfiguration.

Prototype

public void setHostConfiguration(HostConfiguration paramHostConfiguration)

Source Link

Usage

From source file:nz.net.kallisti.emusicj.network.http.proxy.HttpClientProvider.java

public HttpClient getHttpClient() {
    HttpState state = getState();/*from   w  w w .  ja v  a  2  s . co m*/
    HttpClient client = new HttpClient();
    client.setState(state);
    if (!prefs.getProxyHost().equals("") && prefs.usingProxy()) {
        HostConfiguration hostConf = new HostConfiguration();
        hostConf.setProxy(prefs.getProxyHost(), prefs.getProxyPort());
        client.setHostConfiguration(hostConf);
        client.getParams().setParameter(CredentialsProvider.PROVIDER, proxyCredsProvider);
    }
    return client;
}

From source file:org.activebpel.rt.axis.bpel.handlers.AeHTTPSender.java

/**
 * invoke creates a socket connection, sends the request SOAP message and then
 * reads the response SOAP message back from the SOAP server
 *
 * @param msgContext the message context
 *
 * @throws AxisFault//w ww . j  a v  a 2  s  .  co m
 * @deprecated
 */
public void invoke(MessageContext msgContext) throws AxisFault {
    HttpMethodBase method = null;
    if (log.isDebugEnabled()) {
        log.debug(Messages.getMessage("enter00", //$NON-NLS-1$
                "CommonsHTTPSender::invoke")); //$NON-NLS-1$
    }
    try {
        URL targetURL = new URL(msgContext.getStrProp(MessageContext.TRANS_URL));

        // no need to retain these, as the cookies/credentials are
        // stored in the message context across multiple requests.
        // the underlying connection manager, however, is retained
        // so sockets get recycled when possible.
        HttpClient httpClient = new HttpClient(connectionManager);
        // the timeout value for allocation of connections from the pool
        httpClient.setHttpConnectionFactoryTimeout(clientProperties.getConnectionPoolTimeout());

        HostConfiguration hostConfiguration = getHostConfiguration(httpClient, targetURL);
        httpClient.setHostConfiguration(hostConfiguration);

        // look for option to send credentials preemptively (w/out challenge)
        // Control of Preemptive is controlled via policy on a per call basis.
        String preemptive = (String) msgContext.getProperty("HTTPPreemptive"); //$NON-NLS-1$
        if ("true".equals(preemptive)) //$NON-NLS-1$
        {
            httpClient.getParams().setAuthenticationPreemptive(true);
        }

        String webMethod = null;
        boolean posting = true;

        // If we're SOAP 1.2, allow the web method to be set from the
        // MessageContext.
        if (msgContext.getSOAPConstants() == SOAPConstants.SOAP12_CONSTANTS) {
            webMethod = msgContext.getStrProp(SOAP12Constants.PROP_WEBMETHOD);
            if (webMethod != null) {
                posting = webMethod.equals(HTTPConstants.HEADER_POST);
            }
        }

        Message reqMessage = msgContext.getRequestMessage();
        if (posting) {
            method = new PostMethod(targetURL.toString());
            addContextInfo(method, httpClient, msgContext, targetURL);
            ByteArrayOutputStream baos = new ByteArrayOutputStream();
            reqMessage.writeTo(baos);
            ((PostMethod) method).setRequestBody(new ByteArrayInputStream(baos.toByteArray()));
            ((PostMethod) method).setUseExpectHeader(false); // workaround for
        } else {
            method = new GetMethod(targetURL.toString());
            addContextInfo(method, httpClient, msgContext, targetURL);
        }
        // don't forget the cookies!
        // Cookies need to be set on HttpState, since HttpMethodBase
        // overwrites the cookies from HttpState
        if (msgContext.getMaintainSession()) {
            HttpState state = httpClient.getState();
            state.setCookiePolicy(CookiePolicy.COMPATIBILITY);
            String host = hostConfiguration.getHost();
            String path = targetURL.getPath();
            boolean secure = hostConfiguration.getProtocol().isSecure();
            String ck1 = (String) msgContext.getProperty(HTTPConstants.HEADER_COOKIE);

            String ck2 = (String) msgContext.getProperty(HTTPConstants.HEADER_COOKIE2);
            if (ck1 != null) {
                int index = ck1.indexOf('=');
                state.addCookie(new Cookie(host, ck1.substring(0, index), ck1.substring(index + 1), path, null,
                        secure));
            }
            if (ck2 != null) {
                int index = ck2.indexOf('=');
                state.addCookie(new Cookie(host, ck2.substring(0, index), ck2.substring(index + 1), path, null,
                        secure));
            }
            httpClient.setState(state);
        }
        boolean hasSoapFault = false;
        int returnCode = httpClient.executeMethod(method);
        String contentType = null;
        String contentLocation = null;
        String contentLength = null;
        if (method.getResponseHeader(HTTPConstants.HEADER_CONTENT_TYPE) != null) {
            contentType = method.getResponseHeader(HTTPConstants.HEADER_CONTENT_TYPE).getValue();
        }
        if (method.getResponseHeader(HTTPConstants.HEADER_CONTENT_LOCATION) != null) {
            contentLocation = method.getResponseHeader(HTTPConstants.HEADER_CONTENT_LOCATION).getValue();
        }
        if (method.getResponseHeader(HTTPConstants.HEADER_CONTENT_LENGTH) != null) {
            contentLength = method.getResponseHeader(HTTPConstants.HEADER_CONTENT_LENGTH).getValue();
        }
        contentType = (null == contentType) ? null : contentType.trim();
        if ((returnCode > 199) && (returnCode < 300)) {

            // SOAP return is OK - so fall through
        } else if (msgContext.getSOAPConstants() == SOAPConstants.SOAP12_CONSTANTS) {
            // For now, if we're SOAP 1.2, fall through, since the range of
            // valid result codes is much greater
        } else if ((contentType != null) && !contentType.equals("text/html") //$NON-NLS-1$
                && ((returnCode > 499) && (returnCode < 600))) {

            // SOAP Fault should be in here - so fall through
            hasSoapFault = true;
        } else {
            String statusMessage = method.getStatusText();
            AxisFault fault = new AxisFault("HTTP", //$NON-NLS-1$
                    "(" + returnCode + ")" //$NON-NLS-1$ //$NON-NLS-2$
                            + statusMessage,
                    null, null);

            try {
                fault.setFaultDetailString(Messages.getMessage("return01", //$NON-NLS-1$
                        "" + returnCode, method.getResponseBodyAsString())); //$NON-NLS-1$
                fault.addFaultDetail(Constants.QNAME_FAULTDETAIL_HTTPERRORCODE, Integer.toString(returnCode));
                throw fault;
            } finally {
                method.releaseConnection(); // release connection back to pool.
            }
        }

        // wrap the response body stream so that close() also releases the connection back to the pool.
        InputStream releaseConnectionOnCloseStream = createConnectionReleasingInputStream(method);

        Message outMsg = new Message(releaseConnectionOnCloseStream, false, contentType, contentLocation);
        // Transfer HTTP headers of HTTP message to MIME headers of SOAP message
        Header[] responseHeaders = method.getResponseHeaders();
        MimeHeaders responseMimeHeaders = outMsg.getMimeHeaders();
        for (int i = 0; i < responseHeaders.length; i++) {
            Header responseHeader = responseHeaders[i];
            responseMimeHeaders.addHeader(responseHeader.getName(), responseHeader.getValue());
        }

        OperationDesc operation = msgContext.getOperation();
        if (hasSoapFault || operation.getMep().equals(OperationType.REQUEST_RESPONSE)) {
            msgContext.setResponseMessage(outMsg);
        } else {
            // Change #1
            //
            // If the operation is a one-way, then don't set the response
            // on the msg context. Doing so will cause Axis to attempt to
            // read from a non-existent SOAP message which causes errors.
            //
            // Note: also checking to see if the return type is our "VOID"
            // QName from the AeInvokeHandler since that's our workaround
            // for avoiding Axis's Thread creation in Call.invokeOneWay()
            //
            // Since the message context won't have a chance to consume the
            // response stream (which closes the connection), close the
            // connection here.
            method.releaseConnection();
        }

        if (log.isDebugEnabled()) {
            if (null == contentLength) {
                log.debug("\n" //$NON-NLS-1$
                        + Messages.getMessage("no00", "Content-Length")); //$NON-NLS-1$ //$NON-NLS-2$
            }
            log.debug("\n" + Messages.getMessage("xmlRecd00")); //$NON-NLS-1$ //$NON-NLS-2$
            log.debug("-----------------------------------------------"); //$NON-NLS-1$
            log.debug(outMsg.getSOAPPartAsString());
        }

        // if we are maintaining session state,
        // handle cookies (if any)
        if (msgContext.getMaintainSession()) {
            Header[] headers = method.getResponseHeaders();
            for (int i = 0; i < headers.length; i++) {
                if (headers[i].getName().equalsIgnoreCase(HTTPConstants.HEADER_SET_COOKIE))
                    msgContext.setProperty(HTTPConstants.HEADER_COOKIE, cleanupCookie(headers[i].getValue()));
                else if (headers[i].getName().equalsIgnoreCase(HTTPConstants.HEADER_SET_COOKIE2))
                    msgContext.setProperty(HTTPConstants.HEADER_COOKIE2, cleanupCookie(headers[i].getValue()));
            }

        }

    } catch (Throwable t) {
        log.debug(t);

        if (method != null) {
            method.releaseConnection();
        }

        // We can call Axis.makeFault() if it's an exception; otherwise
        // construct the AxisFault directly.
        throw (t instanceof Exception) ? AxisFault.makeFault((Exception) t)
                : new AxisFault(t.getLocalizedMessage(), t);
    }

    if (log.isDebugEnabled()) {
        log.debug(Messages.getMessage("exit00", //$NON-NLS-1$
                "CommonsHTTPSender::invoke")); //$NON-NLS-1$
    }
}

From source file:org.ado.picasa.FileDownloader.java

public String downloader(String downloadLocation, String filename) throws Exception {
    if (downloadLocation.trim().equals("")) {
        throw new Exception("The element you have specified does not link to anything!");
    }/*from  w  ww. j  a  v a  2 s. co  m*/
    URL downloadURL = new URL(downloadLocation);
    HttpClient client = new HttpClient();
    client.getParams().setCookiePolicy(CookiePolicy.RFC_2965);
    client.setHostConfiguration(mimicHostConfiguration(downloadURL.getHost(), downloadURL.getPort()));
    client.setState(mimicCookieState(driver.manage().getCookies()));
    HttpMethod getRequest = new GetMethod(downloadURL.getPath());
    FileHandler downloadedFile;
    if (StringUtils.isNotBlank(filename)) {
        downloadedFile = new FileHandler(downloadPath + "/" + filename, true);
    } else {
        downloadedFile = new FileHandler(downloadPath + "/" + downloadURL.getFile().replaceFirst("/|\\\\", ""),
                true);
    }
    try {
        int status = client.executeMethod(getRequest);
        System.out.println(
                String.format("HTTP Status %d when getting '%s'", status, downloadURL.toExternalForm()));
        BufferedInputStream in = new BufferedInputStream(getRequest.getResponseBodyAsStream());
        int offset = 0;
        int len = 4096;
        int bytes = 0;
        byte[] block = new byte[len];
        while ((bytes = in.read(block, offset, len)) > -1) {
            downloadedFile.getWritableFileOutputStream().write(block, 0, bytes);
        }
        downloadedFile.close();
        in.close();
        System.out.println(String.format("File downloaded to '%s'", downloadedFile.getAbsoluteFile()));
    } catch (Exception e) {
        throw new Exception("Download failed!");
    } finally {
        getRequest.releaseConnection();
    }
    return downloadedFile.getAbsoluteFile();
}

From source file:org.alfresco.httpclient.HttpClientFactory.java

protected HttpClient getHttpsClient(String httpsHost, int httpsPort) {
    // Configure a custom SSL socket factory that will enforce mutual authentication
    HttpClient httpClient = constructHttpClient();
    HttpHostFactory hostFactory = new HttpHostFactory(new Protocol("https", sslSocketFactory, httpsPort));
    httpClient.setHostConfiguration(new HostConfigurationWithHostFactory(hostFactory));
    httpClient.getHostConfiguration().setHost(httpsHost, httpsPort, "https");
    return httpClient;
}

From source file:org.apache.cocoon.generation.WebServiceProxyGenerator.java

/**
 * Create one per client session. /*w  w  w .  j  a  v a  2s  . c  o m*/
 */
protected HttpClient getHttpClient() throws ProcessingException {
    URI uri = null;
    String host = null;
    Request request = ObjectModelHelper.getRequest(objectModel);
    Session session = request.getSession(true);
    HttpClient httpClient = null;
    if (session != null) {
        httpClient = (HttpClient) session.getAttribute(HTTP_CLIENT);
    }
    if (httpClient == null) {
        httpClient = new HttpClient();
        HostConfiguration config = httpClient.getHostConfiguration();
        if (config == null) {
            config = new HostConfiguration();
        }

        /* TODO: fixme!
         * When the specified source sent to the wsproxy is not "http" 
         * (e.g. "cocoon:/"), the HttpClient throws an exception.  Does the source
         * here need to be resolved before being set in the HostConfiguration?
         */
        try {
            uri = new URI(this.source);
            host = uri.getHost();
            config.setHost(uri);
        } catch (URIException ex) {
            throw new ProcessingException("URI format error: " + ex, ex);
        }

        // Check the http.nonProxyHosts to see whether or not the current
        // host needs to be served through the proxy server.
        boolean proxiableHost = true;
        String nonProxyHosts = System.getProperty("http.nonProxyHosts");
        if (nonProxyHosts != null) {
            StringTokenizer tok = new StringTokenizer(nonProxyHosts, "|");

            while (tok.hasMoreTokens()) {
                String nonProxiableHost = tok.nextToken().trim();

                // XXX is there any other characters that need to be
                // escaped?
                nonProxiableHost = StringUtils.replace(nonProxiableHost, ".", "\\.");
                nonProxiableHost = StringUtils.replace(nonProxiableHost, "*", ".*");

                // XXX do we want .example.com to match
                // computer.example.com?  it seems to be a very common
                // idiom for the nonProxyHosts, in that case then we want
                // to change "^" to "^.*"
                RE re = null;
                try {
                    re = new RE("^" + nonProxiableHost + "$");
                } catch (Exception ex) {
                    throw new ProcessingException("Regex syntax error: " + ex, ex);
                }

                if (re.match(host)) {
                    proxiableHost = false;
                    break;
                }
            }
        }

        if (proxiableHost && System.getProperty("http.proxyHost") != null) {
            String proxyHost = System.getProperty("http.proxyHost");
            int proxyPort = Integer.parseInt(System.getProperty("http.proxyPort"));
            config.setProxy(proxyHost, proxyPort);
        }

        httpClient.setHostConfiguration(config);

        session.setAttribute(HTTP_CLIENT, httpClient);
    }
    return httpClient;
}

From source file:org.apache.cocoon.transformation.SparqlTransformer.java

private void executeRequest(String url, String method, Map httpHeaders, SourceParameters requestParameters)
        throws ProcessingException, IOException, SAXException {
    HttpClient httpclient = new HttpClient();
    if (System.getProperty("http.proxyHost") != null) {
        // getLogger().warn("PROXY: "+System.getProperty("http.proxyHost"));
        String nonProxyHostsRE = System.getProperty("http.nonProxyHosts", "");
        if (nonProxyHostsRE.length() > 0) {
            String[] pHosts = nonProxyHostsRE.replaceAll("\\.", "\\\\.").replaceAll("\\*", ".*").split("\\|");
            nonProxyHostsRE = "";
            for (String pHost : pHosts) {
                nonProxyHostsRE += "|(^https?://" + pHost + ".*$)";
            }//from ww  w  .j a va 2s.  co m
            nonProxyHostsRE = nonProxyHostsRE.substring(1);
        }
        if (nonProxyHostsRE.length() == 0 || !url.matches(nonProxyHostsRE)) {
            try {
                HostConfiguration hostConfiguration = httpclient.getHostConfiguration();
                hostConfiguration.setProxy(System.getProperty("http.proxyHost"),
                        Integer.parseInt(System.getProperty("http.proxyPort", "80")));
                httpclient.setHostConfiguration(hostConfiguration);
            } catch (Exception e) {
                throw new ProcessingException("Cannot set proxy!", e);
            }
        }
    }
    // Make the HttpMethod.
    HttpMethod httpMethod = null;
    // Do not use empty query parameter.
    if (requestParameters.getParameter(parameterName).trim().equals("")) {
        requestParameters.removeParameter(parameterName);
    }
    // Instantiate different HTTP methods.
    if ("GET".equalsIgnoreCase(method)) {
        httpMethod = new GetMethod(url);
        if (requestParameters.getEncodedQueryString() != null) {
            httpMethod.setQueryString(
                    requestParameters.getEncodedQueryString().replace("\"", "%22")); /* Also escape '"' */
        } else {
            httpMethod.setQueryString("");
        }
    } else if ("POST".equalsIgnoreCase(method)) {
        PostMethod httpPostMethod = new PostMethod(url);
        if (httpHeaders.containsKey(HTTP_CONTENT_TYPE) && ((String) httpHeaders.get(HTTP_CONTENT_TYPE))
                .startsWith("application/x-www-form-urlencoded")) {
            // Encode parameters in POST body.
            Iterator parNames = requestParameters.getParameterNames();
            while (parNames.hasNext()) {
                String parName = (String) parNames.next();
                httpPostMethod.addParameter(parName, requestParameters.getParameter(parName));
            }
        } else {
            // Use query parameter as POST body
            httpPostMethod.setRequestBody(requestParameters.getParameter(parameterName));
            // Add other parameters to query string
            requestParameters.removeParameter(parameterName);
            if (requestParameters.getEncodedQueryString() != null) {
                httpPostMethod.setQueryString(
                        requestParameters.getEncodedQueryString().replace("\"", "%22")); /* Also escape '"' */
            } else {
                httpPostMethod.setQueryString("");
            }
        }
        httpMethod = httpPostMethod;
    } else if ("PUT".equalsIgnoreCase(method)) {
        PutMethod httpPutMethod = new PutMethod(url);
        httpPutMethod.setRequestBody(requestParameters.getParameter(parameterName));
        requestParameters.removeParameter(parameterName);
        httpPutMethod.setQueryString(requestParameters.getEncodedQueryString());
        httpMethod = httpPutMethod;
    } else if ("DELETE".equalsIgnoreCase(method)) {
        httpMethod = new DeleteMethod(url);
        httpMethod.setQueryString(requestParameters.getEncodedQueryString());
    } else {
        throw new ProcessingException("Unsupported method: " + method);
    }
    // Authentication (optional).
    if (credentials != null && credentials.length() > 0) {
        String[] unpw = credentials.split("\t");
        httpclient.getParams().setAuthenticationPreemptive(true);
        httpclient.getState().setCredentials(new AuthScope(httpMethod.getURI().getHost(),
                httpMethod.getURI().getPort(), AuthScope.ANY_REALM),
                new UsernamePasswordCredentials(unpw[0], unpw[1]));
    }
    // Add request headers.
    Iterator headers = httpHeaders.entrySet().iterator();
    while (headers.hasNext()) {
        Map.Entry header = (Map.Entry) headers.next();
        httpMethod.addRequestHeader((String) header.getKey(), (String) header.getValue());
    }
    // Declare some variables before the try-block.
    XMLizer xmlizer = null;
    try {
        // Execute the request.
        int responseCode;
        responseCode = httpclient.executeMethod(httpMethod);
        // Handle errors, if any.
        if (responseCode < 200 || responseCode >= 300) {
            if (showErrors) {
                AttributesImpl attrs = new AttributesImpl();
                attrs.addCDATAAttribute("status", "" + responseCode);
                xmlConsumer.startElement(SPARQL_NAMESPACE_URI, "error", "sparql:error", attrs);
                String responseBody = httpMethod.getStatusText(); //httpMethod.getResponseBodyAsString();
                xmlConsumer.characters(responseBody.toCharArray(), 0, responseBody.length());
                xmlConsumer.endElement(SPARQL_NAMESPACE_URI, "error", "sparql:error");
                return; // Not a nice, but quick and dirty way to end.
            } else {
                throw new ProcessingException("Received HTTP status code " + responseCode + " "
                        + httpMethod.getStatusText() + ":\n" + httpMethod.getResponseBodyAsString());
            }
        }
        // Parse the response
        if (responseCode == 204) { // No content.
            String statusLine = httpMethod.getStatusLine().toString();
            xmlConsumer.startElement(SPARQL_NAMESPACE_URI, "result", "sparql:result", EMPTY_ATTRIBUTES);
            xmlConsumer.characters(statusLine.toCharArray(), 0, statusLine.length());
            xmlConsumer.endElement(SPARQL_NAMESPACE_URI, "result", "sparql:result");
        } else if (parse.equalsIgnoreCase("xml")) {
            InputStream responseBodyStream = httpMethod.getResponseBodyAsStream();
            xmlizer = (XMLizer) manager.lookup(XMLizer.ROLE);
            xmlizer.toSAX(responseBodyStream, "text/xml", httpMethod.getURI().toString(),
                    new IncludeXMLConsumer(xmlConsumer));
            responseBodyStream.close();
        } else if (parse.equalsIgnoreCase("text")) {
            xmlConsumer.startElement(SPARQL_NAMESPACE_URI, "result", "sparql:result", EMPTY_ATTRIBUTES);
            String responseBody = httpMethod.getResponseBodyAsString();
            xmlConsumer.characters(responseBody.toCharArray(), 0, responseBody.length());
            xmlConsumer.endElement(SPARQL_NAMESPACE_URI, "result", "sparql:result");
        } else {
            throw new ProcessingException("Unknown parse type: " + parse);
        }
    } catch (ServiceException e) {
        throw new ProcessingException("Cannot find the right XMLizer for " + XMLizer.ROLE, e);
    } finally {
        if (xmlizer != null)
            manager.release((Component) xmlizer);
        httpMethod.releaseConnection();
    }
}

From source file:org.apache.jackrabbit.spi2dav.RepositoryServiceImpl.java

protected HttpClient getClient(SessionInfo sessionInfo) throws RepositoryException {
    HttpClient client = (HttpClient) clients.get(sessionInfo);
    if (client == null) {
        client = new HttpClient(connectionManager);
        client.setHostConfiguration(hostConfig);
        // NOTE: null credentials only work if 'missing-auth-mapping' param is
        // set on the server
        org.apache.commons.httpclient.Credentials creds = null;
        if (sessionInfo != null) {
            checkSessionInfo(sessionInfo);
            creds = ((SessionInfoImpl) sessionInfo).getCredentials().getCredentials();
            // always send authentication not waiting for 401
            client.getParams().setAuthenticationPreemptive(true);
        }//from ww w . ja v  a 2s.com
        client.getState().setCredentials(AuthScope.ANY, creds);
        clients.put(sessionInfo, client);
        log.debug("Created Client " + client + " for SessionInfo " + sessionInfo);
    }
    return client;
}

From source file:org.apache.jackrabbit.spi2dav.RepositoryServiceImpl.java

protected HttpClient getClient(SessionInfo sessionInfo) throws RepositoryException {
    Object clientKey = getClientKey(sessionInfo);
    HttpClient client = clients.get(clientKey);
    if (client == null) {
        client = new HttpClient(connectionManager);
        client.setHostConfiguration(hostConfig);
        // NOTE: null credentials only work if 'missing-auth-mapping' param is
        // set on the server
        org.apache.commons.httpclient.Credentials creds = null;
        if (sessionInfo != null) {
            checkSessionInfo(sessionInfo);
            creds = ((SessionInfoImpl) sessionInfo).getCredentials().getCredentials();
            // always send authentication not waiting for 401
            client.getParams().setAuthenticationPreemptive(true);
        }/*www .  jav  a 2 s . co m*/
        client.getState().setCredentials(AuthScope.ANY, creds);
        clients.put(clientKey, client);
        log.debug("Created Client " + client + " for SessionInfo " + sessionInfo);
    }
    return client;
}

From source file:org.apache.jmeter.protocol.http.sampler.HTTPHC3Impl.java

/**
 * Returns an <code>HttpConnection</code> fully ready to attempt
 * connection. This means it sets the request method (GET or POST), headers,
 * cookies, and authorization for the URL request.
 * <p>//from  www  .j a  v  a  2s.c om
 * The request infos are saved into the sample result if one is provided.
 *
 * @param u
 *            <code>URL</code> of the URL request
 * @param httpMethod
 *            GET/PUT/HEAD etc
 * @param res
 *            sample result to save request infos to
 * @return <code>HttpConnection</code> ready for .connect
 * @exception IOException
 *                if an I/O Exception occurs
 */
protected HttpClient setupConnection(URL u, HttpMethodBase httpMethod, HTTPSampleResult res)
        throws IOException {

    String urlStr = u.toString();

    org.apache.commons.httpclient.URI uri = new org.apache.commons.httpclient.URI(urlStr, false);

    String schema = uri.getScheme();
    if ((schema == null) || (schema.length() == 0)) {
        schema = HTTPConstants.PROTOCOL_HTTP;
    }

    final boolean isHTTPS = HTTPConstants.PROTOCOL_HTTPS.equalsIgnoreCase(schema);
    if (isHTTPS) {
        SSLManager.getInstance(); // ensure the manager is initialised
        // we don't currently need to do anything further, as this sets the default https protocol
    }

    Protocol protocol = Protocol.getProtocol(schema);

    String host = uri.getHost();
    int port = uri.getPort();

    /*
     *  We use the HostConfiguration as the key to retrieve the HttpClient,
     *  so need to ensure that any items used in its equals/hashcode methods are
     *  not changed after use, i.e.:
     *  host, port, protocol, localAddress, proxy
     *
    */
    HostConfiguration hc = new HostConfiguration();
    hc.setHost(host, port, protocol); // All needed to ensure re-usablility

    // Set up the local address if one exists
    final InetAddress inetAddr = getIpSourceAddress();
    if (inetAddr != null) {// Use special field ip source address (for pseudo 'ip spoofing')
        hc.setLocalAddress(inetAddr);
    } else {
        hc.setLocalAddress(localAddress); // null means use the default
    }

    final String proxyHost = getProxyHost();
    final int proxyPort = getProxyPortInt();

    boolean useStaticProxy = isStaticProxy(host);
    boolean useDynamicProxy = isDynamicProxy(proxyHost, proxyPort);

    if (useDynamicProxy) {
        hc.setProxy(proxyHost, proxyPort);
        useStaticProxy = false; // Dynamic proxy overrules static proxy
    } else if (useStaticProxy) {
        if (log.isDebugEnabled()) {
            log.debug("Setting proxy: " + PROXY_HOST + ":" + PROXY_PORT);
        }
        hc.setProxy(PROXY_HOST, PROXY_PORT);
    }

    Map<HostConfiguration, HttpClient> map = httpClients.get();
    // N.B. HostConfiguration.equals() includes proxy settings in the compare.
    HttpClient httpClient = map.get(hc);

    if (httpClient != null && resetSSLContext && isHTTPS) {
        httpClient.getHttpConnectionManager().closeIdleConnections(-1000);
        httpClient = null;
        JsseSSLManager sslMgr = (JsseSSLManager) SSLManager.getInstance();
        sslMgr.resetContext();
        resetSSLContext = false;
    }

    if (httpClient == null) {
        httpClient = new HttpClient(new SimpleHttpConnectionManager());
        httpClient.getParams().setParameter(HttpMethodParams.RETRY_HANDLER,
                new DefaultHttpMethodRetryHandler(RETRY_COUNT, false));
        if (log.isDebugEnabled()) {
            log.debug("Created new HttpClient: @" + System.identityHashCode(httpClient));
        }
        httpClient.setHostConfiguration(hc);
        map.put(hc, httpClient);
    } else {
        if (log.isDebugEnabled()) {
            log.debug("Reusing the HttpClient: @" + System.identityHashCode(httpClient));
        }
    }

    // Set up any required Proxy credentials
    if (useDynamicProxy) {
        String user = getProxyUser();
        if (user.length() > 0) {
            httpClient.getState().setProxyCredentials(
                    new AuthScope(proxyHost, proxyPort, null, AuthScope.ANY_SCHEME),
                    new NTCredentials(user, getProxyPass(), localHost, PROXY_DOMAIN));
        } else {
            httpClient.getState().clearProxyCredentials();
        }
    } else {
        if (useStaticProxy) {
            if (PROXY_USER.length() > 0) {
                httpClient.getState().setProxyCredentials(
                        new AuthScope(PROXY_HOST, PROXY_PORT, null, AuthScope.ANY_SCHEME),
                        new NTCredentials(PROXY_USER, PROXY_PASS, localHost, PROXY_DOMAIN));
            }
        } else {
            httpClient.getState().clearProxyCredentials();
        }
    }

    int rto = getResponseTimeout();
    if (rto > 0) {
        httpMethod.getParams().setSoTimeout(rto);
    }

    int cto = getConnectTimeout();
    if (cto > 0) {
        httpClient.getHttpConnectionManager().getParams().setConnectionTimeout(cto);
    }

    // Allow HttpClient to handle the redirects:
    httpMethod.setFollowRedirects(getAutoRedirects());

    // a well-behaved browser is supposed to send 'Connection: close'
    // with the last request to an HTTP server. Instead, most browsers
    // leave it to the server to close the connection after their
    // timeout period. Leave it to the JMeter user to decide.
    if (getUseKeepAlive()) {
        httpMethod.setRequestHeader(HTTPConstants.HEADER_CONNECTION, HTTPConstants.KEEP_ALIVE);
    } else {
        httpMethod.setRequestHeader(HTTPConstants.HEADER_CONNECTION, HTTPConstants.CONNECTION_CLOSE);
    }

    setConnectionHeaders(httpMethod, u, getHeaderManager(), getCacheManager());
    String cookies = setConnectionCookie(httpMethod, u, getCookieManager());

    setConnectionAuthorization(httpClient, u, getAuthManager());

    if (res != null) {
        res.setCookies(cookies);
    }

    return httpClient;
}

From source file:org.apache.maven.plugin.jira.AbstractJiraDownloader.java

/**
 * Execute the query on the JIRA server.
 *
 * @throws Exception on error/*  w  w  w .  j  ava  2 s .c  om*/
 */
public void doExecute() throws Exception {
    try {
        HttpClient client = new HttpClient();

        // MCHANGES-89 Allow circular redirects
        HttpClientParams clientParams = client.getParams();
        clientParams.setBooleanParameter(HttpClientParams.ALLOW_CIRCULAR_REDIRECTS, true);

        HttpState state = new HttpState();

        HostConfiguration hc = new HostConfiguration();

        client.setHostConfiguration(hc);

        client.setState(state);

        Map<String, String> urlMap = JiraHelper.getJiraUrlAndProjectId(project.getIssueManagement().getUrl());

        String jiraUrl = urlMap.get("url");
        getLog().debug("JIRA lives at: " + jiraUrl);

        String jiraId = urlMap.get("id");

        determineProxy(jiraUrl, client);

        prepareBasicAuthentication(client);

        boolean jiraAuthenticationSuccessful = false;
        if (isJiraAuthenticationConfigured()) {
            jiraAuthenticationSuccessful = doJiraAuthentication(client, jiraUrl);
        }

        if ((isJiraAuthenticationConfigured() && jiraAuthenticationSuccessful)
                || !isJiraAuthenticationConfigured()) {
            if (jiraId == null || jiraId.length() == 0) {
                log.debug("The JIRA URL " + project.getIssueManagement().getUrl()
                        + " doesn't include a pid, trying to extract it from JIRA.");
                jiraId = JiraHelper.getPidFromJira(log, project.getIssueManagement().getUrl(), client);
            }

            if (jiraId == null) {
                getLog().error("The issue management URL in the POM does not include a pid,"
                        + " and it was not possible to extract it from the page at that URL.");
            } else {
                // create the URL for getting the proper issues from JIRA
                String fullURL = jiraUrl + "/secure/IssueNavigator.jspa?view=rss&pid=" + jiraId;

                if (getFixFor() != null) {
                    fullURL += "&fixfor=" + getFixFor();
                }

                String createdFilter = createFilter();
                if (createdFilter.charAt(0) != '&') {
                    fullURL += "&";
                }
                fullURL += createdFilter;

                fullURL += ("&tempMax=" + nbEntriesMax + "&reset=true&decorator=none");

                if (log.isDebugEnabled()) {
                    log.debug("download jira issues from url " + fullURL);
                }

                // execute the GET
                download(client, fullURL);
            }
        }
    } catch (Exception e) {
        if (project.getIssueManagement() != null) {
            getLog().error("Error accessing " + project.getIssueManagement().getUrl(), e);
        } else {
            getLog().error("Error accessing mock project issues", e);
        }
    }
}