Example usage for org.apache.commons.httpclient MultiThreadedHttpConnectionManager MultiThreadedHttpConnectionManager

List of usage examples for org.apache.commons.httpclient MultiThreadedHttpConnectionManager MultiThreadedHttpConnectionManager

Introduction

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

Prototype

public MultiThreadedHttpConnectionManager() 

Source Link

Usage

From source file:org.obm.sync.solr.jms.DefaultCommandConverter.java

@Inject
@VisibleForTesting//from w  w  w.j a  v a2  s.  co  m
public DefaultCommandConverter(LocatorService locatorService, ContactIndexer.Factory contactIndexerFactory,
        EventIndexer.Factory eventIndexerFactory) {
    this.locatorService = locatorService;

    MultiThreadedHttpConnectionManager cnxManager = new MultiThreadedHttpConnectionManager();
    cnxManager.getParams().setDefaultMaxConnectionsPerHost(10);
    cnxManager.getParams().setMaxTotalConnections(100);
    solrHttpClient = new HttpClient(cnxManager);

    solrServiceToFactoryMap = new EnumMap<SolrService, IndexerFactory<? extends Serializable>>(
            SolrService.class);
    solrServiceToFactoryMap.put(SolrService.EVENT_SERVICE, eventIndexerFactory);
    solrServiceToFactoryMap.put(SolrService.CONTACT_SERVICE, contactIndexerFactory);
}

From source file:org.olat.core.util.httpclient.HttpClientFactory.java

/**
 * A HttpClient with basic authentication and no host or port setting. Can only be used to retrieve absolute URLs
 * //from  w  ww  .j a  v a  2  s .  c  o  m
 * @param user can be NULL
 * @param password can be NULL
 * @return HttpClient
 */
public static HttpClient getHttpClientInstance(String user, String password) {
    HttpConnectionManager connectionManager = new MultiThreadedHttpConnectionManager();
    HttpConnectionParams params = connectionManager.getParams();
    // wait max 10 seconds to establish connection
    params.setConnectionTimeout(10000);
    // a read() call on the InputStream associated with this Socket
    // will block for only this amount
    params.setSoTimeout(10000);
    HttpClient c = new HttpClient(connectionManager);

    // use basic authentication if available
    if (user != null && user.length() > 0) {
        AuthScope authScope = new AuthScope(null, -1, null);
        Credentials credentials = new UsernamePasswordCredentials(user, password);
        c.getState().setCredentials(authScope, credentials);
    }
    return c;
}

From source file:org.opencastproject.distribution.hydrant.HydrantDistributionService.java

/**
 * Distributes the mediapackage's element to the location that is returned by the concrete implementation. In
 * addition, a representation of the distributed element is added to the mediapackage.
 * /*from   w w  w. j  a  v a2  s  .com*/
 * @see org.opencastproject.distribution.api.DistributionService#distribute(String, MediaPackageElement)
 */
