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

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

Introduction

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

Prototype

public HttpConnectionManager getHttpConnectionManager()

Source Link

Usage

From source file:org.apache.commons.httpclient.demo.httpclientfileupload.java

public static void main(String[] args) {

    MultipartPostMethod filePost = new MultipartPostMethod(targetURL);

    File targetFilePath = new File("htmlparser.zip");

    try {/*from w  w w .java2s. c om*/
        filePost.addParameter("fileName", targetFilePath);
    } catch (FileNotFoundException ex) {
        ex.printStackTrace();
    }

    HttpClient client = new HttpClient();

    //,

    client.getHttpConnectionManager().getParams().setConnectionTimeout(5000);

    //        try {
    //            int status = client.executeMethod(filePost);
    //        } catch (IOException ex1) {
    //            ex1.printStackTrace();
    //        }

}

From source file:org.apache.cxf.aegis.jaxws.AegisJaxwsGetTest.java

private HttpClient createClient() {
    HttpClient httpClient = new HttpClient();
    httpClient.getHttpConnectionManager().getParams().setConnectionTimeout(5000);
    return httpClient;
}

From source file:org.apache.gobblin.kafka.schemareg.HttpClientFactory.java

@Override
public HttpClient create() throws Exception {

    HttpClient client = new HttpClient();
    if (soTimeout >= 0) {
        client.getParams().setSoTimeout(soTimeout);
    }// w w  w  .ja  v a  2 s .  c o m

    if (connTimeout >= 0) {
        client.getHttpConnectionManager().getParams().setConnectionTimeout(connTimeout);
    }

    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 w w  w . j a  v a 2  s .  com
 * 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.jmeter.protocol.http.sampler.HTTPHC3Impl.java

/**
 * //w w  w  .ja  va  2  s .  c o m
 */
private void closeThreadLocalConnections() {
    // Does not need to be synchronised, as all access is from same thread
    Map<HostConfiguration, HttpClient> map = httpClients.get();

    if (map != null) {
        for (HttpClient cl : map.values()) {
            // Can cause NPE in HttpClient 3.1
            //((SimpleHttpConnectionManager)cl.getHttpConnectionManager()).shutdown();// Closes the connection
            // Revert to original method:
            cl.getHttpConnectionManager().closeIdleConnections(-1000);// Closes the connection
        }
        map.clear();
    }
}

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

/** {@inheritDoc} */
@Override//from  w  ww.j a v  a2  s.  c o  m
public boolean interrupt() {
    HttpClient client = savedClient;
    if (client != null) {
        savedClient = null;
        // TODO - not sure this is the best method
        final HttpConnectionManager httpConnectionManager = client.getHttpConnectionManager();
        if (httpConnectionManager instanceof SimpleHttpConnectionManager) {// Should be true
            ((SimpleHttpConnectionManager) httpConnectionManager).shutdown();
        }
    }
    return client != null;
}

From source file:org.apache.maven.plugin.doap.DoapUtil.java

/**
 * Fetch an URL//from  w  w w.  jav a2s  . c  om
 *
 * @param settings the user settings used to fetch the url with an active proxy, if defined.
 * @param url the url to fetch
 * @throws IOException if any
 * @see #DEFAULT_TIMEOUT
 * @since 1.1
 */
public static void fetchURL(Settings settings, URL url) throws IOException {
    if (url == null) {
        throw new IllegalArgumentException("The url is null");
    }

    if ("file".equals(url.getProtocol())) {
        InputStream in = null;
        try {
            in = url.openStream();
        } finally {
            IOUtil.close(in);
        }

        return;
    }

    // http, https...
    HttpClient httpClient = new HttpClient(new MultiThreadedHttpConnectionManager());
    httpClient.getHttpConnectionManager().getParams().setConnectionTimeout(DEFAULT_TIMEOUT);
    httpClient.getHttpConnectionManager().getParams().setSoTimeout(DEFAULT_TIMEOUT);
    httpClient.getParams().setBooleanParameter(HttpClientParams.ALLOW_CIRCULAR_REDIRECTS, true);

    // Some web servers don't allow the default user-agent sent by httpClient
    httpClient.getParams().setParameter(HttpMethodParams.USER_AGENT,
            "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.0)");

    if (settings != null && settings.getActiveProxy() != null) {
        Proxy activeProxy = settings.getActiveProxy();

        ProxyInfo proxyInfo = new ProxyInfo();
        proxyInfo.setNonProxyHosts(activeProxy.getNonProxyHosts());

        if (StringUtils.isNotEmpty(activeProxy.getHost())
                && !ProxyUtils.validateNonProxyHosts(proxyInfo, url.getHost())) {
            httpClient.getHostConfiguration().setProxy(activeProxy.getHost(), activeProxy.getPort());

            if (StringUtils.isNotEmpty(activeProxy.getUsername()) && activeProxy.getPassword() != null) {
                Credentials credentials = new UsernamePasswordCredentials(activeProxy.getUsername(),
                        activeProxy.getPassword());

                httpClient.getState().setProxyCredentials(AuthScope.ANY, credentials);
            }
        }
    }

    GetMethod getMethod = new GetMethod(url.toString());
    try {
        int status;
        try {
            status = httpClient.executeMethod(getMethod);
        } catch (SocketTimeoutException e) {
            // could be a sporadic failure, one more retry before we give up
            status = httpClient.executeMethod(getMethod);
        }

        if (status != HttpStatus.SC_OK) {
            throw new FileNotFoundException(url.toString());
        }
    } finally {
        getMethod.releaseConnection();
    }
}

From source file:org.apache.sling.discovery.impl.topology.connector.TopologyConnectorClient.java

/** ping the server and pass the announcements between the two **/
void ping(final boolean force) {
    if (autoStopped) {
        // then we suppress any further pings!
        logger.debug("ping: autoStopped=true, hence suppressing any further pings.");
        return;// w  w w  .  j a v  a 2 s. c  o  m
    }
    if (force) {
        backoffPeriodEnd = -1;
    } else if (backoffPeriodEnd > 0) {
        if (System.currentTimeMillis() < backoffPeriodEnd) {
            logger.debug("ping: not issueing a heartbeat due to backoff instruction from peer.");
            return;
        } else {
            logger.debug("ping: backoff period ended, issuing another ping now.");
        }
    }
    final String uri = connectorUrl.toString() + "." + clusterViewService.getSlingId() + ".json";
    if (logger.isDebugEnabled()) {
        logger.debug("ping: connectorUrl=" + connectorUrl + ", complete uri=" + uri);
    }
    HttpClient httpClient = new HttpClient();
    final PutMethod method = new PutMethod(uri);
    Announcement resultingAnnouncement = null;
    try {
        String userInfo = connectorUrl.getUserInfo();
        if (userInfo != null) {
            Credentials c = new UsernamePasswordCredentials(userInfo);
            httpClient.getState()
                    .setCredentials(new AuthScope(method.getURI().getHost(), method.getURI().getPort()), c);
        }

        Announcement topologyAnnouncement = new Announcement(clusterViewService.getSlingId());
        topologyAnnouncement.setServerInfo(serverInfo);
        final ClusterView clusterView = clusterViewService.getClusterView();
        topologyAnnouncement.setLocalCluster(clusterView);
        if (force) {
            logger.debug("ping: sending a resetBackoff");
            topologyAnnouncement.setResetBackoff(true);
        }
        announcementRegistry.addAllExcept(topologyAnnouncement, clusterView, new AnnouncementFilter() {

            public boolean accept(final String receivingSlingId, final Announcement announcement) {
                // filter out announcements that are of old cluster instances
                // which I dont really have in my cluster view at the moment
                final Iterator<InstanceDescription> it = clusterViewService.getClusterView().getInstances()
                        .iterator();
                while (it.hasNext()) {
                    final InstanceDescription instance = it.next();
                    if (instance.getSlingId().equals(receivingSlingId)) {
                        // then I have the receiving instance in my cluster view
                        // all fine then
                        return true;
                    }
                }
                // looks like I dont have the receiving instance in my cluster view
                // then I should also not propagate that announcement anywhere
                return false;
            }
        });
        final String p = requestValidator.encodeMessage(topologyAnnouncement.asJSON());

        if (logger.isDebugEnabled()) {
            logger.debug("ping: topologyAnnouncement json is: " + p);
        }
        requestValidator.trustMessage(method, p);
        if (config.isGzipConnectorRequestsEnabled()) {
            // tell the server that the content is gzipped:
            method.addRequestHeader("Content-Encoding", "gzip");
            // and gzip the body:
            final ByteArrayOutputStream baos = new ByteArrayOutputStream();
            final GZIPOutputStream gzipOut = new GZIPOutputStream(baos);
            gzipOut.write(p.getBytes("UTF-8"));
            gzipOut.close();
            final byte[] gzippedEncodedJson = baos.toByteArray();
            method.setRequestEntity(new ByteArrayRequestEntity(gzippedEncodedJson, "application/json"));
            lastRequestEncoding = "gzip";
        } else {
            // otherwise plaintext:
            method.setRequestEntity(new StringRequestEntity(p, "application/json", "UTF-8"));
            lastRequestEncoding = "plaintext";
        }
        // independent of request-gzipping, we do accept the response to be gzipped,
        // so indicate this to the server:
        method.addRequestHeader("Accept-Encoding", "gzip");
        DefaultHttpMethodRetryHandler retryhandler = new DefaultHttpMethodRetryHandler(0, false);
        httpClient.getParams().setParameter(HttpMethodParams.RETRY_HANDLER, retryhandler);
        httpClient.getHttpConnectionManager().getParams()
                .setConnectionTimeout(1000 * config.getConnectionTimeout());
        httpClient.getHttpConnectionManager().getParams().setSoTimeout(1000 * config.getSoTimeout());
        method.getParams().setSoTimeout(1000 * config.getSoTimeout());
        httpClient.executeMethod(method);
        if (logger.isDebugEnabled()) {
            logger.debug("ping: done. code=" + method.getStatusCode() + " - " + method.getStatusText());
        }
        lastStatusCode = method.getStatusCode();
        lastResponseEncoding = null;
        if (method.getStatusCode() == HttpServletResponse.SC_OK) {
            final Header contentEncoding = method.getResponseHeader("Content-Encoding");
            if (contentEncoding != null && contentEncoding.getValue() != null
                    && contentEncoding.getValue().contains("gzip")) {
                lastResponseEncoding = "gzip";
            } else {
                lastResponseEncoding = "plaintext";
            }
            String responseBody = requestValidator.decodeMessage(method); // limiting to 16MB, should be way enough
            if (logger.isDebugEnabled()) {
                logger.debug("ping: response body=" + responseBody);
            }
            if (responseBody != null && responseBody.length() > 0) {
                Announcement inheritedAnnouncement = Announcement.fromJSON(responseBody);
                final long backoffInterval = inheritedAnnouncement.getBackoffInterval();
                if (backoffInterval > 0) {
                    // then reset the backoffPeriodEnd:

                    /* minus 1 sec to avoid slipping the interval by a few millis */
                    this.backoffPeriodEnd = System.currentTimeMillis() + (1000 * backoffInterval) - 1000;
                    logger.debug("ping: servlet instructed to backoff: backoffInterval=" + backoffInterval
                            + ", resulting in period end of " + new Date(backoffPeriodEnd));
                } else {
                    logger.debug("ping: servlet did not instruct any backoff-ing at this stage");
                    this.backoffPeriodEnd = -1;
                }
                if (inheritedAnnouncement.isLoop()) {
                    if (logger.isDebugEnabled()) {
                        logger.debug(
                                "ping: connector response indicated a loop detected. not registering this announcement from "
                                        + inheritedAnnouncement.getOwnerId());
                    }
                    if (inheritedAnnouncement.getOwnerId().equals(clusterViewService.getSlingId())) {
                        // SLING-3316 : local-loop detected. Check config to see if we should stop this connector

                        if (config.isAutoStopLocalLoopEnabled()) {
                            inheritedAnnouncement = null; // results in connected -> false and representsloop -> true
                            autoStopped = true; // results in isAutoStopped -> true
                        }
                    }
                } else {
                    inheritedAnnouncement.setInherited(true);
                    if (announcementRegistry.registerAnnouncement(inheritedAnnouncement) == -1) {
                        if (logger.isDebugEnabled()) {
                            logger.debug(
                                    "ping: connector response is from an instance which I already see in my topology"
                                            + inheritedAnnouncement);
                        }
                        statusDetails = "receiving side is seeing me via another path (connector or cluster) already (loop)";
                        return;
                    }
                }
                resultingAnnouncement = inheritedAnnouncement;
                statusDetails = null;
            } else {
                statusDetails = "no response body received";
            }
        } else {
            statusDetails = "got HTTP Status-Code: " + lastStatusCode;
        }
        // SLING-2882 : reset suppressPingWarnings_ flag in success case
        suppressPingWarnings_ = false;
    } catch (URIException e) {
        logger.warn("ping: Got URIException: " + e + ", uri=" + uri);
        statusDetails = e.toString();
    } catch (IOException e) {
        // SLING-2882 : set/check the suppressPingWarnings_ flag
        if (suppressPingWarnings_) {
            if (logger.isDebugEnabled()) {
                logger.debug("ping: got IOException: " + e + ", uri=" + uri);
            }
        } else {
            suppressPingWarnings_ = true;
            logger.warn("ping: got IOException [suppressing further warns]: " + e + ", uri=" + uri);
        }
        statusDetails = e.toString();
    } catch (JSONException e) {
        logger.warn("ping: got JSONException: " + e);
        statusDetails = e.toString();
    } catch (RuntimeException re) {
        logger.warn("ping: got RuntimeException: " + re, re);
        statusDetails = re.toString();
    } finally {
        method.releaseConnection();
        lastInheritedAnnouncement = resultingAnnouncement;
        lastPingedAt = System.currentTimeMillis();
    }
}

From source file:org.apache.sling.ide.osgi.impl.HttpOsgiClient.java

private HttpClient getHttpClient() {

    HttpClient client = new HttpClient();
    client.getHttpConnectionManager().getParams().setConnectionTimeout(DEFAULT_CONNECT_TIMEOUT_SECONDS * 1000);
    client.getHttpConnectionManager().getParams().setSoTimeout(DEFAULT_SOCKET_TIMEOUT_SECONDS * 1000);
    client.getParams().setAuthenticationPreemptive(true);
    Credentials defaultcreds = new UsernamePasswordCredentials(repositoryInfo.getUsername(),
            repositoryInfo.getPassword());
    client.getState().setCredentials(//from   w w w  . j av  a 2s.c o  m
            new AuthScope(repositoryInfo.getHost(), repositoryInfo.getPort(), AuthScope.ANY_REALM),
            defaultcreds);
    return client;
}

From source file:org.apache.sling.maven.bundlesupport.AbstractBundleDeployMojo.java

private void post(String targetURL, File file) throws MojoExecutionException {

    PostMethod filePost = new PostMethod(targetURL);
    try {//from   w  w  w.  j  av a  2  s.  c  o  m
        Part[] parts = { new FilePart(file.getName(), new FilePartSource(file.getName(), file)),
                new StringPart("_noredir_", "_noredir_") };
        filePost.setRequestEntity(new MultipartRequestEntity(parts, filePost.getParams()));
        HttpClient client = new HttpClient();
        client.getHttpConnectionManager().getParams().setConnectionTimeout(5000);
        int status = client.executeMethod(filePost);
        if (status == HttpStatus.SC_OK) {
            getLog().info("Bundle deployed");
        } else {
            String msg = "Deployment failed, cause: " + HttpStatus.getStatusText(status);
            if (failOnError) {
                throw new MojoExecutionException(msg);
            } else {
                getLog().error(msg);
            }
        }
    } catch (Exception ex) {
        throw new MojoExecutionException("Deployment on " + targetURL + " failed, cause: " + ex.getMessage(),
                ex);
    } finally {
        filePost.releaseConnection();
    }
}