Example usage for org.apache.http.impl.client HttpClientBuilder setUserAgent

List of usage examples for org.apache.http.impl.client HttpClientBuilder setUserAgent

Introduction

In this page you can find the example usage for org.apache.http.impl.client HttpClientBuilder setUserAgent.

Prototype

public final HttpClientBuilder setUserAgent(final String userAgent) 

Source Link

Document

Assigns User-Agent value.

Usage

From source file:org.georchestra.extractorapp.ws.extractor.csw.CSWExtractor.java

/**
 * checks the permissions to access to the CSW
 * //from  w  w w.jav  a 2s  . c o m
 * @param request
 * @param username request user name
 * @param roles
 * 
 * @throws IOException
 */
public void checkPermission(ExtractorLayerRequest request, String username, String roles) throws IOException {

    InputStream content = null;
    boolean isMetadata = false;
    try {
        final HttpClientBuilder httpClientBuilder = HttpClientBuilder.create();
        httpClientBuilder.setUserAgent(this.userAgent);

        HttpClientContext localContext = HttpClientContext.create();
        final HttpHost httpHost = new HttpHost(request._isoMetadataURL.getHost(),
                request._isoMetadataURL.getPort());

        HttpGet get = new HttpGet(request._isoMetadataURL.toURI());

        if (username != null && (_secureHost.equalsIgnoreCase(request._isoMetadataURL.getHost())
                || "127.0.0.1".equalsIgnoreCase(request._isoMetadataURL.getHost())
                || "localhost".equalsIgnoreCase(request._isoMetadataURL.getHost()))) {
            LOG.debug(getClass().getName()
                    + ".checkPermission - Secured Server: adding username header and role headers to request for checkPermission");
            WfsExtractor.addImpersonateUserHeaders(username, roles, get);

            WfsExtractor.enablePreemptiveBasicAuth(request._isoMetadataURL, httpClientBuilder, localContext,
                    httpHost, _adminUserName, _adminPassword);

        } else {
            LOG.debug("WcsExtractor.checkPermission - Non Secured Server");
        }

        // checks whether it is a metadata

        final CloseableHttpClient httpclient = httpClientBuilder.build();
        content = httpclient.execute(httpHost, get, localContext).getEntity().getContent();

        String metadata = FileUtils.asString(content);
        Pattern regex = Pattern.compile("<(gmd:)?MD_Metadata*");

        isMetadata = regex.matcher(metadata).find();

    } catch (Exception e) {

        throw new IOException(e);

    } finally {

        if (content != null)
            content.close();
    }

    if (!isMetadata) {
        throw new SecurityException("The metadata is not available: " + request._isoMetadataURL);
    }

}

From source file:org.ow2.proactive.http.CommonHttpClientBuilder.java

public org.apache.http.impl.client.HttpClientBuilder createInternalHttpClientBuilder() {
    org.apache.http.impl.client.HttpClientBuilder result = org.apache.http.impl.client.HttpClientBuilder
            .create();/*w w w .ja  v  a 2  s  .c om*/

    result.setUserAgent("ProActive");

    return result;
}

From source file:org.sonatype.nexus.internal.httpclient.HttpClientManagerImpl.java

/**
 * Allows for verification on unverifiable final method. NOTE: if you modify the behavior of this
 * method beyond simply delegating to {@link HttpClientBuilder#setUserAgent}, write a unit test for it.
 *//*  w ww. j  a v  a  2  s .  c om*/
@VisibleForTesting
void setUserAgent(HttpClientBuilder builder, String value) {
    builder.setUserAgent(value);
}

From source file:net.yacy.cora.protocol.http.HTTPClient.java