protected MediaPackageElement distribute(Job job, MediaPackage mediapackage, String elementId)
        throws DistributionException {

    if (mediapackage == null)
        throw new IllegalArgumentException("Mediapackage must be specified");
    if (elementId == null)
        throw new IllegalArgumentException("Element ID must be specified");

    String mediaPackageId = mediapackage.getIdentifier().compact();
    MediaPackageElement element = mediapackage.getElementById(elementId);

    // Make sure the element exists
    if (mediapackage.getElementById(elementId) == null)
        throw new IllegalStateException("No element " + elementId + " found in mediapackage");

    try {
        // The hydrant server only supports tracks
        if (!(element instanceof Track)) {
            return null;
        }

        String parentpid = mediapackage.getTitle();
        if (parentpid == null) {
            throw new DistributionException("Could not find Hydrant pid in mediapackage.");
        }

        logger.trace("Found parent pid: {}", parentpid);

        try {
            String url = UrlSupport.concat(new String[] { hydrantUrl, "derivatives" });
            MultiThreadedHttpConnectionManager mgr = new MultiThreadedHttpConnectionManager();
            HttpClient client = new HttpClient(mgr);
            Credentials defaultcreds = new UsernamePasswordCredentials(hydrantAdminUsername,
                    hydrantAdminPassword);
            client.getState().setCredentials(AuthScope.ANY, defaultcreds);
            client.getParams().setAuthenticationPreemptive(true);

            PostMethod post = new PostMethod(url);
            post.setDoAuthentication(true);

            Part[] parts = { new StringPart("stream_url", element.getURI().toString()),
                    new StringPart("master", parentpid), };
            post.setRequestEntity(new MultipartRequestEntity(parts, post.getParams()));
            int status = client.executeMethod(post);
            logger.debug("Got status: " + status);
            logger.trace("Got response body: " + post.getResponseBodyAsString());
        } catch (IOException e) {
            logger.debug("Exception distributing to Hydrant: " + e.getCause());
            throw new DistributionException("Error distributing to Hydrant instance", e);
        }

        logger.info("Distributed {} to hydrant", elementId);

        // Create a representation of the distributed file in the mediapackage
        MediaPackageElement distributedElement = (MediaPackageElement) element.clone();
        //TODO Create and set a valid distribution URI
        /*
              try {
                distributedElement.setURI(getDistributionUri(mediaPackageId, element));
              } catch (URISyntaxException e) {
                throw new DistributionException("Distributed element produces an invalid URI", e);
              }
        */
        distributedElement.setIdentifier(null);

        logger.info("Finished distribution of {}", element);
        return distributedElement;

    } catch (Exception e) {
        logger.warn("Error distributing " + element, e);
        if (e instanceof DistributionException) {
            throw (DistributionException) e;
        } else {
            throw new DistributionException(e);
        }
    }
}

From source file:org.openehealth.ipf.commons.test.http.client.Client.java

public Client() {
    mgr = new MultiThreadedHttpConnectionManager();
    client = new HttpClient(mgr);
    contentType = "text/plain";
}

From source file:org.openhab.persistence.grafana.internal.GrafanaChartProvider.java

public void activate(final BundleContext bundleContext, final Map<String, Object> config) {
    logger.debug("Starting up grafana chart provider");
    MultiThreadedHttpConnectionManager connectionManager = new MultiThreadedHttpConnectionManager();
    proxy = new HttpClient(connectionManager);
}

From source file:org.openjena.sarq.SolrServer.java

private CommonsHttpSolrServer buildSolrQueryServer(String url, boolean binary) throws MalformedURLException {
    if (url == null) {
        throw new IllegalArgumentException("URL cannot be null.");
    }// w  w  w . j av  a2 s.  c  o  m

    MultiThreadedHttpConnectionManager cm = new MultiThreadedHttpConnectionManager();
    ResponseParser parser = null;
    if (binary) {
        parser = new BinaryResponseParser();
    } else {
        parser = new XMLResponseParser();
    }
    CommonsHttpSolrServer server = new CommonsHttpSolrServer(new URL(url), new HttpClient(cm), parser, false);
    server.setSoTimeout(1000);
    server.setConnectionTimeout(2000);
    server.setDefaultMaxConnectionsPerHost(10);
    server.setMaxTotalConnections(10);
    server.setFollowRedirects(false);
    server.setAllowCompression(true);
    server.setMaxRetries(1);
    if (binary) {
        server.setRequestWriter(new BinaryRequestWriter());
    } else {
        server.setRequestWriter(new RequestWriter());
    }

    return server;
}

From source file:org.openmicroscopy.is.HttpImageServer.java

/**
 * Creates the {@link HttpClient} object for this instance to use.
 * Can be overridden if a class other than the default should be
 * used./*from   w w w.  ja v  a  2 s . c  o m*/
 */
