Example usage for org.apache.http.impl NoConnectionReuseStrategy NoConnectionReuseStrategy

List of usage examples for org.apache.http.impl NoConnectionReuseStrategy NoConnectionReuseStrategy

Introduction

In this page you can find the example usage for org.apache.http.impl NoConnectionReuseStrategy NoConnectionReuseStrategy.

Prototype

NoConnectionReuseStrategy

Source Link

Usage

From source file:org.carrot2.util.httpclient.HttpClientFactory.java

/**
 * @param timeout Timeout in milliseconds.
 * @return Returns a client with sockets configured to timeout after some sensible
 *         time.//from w  ww.  j a  va  2 s.  c  o m
 */
public static DefaultHttpClient getTimeoutingClient(int timeout) {
    final DefaultHttpClient httpClient = new DefaultHttpClient();

    configureProxy(httpClient);

    // Setup defaults.
    httpClient.setReuseStrategy(new NoConnectionReuseStrategy());

    httpClient.getParams().setIntParameter(CoreConnectionPNames.SO_TIMEOUT, timeout);
    httpClient.getParams().setIntParameter(CoreConnectionPNames.CONNECTION_TIMEOUT, timeout);
    httpClient.getParams().setIntParameter(CoreConnectionPNames.SO_LINGER, 0);

    return httpClient;
}

From source file:com.fluidops.fedx.FedXFactory.java