private static HttpClientBuilder initClientBuilder() {
    final HttpClientBuilder builder = HttpClientBuilder.create();

    builder.setConnectionManager(CONNECTION_MANAGER);
    builder.setDefaultRequestConfig(dfltReqConf);

    // UserAgent// w w  w.  j  av  a  2 s .  c o m
    builder.setUserAgent(ClientIdentification.yacyInternetCrawlerAgent.userAgent);

    // remove retries; we expect connections to fail; therefore we should not retry
    //builder.disableAutomaticRetries();
    // disable the cookiestore, cause this may cause segfaults and is not needed
    builder.setDefaultCookieStore(null);
    builder.disableCookieManagement();

    // add custom keep alive strategy
    builder.setKeepAliveStrategy(customKeepAliveStrategy());

    // ask for gzip
    builder.addInterceptorLast(new GzipRequestInterceptor());
    // uncompress gzip
    builder.addInterceptorLast(new GzipResponseInterceptor());
    // Proxy
    builder.setRoutePlanner(ProxySettings.RoutePlanner);
    builder.setDefaultCredentialsProvider(ProxySettings.CredsProvider);

    return builder;
}

From source file:com.github.segator.scaleway.api.ScalewayClient.java

public ScalewayClient(String accessToken, String organizationToken, ScalewayComputeRegion region) {
    this.accessToken = accessToken;
    this.organizationToken = organizationToken;
    this.region = region;
    HttpClientBuilder httpBuilder = HttpClients.custom();
    httpBuilder.setUserAgent(ScalewayConstants.USER_AGENT);
    this.httpclient = httpBuilder.build();
}

From source file:com.crosstreelabs.cognitio.gumshoe.transport.HttpTransport.java

private void buildHttpClient() {
    requestConfig = RequestConfig.custom().setExpectContinueEnabled(false).setCookieSpec(CookieSpecs.DEFAULT)
            .setRedirectsEnabled(false).setSocketTimeout(5000).setConnectTimeout(5000)
            .setConnectionRequestTimeout(5000).setStaleConnectionCheckEnabled(true).build();

    RegistryBuilder<ConnectionSocketFactory> connRegistryBuilder = RegistryBuilder.create();
    connRegistryBuilder.register("http", PlainConnectionSocketFactory.INSTANCE);
    try { // Fixing: https://code.google.com/p/crawler4j/issues/detail?id=174
          // By always trusting the ssl certificate
        SSLContext sslContext = SSLContexts.custom().loadTrustMaterial(null, new TrustStrategy() {
            @Override/*from w  w w  .  j a  v  a  2s. com*/
            public boolean isTrusted(final X509Certificate[] chain, String authType) {
                return true;
            }
        }).build();
        SSLConnectionSocketFactory sslsf = new SSLConnectionSocketFactory(sslContext,
                SSLConnectionSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER);
        connRegistryBuilder.register("https", sslsf);
    } catch (KeyManagementException | KeyStoreException | NoSuchAlgorithmException e) {
        LOGGER.warn("Exception thrown while trying to register https");
        LOGGER.debug("Stacktrace", e);
    }

    Registry<ConnectionSocketFactory> connRegistry = connRegistryBuilder.build();
    connectionManager = new PoolingHttpClientConnectionManager(connRegistry);
    connectionManager.setMaxTotal(5);
    connectionManager.setDefaultMaxPerRoute(5);

    HttpClientBuilder clientBuilder = HttpClientBuilder.create();
    clientBuilder.setDefaultRequestConfig(requestConfig);
    clientBuilder.setConnectionManager(connectionManager);
    clientBuilder.setUserAgent("Cognitio");

    httpClient = clientBuilder.build();
}

From source file:com.mediaworx.intellij.opencmsplugin.connector.OpenCmsPluginConnector.java

/**
 * Creates a new Plugin Connector/*from   w  ww. j  av a  2s .  c o m*/
 * @param connectorUrl          the Url under which the connector JSP cam be called
 * @param user                  OpenCms user to be used for communication with the connector
 * @param password              The OpenCms user's password
 * @param useMetaDateVariables  <code>true</code> if date variables should be used in meta data, <code>false</code>
 *                              otherwise
 * @param useMetaIdVariables    <code>true</code> if UUID variables should be used in meta data, <code>false</code>
 *                              otherwise
 */