protected HttpClient createHttpClient() {
    MultiThreadedHttpConnectionManager cm = new MultiThreadedHttpConnectionManager();
    HttpClient client = new HttpClient(cm);
    client.setConnectionTimeout(10000);
    return client;
}

From source file:org.opennms.features.geocoder.google.GoogleGeocoderService.java

public void ensureInitialized() throws GeocoderException {
    if (m_geocoder == null) {
        final HttpClient httpClient = new HttpClient(new MultiThreadedHttpConnectionManager());

        if (notEmpty(m_clientId) && notEmpty(m_clientKey)) {
            try {
                LOG.info("Initializing Google Geocoder using Client ID and Key.");
                m_geocoder = new AdvancedGeoCoder(httpClient, m_clientId, m_clientKey);
            } catch (final InvalidKeyException e) {
                throw new GeocoderException("Unable to initialize Google Geocoder.", e);
            }// w w w  .  j av  a  2 s  . com
        }

        if (m_geocoder == null) {
            LOG.info("Initializing Google Geocoder using default configuration.");
            m_geocoder = new AdvancedGeoCoder(httpClient);
        }

        /* Configure proxying, if necessary... */
        final String httpProxyHost = System.getProperty("http.proxyHost");
        final Integer httpProxyPort = Integer.getInteger("http.proxyPort");
        if (httpProxyHost != null && httpProxyPort != null) {
            LOG.info("Proxy configuration found, using {}:{} as HTTP proxy.", httpProxyHost, httpProxyPort);
            httpClient.getHostConfiguration().setProxy(httpProxyHost, httpProxyPort);
        } else {
            LOG.info("No proxy configuration found.");
        }

        /* Limit retries... */
        httpClient.getParams().setParameter(HttpMethodParams.RETRY_HANDLER,
                new DefaultHttpMethodRetryHandler(1, true));

        LOG.info("Google Geocoder initialized.");
    }
}

From source file:org.openrdf.http.client.HTTPClient.java

public HTTPClient() {
    valueFactory = ValueFactoryImpl.getInstance();

    // Use MultiThreadedHttpConnectionManager to allow concurrent access on
    // HttpClient
    manager = new MultiThreadedHttpConnectionManager();

    // Allow 20 concurrent connections to the same host (default is 2)
    HttpConnectionManagerParams params = new HttpConnectionManagerParams();
    params.setDefaultMaxConnectionsPerHost(20);
    manager.setParams(params);// w w  w. j  a  v a2  s.co m

    httpClient = new HttpClient(manager);

    configureProxySettings(httpClient);
}

From source file:org.openrdf.repository.sparql.SPARQLConnection.java

public SPARQLConnection(SPARQLRepository repository, String queryEndpointUrl, String updateEndpointUrl) {
    super(repository);
    this.queryEndpointUrl = queryEndpointUrl;
    this.updateEndpointUrl = updateEndpointUrl;

    // Use MultiThreadedHttpConnectionManager to allow concurrent access on
    // HttpClient
    HttpConnectionManager manager = new MultiThreadedHttpConnectionManager();

    // Allow 20 concurrent connections to the same host (default is 2)
    HttpConnectionManagerParams params = new HttpConnectionManagerParams();
    params.setDefaultMaxConnectionsPerHost(20);
    params.setStaleCheckingEnabled(false);
    manager.setParams(params);/*from   w w  w .j  av a  2 s.co  m*/

    HttpClientParams clientParams = new HttpClientParams();
    clientParams.setParameter(HttpMethodParams.USER_AGENT,
            APP_NAME + "/" + VERSION + " " + clientParams.getParameter(HttpMethodParams.USER_AGENT));
    // set additional HTTP headers, if desired by the user
    if (repository.getAdditionalHttpHeaders() != null)
        clientParams.setParameter(ADDITIONAL_HEADER_NAME, repository.getAdditionalHttpHeaders());
    client = new HttpClient(clientParams, manager);
}