/**
 * Initialize the federation with the provided sparql endpoints. 
 * /*from  www .  j  a v a2s.  co m*/
 * NOTE: {@link Config#initialize()} needs to be invoked before.
 * 
 * @param dataConfig
 *             the location of the data source configuration
 * 
 * @return
 *          the initialized FedX federation {@link Sail} wrapped in a {@link SailRepository}
 * 
 * @throws Exception
 */
public static SailRepository initializeSparqlFederation(List<String> sparqlEndpoints) {
    // initialize httpclient parameters
    httpClientBuilder = HttpClientBuilders.getSSLTrustAllHttpClientBuilder();
    httpClientBuilder.setMaxConnTotal(Config.getMaxHttpConnectionCount());
    httpClientBuilder.setMaxConnPerRoute(Config.getMaxHttpConnectionCountPerRoute());

    //httpClientBuilder.evictExpiredConnections();
    httpClientBuilder.setConnectionReuseStrategy(new NoConnectionReuseStrategy());
    //httpClientBuilder.setConnectionTimeToLive(1000, TimeUnit.MILLISECONDS);
    //httpClientBuilder.disableAutomaticRetries();

    //      httpClientBuilder.setKeepAliveStrategy(new ConnectionKeepAliveStrategy(){
    //
    //         @Override
    //         public long getKeepAliveDuration(HttpResponse response, HttpContext context) {
    //            return 0;
    //         }});

    httpClient = httpClientBuilder.build();
    List<Endpoint> endpoints = new ArrayList<Endpoint>();
    for (String url : sparqlEndpoints) {
        endpoints.add(EndpointFactory.loadSPARQLEndpoint(url));
    }
    return initializeFederation(endpoints);
}

From source file:org.rapidoid.http.HttpClientUtil.java

static CloseableHttpAsyncClient client(HttpClient client) {

    ConnectionReuseStrategy reuseStrategy = client.reuseConnections() ? new DefaultConnectionReuseStrategy()
            : new NoConnectionReuseStrategy();

    HttpAsyncClientBuilder builder = HttpAsyncClients.custom()
            .setThreadFactory(new RapidoidThreadFactory("http-client")).disableConnectionState()
            .disableAuthCaching().setMaxConnPerRoute(client.maxConnPerRoute())
            .setMaxConnTotal(client.maxConnTotal()).setConnectionReuseStrategy(reuseStrategy)
            .setRedirectStrategy(client.followRedirects() ? new DefaultRedirectStrategy() : NO_REDIRECTS);

    if (!U.isEmpty(client.cookies())) {
        BasicCookieStore cookieStore = new BasicCookieStore();

        for (Map.Entry<String, String> e : client.cookies().entrySet()) {
            BasicClientCookie cookie = new BasicClientCookie(e.getKey(), e.getValue());

            String host = client.host();
            U.notNull(host, "HTTP client host");

            cookie.setDomain(getDomain(host));
            cookie.setPath("/");
            cookieStore.addCookie(cookie);
        }/* w  w  w  .j a v a2 s.  c  o m*/

        builder = builder.setDefaultCookieStore(cookieStore);
    }

    if (client.userAgent() != null) {
        builder = builder.setUserAgent(client.userAgent());
    }

    if (!client.keepCookies() && U.isEmpty(client.cookies())) {
        builder = builder.disableCookieManagement();
    }

    return builder.build();
}

From source file:io.github.hebra.elasticsearch.beat.meterbeat.device.dlink.DSPW215.java

@Override
public String fetchData() {
    final String url = config.getBaseurl().concat("/my_cgi.cgi?")
            .concat(new BigInteger(130, secureRandom).toString(32));

    try {//  w ww .  ja  v  a 2  s .c o  m
        RequestConfig requestConfig = RequestConfig.custom().setSocketTimeout(timeout)
                .setConnectTimeout(timeout).setConnectionRequestTimeout(timeout).build();

        HttpClient client = HttpClientBuilder.create().setConnectionTimeToLive(5, TimeUnit.SECONDS)
                .setConnectionReuseStrategy(new NoConnectionReuseStrategy()).build();
        HttpPost post = new HttpPost(url);

        post.setConfig(requestConfig);

        post.setHeader("User-Agent", USER_AGENT);
        post.setHeader("Accept-Language", "en-US,en;q=0.5");

        final List<NameValuePair> urlParameters = new ArrayList<>();
        urlParameters.add(new BasicNameValuePair("request", "create_chklst"));
        post.setEntity(new UrlEncodedFormEntity(urlParameters));

        final HttpResponse response = client.execute(post);

        final String content = IOUtils.toString(response.getEntity().getContent(), Charsets.US_ASCII);

        EntityUtils.consume(response.getEntity());

        return content.split("Meter Watt: ", 2)[1].trim();
    } catch (IOException ioEx) {
        log.error("Timeout when trying to read from {} on {}: {}", config.getName(), config.getBaseurl(),
                ioEx.getMessage());
    }

    return null;
}

From source file:org.aludratest.service.gui.web.selenium.TAFMSSeleniumResourceService.java

@Override
public String acquire() {
    // prepare a JSON query to the given TAFMS server
    JSONObject query = new JSONObject();

    try {/*  w  w  w.  j  av  a2s  . c o  m*/
        query.put("resourceType", "selenium");
        query.put("niceLevel", configuration.getIntValue("tafms.niceLevel", 0));
        String jobName = configuration.getStringValue("tafms.jobName");
        if (jobName != null && !"".equals(jobName)) {
            query.put("jobName", jobName);
        }
    } catch (JSONException e) {
    }

    // prepare authentication
    BasicCredentialsProvider provider = new BasicCredentialsProvider();
    provider.setCredentials(AuthScope.ANY, new UsernamePasswordCredentials(
            configuration.getStringValue("tafms.user"), configuration.getStringValue("tafms.password")));

    CloseableHttpClient client = HttpClientBuilder.create()
            .setConnectionReuseStrategy(new NoConnectionReuseStrategy()).disableConnectionState()
            .disableAutomaticRetries().setDefaultCredentialsProvider(provider).build();

    String message = null;
    try {
        boolean wait;

        // use preemptive authentication to avoid double connection count
        AuthCache authCache = new BasicAuthCache();
        // Generate BASIC scheme object and add it to the local auth cache
        BasicScheme basicAuth = new BasicScheme();
        URL url = new URL(getTafmsUrl());
        HttpHost host = new HttpHost(url.getHost(), url.getPort() == -1 ? url.getDefaultPort() : url.getPort(),
                url.getProtocol());
        authCache.put(host, basicAuth);

        // Add AuthCache to the execution context
        BasicHttpContext localcontext = new BasicHttpContext();
        localcontext.setAttribute(HttpClientContext.AUTH_CACHE, authCache);

        do {
            // send a POST request to resource URL
            HttpPost request = new HttpPost(getTafmsUrl() + "resource");

            // attach query as JSON string data
            request.setEntity(new StringEntity(query.toString(), ContentType.APPLICATION_JSON));

            CloseableHttpResponse response = null;

            // fire request
            response = client.execute(request, localcontext);

            try {
                if (response.getStatusLine() == null) {
                    throw new ClientProtocolException("No HTTP status line transmitted");
                }

                message = extractMessage(response);
                if (response.getStatusLine().getStatusCode() != HttpStatus.SC_OK) {
                    LOG.error("Exception when querying TAFMS server for resource. HTTP Status: "
                            + response.getStatusLine().getStatusCode() + ", message: " + message);
                    return null;
                }

                JSONObject object = new JSONObject(message);
                if (object.has("errorMessage")) {
                    LOG.error("TAFMS server reported an error: " + object.get("errorMessage"));
                    return null;
                }

                // continue wait?
                if (object.has("waiting") && object.getBoolean("waiting")) {
                    wait = true;
                    query.put("requestId", object.getString("requestId"));
                } else {
                    JSONObject resource = object.optJSONObject("resource");
                    if (resource == null) {
                        LOG.error("TAFMS server response did not provide a resource. Message was: " + message);
                        return null;
                    }

                    String sUrl = resource.getString("url");
                    hostResourceIds.put(sUrl, object.getString("requestId"));

                    return sUrl;
                }
            } finally {
                IOUtils.closeQuietly(response);
            }
        } while (wait);

        // should never come here
        return null;
    } catch (ClientProtocolException e) {
        LOG.error("Exception in HTTP transmission", e);
        return null;
    } catch (IOException e) {
        LOG.error("Exception in communication with TAFMS server", e);
        return null;
    } catch (JSONException e) {
        LOG.error("Invalid JSON received from TAFMS server. JSON message was: " + message, e);
        return null;
    } finally {
        IOUtils.closeQuietly(client);
    }
}

From source file:com.hoccer.api.CloudService.java

protected void setupHttpClient() {

    LOG.info("setting up http client");

    BasicHttpParams httpParams = new BasicHttpParams();
    HttpConnectionParams.setSoTimeout(httpParams, 70 * 1000);
    HttpConnectionParams.setConnectionTimeout(httpParams, 10 * 1000);
    ConnManagerParams.setMaxTotalConnections(httpParams, 200);
    ConnPerRoute connPerRoute = new ConnPerRouteBean(400);
    ConnManagerParams.setMaxConnectionsPerRoute(httpParams, connPerRoute);
    SchemeRegistry schemeRegistry = new SchemeRegistry();
    schemeRegistry.register(new Scheme("http", PlainSocketFactory.getSocketFactory(), 80));
    schemeRegistry.register(new Scheme("https", SSLSocketFactory.getSocketFactory(), 443));
    ThreadSafeClientConnManager cm = new ThreadSafeClientConnManager(httpParams, schemeRegistry);
    // ThreadSafeClientConnManager cm = new ThreadSafeClientConnManager(httpParams,
    // HttpClientWithKeystore.getSchemeRegistry());
    HttpProtocolParams.setVersion(httpParams, HttpVersion.HTTP_1_1);
    HttpProtocolParams.setContentCharset(httpParams, "utf-8");
    mHttpClient = new HttpClientWithKeystore(cm, httpParams);
    mHttpClient.getParams().setParameter("http.useragent", mConfig.getApplicationName());
    mHttpClient.getParams().setBooleanParameter(CoreProtocolPNames.USE_EXPECT_CONTINUE, false);
    mHttpClient.setReuseStrategy(new NoConnectionReuseStrategy());
}

From source file:co.paralleluniverse.fibers.dropwizard.FiberHttpClientBuilder.java

/**
 * Add strategies to client such as ConnectionReuseStrategy and KeepAliveStrategy Note that this
 * method mutates the client object by setting the strategies
 *
 * @param client The InstrumentedHttpClient that should be configured with strategies
 *///from w  w  w .  j a  v a2 s . c om
protected void setStrategiesForClient(HttpAsyncClientBuilder client) {
    final long keepAlive = configuration.getKeepAlive().toMilliseconds();

    // don't keep alive the HTTP connection and thus don't reuse the TCP socket
    if (keepAlive == 0) {
        client.setConnectionReuseStrategy(new NoConnectionReuseStrategy());
    } else {
        client.setConnectionReuseStrategy(new DefaultConnectionReuseStrategy());
        // either keep alive based on response header Keep-Alive,
        // or if the server can keep a persistent connection (-1), then override based on client's configuration
        client.setKeepAliveStrategy(new DefaultConnectionKeepAliveStrategy() {
            @Override
            public long getKeepAliveDuration(HttpResponse response, HttpContext context) {
                final long duration = super.getKeepAliveDuration(response, context);
                return (duration == -1) ? keepAlive : duration;
            }
        });
    }
}

From source file:org.aludratest.service.gui.web.selenium.TAFMSSeleniumResourceService.java

@Override
public void release(String server) {
    if (server == null) {
        return;/*  w  w w  . jav a2s . c  o  m*/
    }

    String resourceKey = hostResourceIds.remove(server);
    if (resourceKey == null) {
        return;
    }

    CloseableHttpClient client = HttpClientBuilder.create()
            .setConnectionReuseStrategy(new NoConnectionReuseStrategy()).disableConnectionState()
            .disableAutomaticRetries().build();

    // send a DELETE request to resource URL
    HttpDelete request = new HttpDelete(getTafmsUrl() + "resource/" + resourceKey);
    CloseableHttpResponse response = null;

    try {
        response = client.execute(request);
    } catch (IOException e) {
        LOG.warn("Could not release TAFMS resource", e);
    } finally {
        IOUtils.closeQuietly(response);
        IOUtils.closeQuietly(client);
    }
}

From source file:ch.cyberduck.core.http.HttpConnectionPoolBuilder.java

public HttpClientBuilder build(final TranscriptListener listener) {
    // Use HTTP Connect proxy implementation provided here instead of
    // relying on internal proxy support in socket factory
    final Proxy proxy = proxyFinder.find(host);
    if (proxy.getType() == Proxy.Type.HTTP) {
        final HttpHost h = new HttpHost(proxy.getHostname(), proxy.getPort(), Scheme.http.name());
        if (log.isInfoEnabled()) {
            log.info(String.format("Setup proxy %s", h));
        }/*from   ww  w  . ja  v a  2  s .  co m*/
        builder.setProxy(h);
    }
    if (proxy.getType() == Proxy.Type.HTTPS) {
        final HttpHost h = new HttpHost(proxy.getHostname(), proxy.getPort(), Scheme.https.name());
        if (log.isInfoEnabled()) {
            log.info(String.format("Setup proxy %s", h));
        }
        builder.setProxy(h);
    }
    builder.setUserAgent(new PreferencesUseragentProvider().get());
    final int timeout = preferences.getInteger("connection.timeout.seconds") * 1000;
    builder.setDefaultSocketConfig(SocketConfig.custom().setTcpNoDelay(true).setSoTimeout(timeout).build());
    builder.setDefaultRequestConfig(RequestConfig.custom().setRedirectsEnabled(true)
            // Disable use of Expect: Continue by default for all methods
            .setExpectContinueEnabled(false).setAuthenticationEnabled(true).setConnectTimeout(timeout)
            // Sets the timeout in milliseconds used when retrieving a connection from the ClientConnectionManager
            .setConnectionRequestTimeout(preferences.getInteger("http.manager.timeout"))
            .setSocketTimeout(timeout).build());
    final String encoding;
    if (null == host.getEncoding()) {
        encoding = preferences.getProperty("browser.charset.encoding");
    } else {
        encoding = host.getEncoding();
    }
    builder.setDefaultConnectionConfig(
            ConnectionConfig.custom().setBufferSize(preferences.getInteger("http.socket.buffer"))
                    .setCharset(Charset.forName(encoding)).build());
    if (preferences.getBoolean("http.connections.reuse")) {
        builder.setConnectionReuseStrategy(new DefaultConnectionReuseStrategy());
    } else {
        builder.setConnectionReuseStrategy(new NoConnectionReuseStrategy());
    }
    builder.setRetryHandler(
            new ExtendedHttpRequestRetryHandler(preferences.getInteger("http.connections.retry")));
    if (!preferences.getBoolean("http.compression.enable")) {
        builder.disableContentCompression();
    }
    builder.setRequestExecutor(new LoggingHttpRequestExecutor(listener));
    // Always register HTTP for possible use with proxy. Contains a number of protocol properties such as the
    // default port and the socket factory to be used to create the java.net.Socket instances for the given protocol
    builder.setConnectionManager(this.pool(this.registry().build()));
    builder.setDefaultAuthSchemeRegistry(RegistryBuilder.<AuthSchemeProvider>create()
            .register(AuthSchemes.BASIC,
                    new BasicSchemeFactory(
                            Charset.forName(preferences.getProperty("http.credentials.charset"))))
            .register(AuthSchemes.DIGEST,
                    new DigestSchemeFactory(
                            Charset.forName(preferences.getProperty("http.credentials.charset"))))
            .register(AuthSchemes.NTLM, new NTLMSchemeFactory())
            .register(AuthSchemes.SPNEGO, new SPNegoSchemeFactory())
            .register(AuthSchemes.KERBEROS, new KerberosSchemeFactory()).build());
    return builder;
}

From source file:org.sonatype.nexus.apachehttpclient.Hc4ProviderImpl.java

@Override
public HttpClient createHttpClient(final boolean reuseConnections) {
    final Builder builder = prepareHttpClient(applicationConfiguration.getGlobalRemoteStorageContext());
    if (!reuseConnections) {
        builder.getHttpClientBuilder().setConnectionReuseStrategy(new NoConnectionReuseStrategy());
    }//from  ww  w .ja  v a 2  s.  c o m
    return builder.build();
}