public OpenCmsPluginConnector(String connectorUrl, String user, String password, boolean useMetaDateVariables,
        boolean useMetaIdVariables) {
    this.connectorUrl = connectorUrl;
    this.user = user;
    this.password = password;
    this.useMetaDateVariables = useMetaDateVariables;
    this.useMetaIdVariables = useMetaIdVariables;
    HttpClientBuilder clientBuilder = HttpClientBuilder.create();
    clientBuilder.setUserAgent("IntelliJ OpenCms plugin connector");
    httpClient = clientBuilder.build();

    jsonParser = new JSONParser();
}

From source file:sachin.spider.SpiderConfig.java

private String handleRedirect(String url) {
    try {/*  ww  w. j a va 2  s. c o  m*/
        HttpGet httpget = new HttpGet(url);
        RequestConfig requestConfig = RequestConfig.custom().setRedirectsEnabled(true)
                .setCircularRedirectsAllowed(true).setRelativeRedirectsAllowed(true)
                .setConnectionRequestTimeout(getConnectionRequestTimeout()).setSocketTimeout(getSocketTimeout())
                .setConnectTimeout(getConnectionTimeout()).build();
        httpget.setConfig(requestConfig);
        HttpClientBuilder builder = HttpClientBuilder.create();
        builder.setUserAgent(getUserAgentString());
        if (isAuthenticate()) {
            CredentialsProvider credentialsProvider = new BasicCredentialsProvider();
            credentialsProvider.setCredentials(AuthScope.ANY,
                    new UsernamePasswordCredentials(getUsername(), getPassword()));
            builder.setDefaultCredentialsProvider(credentialsProvider);
        }
        CloseableHttpClient httpclient = builder.build();
        HttpClientContext context = HttpClientContext.create();
        CloseableHttpResponse response = httpclient.execute(httpget, context);
        HttpHost target = context.getTargetHost();
        List<URI> redirectLocations = context.getRedirectLocations();
        URI location = URIUtils.resolve(httpget.getURI(), target, redirectLocations);
        url = location.toString();
        EntityUtils.consumeQuietly(response.getEntity());
        HttpClientUtils.closeQuietly(response);
    } catch (IOException | URISyntaxException ex) {
        Logger.getLogger(SpiderConfig.class.getName()).log(Level.SEVERE, null, ex);
        System.err.println(url);
    }
    return url;
}

From source file:org.attribyte.api.http.impl.commons.Commons4Client.java

private void initFromOptions(final ClientOptions options) {

    if (options != ClientOptions.IMPLEMENTATION_DEFAULT) {

        HttpClientBuilder builder = HttpClients.custom();
        builder.setMaxConnTotal(options.maxConnectionsTotal);
        builder.setMaxConnPerRoute(options.maxConnectionsPerDestination);
        builder.setUserAgent(options.userAgent);
        if (options.proxyHost != null) {
            builder.setProxy(new HttpHost(options.proxyHost, options.proxyPort));
        }/*  w  ww.j a v  a 2s.c  o m*/

        this.defaultRequestConfig = RequestConfig.custom().setConnectTimeout(options.connectionTimeoutMillis)
                .setConnectionRequestTimeout(options.requestTimeoutMillis)
                .setRedirectsEnabled(RequestOptions.DEFAULT_FOLLOW_REDIRECTS)
                .setMaxRedirects(RequestOptions.DEFAULT_FOLLOW_REDIRECTS ? 5 : 0)
                .setAuthenticationEnabled(false).setCircularRedirectsAllowed(false)
                .setSocketTimeout(options.socketTimeoutMillis).build();
        builder.setDefaultRequestConfig(defaultRequestConfig);

        ConnectionConfig connectionConfig = ConnectionConfig.custom()
                .setBufferSize(
                        options.requestBufferSize > options.responseBufferSize ? options.requestBufferSize
                                : options.responseBufferSize)
                .build();
        builder.setDefaultConnectionConfig(connectionConfig);

        this.httpClient = builder.build();
    } else {
        this.defaultRequestConfig = RequestConfig.DEFAULT;
        this.httpClient = HttpClients.createDefault();
    }
}