Example usage for org.apache.http.client.config RequestConfig copy

List of usage examples for org.apache.http.client.config RequestConfig copy

Introduction

In this page you can find the example usage for org.apache.http.client.config RequestConfig copy.

Prototype

public static RequestConfig.Builder copy(final RequestConfig config) 

Source Link

Usage

From source file:com.googlecode.jdeltasync.DeltaSyncClient.java

/**
 * Sets the connection timeout of the {@link HttpClient} instance. See
 * {@link CoreConnectionPNames#CONNECTION_TIMEOUT}.
 *
 * @param timeout the timeout.//  w ww  .j a v  a 2 s  .  c  om
 */
@Override
public void setConnectionTimeout(int timeout) {
    this.rcConfig = RequestConfig.copy(this.rcConfig).setConnectTimeout(timeout).build();
}

From source file:com.googlecode.jdeltasync.DeltaSyncClient.java

/**
 * Sets the socket timeout (SO_TIMEOUT) of the {@link HttpClient} instance. See
 * {@link CoreConnectionPNames#SO_TIMEOUT}.
 *
 * @param timeout the timeout./*  w w w  .j a v a2 s  .co m*/
 */
@Override
public void setSoTimeout(int timeout) {
    this.rcConfig = RequestConfig.copy(this.rcConfig).setSocketTimeout(timeout).build();
}

From source file:com.ibm.watson.developer_cloud.professor_languo.ingestion.RankerCreationUtil.java

/**
 * /* w ww  .  j  ava 2s  .co  m*/
 * @param uri
 * @param username
 * @param password
 * @return
 */
public static HttpClient createHttpClient(String uri, String username, String password) {
    final URI scopeUri = URI.create(uri);

    final BasicCredentialsProvider credentialsProvider = new BasicCredentialsProvider();
    credentialsProvider.setCredentials(new AuthScope(scopeUri.getHost(), scopeUri.getPort()),
            new UsernamePasswordCredentials(username, password));

    final HttpClientBuilder builder = HttpClientBuilder.create().setMaxConnTotal(128).setMaxConnPerRoute(32)
            .setDefaultRequestConfig(
                    RequestConfig.copy(RequestConfig.DEFAULT).setRedirectsEnabled(true).build());
    builder.setDefaultCredentialsProvider(credentialsProvider);

    return builder.build();
}

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

public HTTPClient(final ClientIdentification.Agent agent) {
    super();// www  .j  av  a2 s  .co  m
    this.timeout = agent.clientTimeout;
    clientBuilder.setUserAgent(agent.userAgent);
    reqConfBuilder = RequestConfig.copy(dfltReqConf);
    setTimout(agent.clientTimeout);
}

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

public HTTPClient(final ClientIdentification.Agent agent, final int timeout) {
    super();//w  w w  .  ja  v  a  2s  .  co m
    this.timeout = timeout;
    clientBuilder.setUserAgent(agent.userAgent);
    reqConfBuilder = RequestConfig.copy(dfltReqConf);
    setTimout(timeout);
}

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

@Override
public Response send(Request request, RequestOptions options) throws IOException {

    HttpUriRequest commonsRequest = null;

    switch (request.getMethod()) {
    case GET:/*  ww w  .ja  v  a2s  .  c o  m*/
        commonsRequest = new HttpGet(request.getURI());
        break;
    case DELETE:
        commonsRequest = new HttpDelete(request.getURI());
        break;
    case HEAD:
        commonsRequest = new HttpHead(request.getURI());
        break;
    case POST: {
        HttpEntityEnclosingRequestBase entityEnclosingRequest = new HttpPost(request.getURI());
        commonsRequest = entityEnclosingRequest;
        EntityBuilder entityBuilder = EntityBuilder.create();
        if (request.getBody() != null) {
            entityBuilder.setBinary(request.getBody().toByteArray());
        } else {
            Collection<Parameter> parameters = request.getParameters();
            List<NameValuePair> nameValuePairs = Lists.newArrayListWithExpectedSize(parameters.size());
            for (Parameter parameter : parameters) {
                String[] values = parameter.getValues();
                for (String value : values) {
                    nameValuePairs.add(new BasicNameValuePair(parameter.getName(), value));
                }
            }
        }
        entityEnclosingRequest.setEntity(entityBuilder.build());
        break;
    }
    case PUT: {
        HttpEntityEnclosingRequestBase entityEnclosingRequest = new HttpPut(request.getURI());
        commonsRequest = entityEnclosingRequest;
        EntityBuilder entityBuilder = EntityBuilder.create();
        if (request.getBody() != null) {
            entityBuilder.setBinary(request.getBody().toByteArray());
        }
        entityEnclosingRequest.setEntity(entityBuilder.build());
        break;
    }
    }

    Collection<Header> headers = request.getHeaders();
    for (Header header : headers) {
        String[] values = header.getValues();
        for (String value : values) {
            commonsRequest.setHeader(header.getName(), value);
        }
    }

    ResponseBuilder builder = new ResponseBuilder();
    CloseableHttpResponse response = null;
    InputStream is = null;
    try {
        if (options.followRedirects != RequestOptions.DEFAULT_FOLLOW_REDIRECTS) {
            RequestConfig localConfig = RequestConfig.copy(defaultRequestConfig)
                    .setRedirectsEnabled(options.followRedirects)
                    .setMaxRedirects(options.followRedirects ? 5 : 0).build();
            HttpClientContext localContext = HttpClientContext.create();
            localContext.setRequestConfig(localConfig);
            response = httpClient.execute(commonsRequest, localContext);
        } else {
            response = httpClient.execute(commonsRequest);
        }

        builder.setStatusCode(response.getStatusLine().getStatusCode());
        for (org.apache.http.Header header : response.getAllHeaders()) {
            builder.addHeader(header.getName(), header.getValue());

        }
        HttpEntity entity = response.getEntity();
        if (entity != null) {
            is = entity.getContent();
            if (is != null) {
                builder.setBody(Request.bodyFromInputStream(is, options.maxResponseBytes));
            }
        }

    } finally {
        if (is != null) {
            try {
                is.close();
            } catch (IOException ioe) {
                //TODO?
            }
        }
        if (response != null) {
            response.close();
        }
    }

    return builder.create();
}

From source file:org.apache.tamaya.etcd.EtcdAccessor.java

/**
 * Creates/updates an entry in etcd. The response as follows:
 * // w w  w  .  jav a2s . c o  m
 * <pre>
 *     {
 * "action": "set",
 * "node": {
 * "createdIndex": 3,
 * "key": "/message",
 * "modifiedIndex": 3,
 * "value": "Hello etcd"
 * },
 * "prevNode": {
 * "createdIndex": 2,
 * "key": "/message",
 * "value": "Hello world",
 * "modifiedIndex": 2
 * }
 * }
 * </pre>
 * 
 * is mapped to:
 * 
 * <pre>
 *     key=value
 *     _key.source=[etcd]http://127.0.0.1:4001
 *     _key.createdIndex=12
 *     _key.modifiedIndex=34
 *     _key.ttl=300
 *     _key.expiry=...
 *      // optional
 *     _key.prevNode.createdIndex=12
 *     _key.prevNode.modifiedIndex=34
 *     _key.prevNode.ttl=300
 *     _key.prevNode.expiration=...
 * </pre>
 *
 * @param key        the property key, not null
 * @param value      the value to be set
 * @param ttlSeconds the ttl in seconds (optional)
 * @return the result map as described above.
 */
public Map<String, String> set(String key, String value, Integer ttlSeconds) {
    final Map<String, String> result = new HashMap<>();
    try {
        final HttpPut put = new HttpPut(serverURL + "/v2/keys/" + key);
        put.setConfig(RequestConfig.copy(RequestConfig.DEFAULT).setSocketTimeout(socketTimeout)
                .setConnectionRequestTimeout(timeout).setConnectTimeout(connectTimeout).build());
        final List<NameValuePair> nvps = new ArrayList<>();
        nvps.add(new BasicNameValuePair("value", value));
        if (ttlSeconds != null) {
            nvps.add(new BasicNameValuePair("ttl", ttlSeconds.toString()));
        }
        put.setEntity(new UrlEncodedFormEntity(nvps));
        try (CloseableHttpResponse response = httpclient.execute(put)) {
            if (response.getStatusLine().getStatusCode() == HttpStatus.SC_CREATED
                    || response.getStatusLine().getStatusCode() == HttpStatus.SC_OK) {
                final HttpEntity entity = response.getEntity();
                final JsonReader reader = readerFactory
                        .createReader(new StringReader(EntityUtils.toString(entity)));
                final JsonObject o = reader.readObject();
                final JsonObject node = o.getJsonObject("node");
                if (node.containsKey("createdIndex")) {
                    result.put("_" + key + ".createdIndex", String.valueOf(node.getInt("createdIndex")));
                }
                if (node.containsKey("modifiedIndex")) {
                    result.put("_" + key + ".modifiedIndex", String.valueOf(node.getInt("modifiedIndex")));
                }
                if (node.containsKey("expiration")) {
                    result.put("_" + key + ".expiration", String.valueOf(node.getString("expiration")));
                }
                if (node.containsKey("ttl")) {
                    result.put("_" + key + ".ttl", String.valueOf(node.getInt("ttl")));
                }
                result.put(key, node.getString("value"));
                result.put("_" + key + ".source", "[etcd]" + serverURL);
                parsePrevNode(key, result, node);
                EntityUtils.consume(entity);
            }
        }
    } catch (final Exception e) {
        LOG.log(Level.INFO, "Error writing to etcd: " + serverURL, e);
        result.put("_ERROR", "Error writing '" + key + "' to etcd: " + serverURL + ": " + e.toString());
    }
    return result;
}

From source file:ch.cyberduck.core.dav.DAVSession.java

@Override
public boolean alert(final ConnectionCallback callback) throws BackgroundException {
    if (super.alert(callback)) {
        // Propose protocol change if HEAD request redirects to HTTPS
        final Path home = new DefaultHomeFinderService(this).find();
        try {//  www . j av  a  2 s .  c om
            final RequestConfig context = client.context().getRequestConfig();
            final HttpHead request = new HttpHead(new DAVPathEncoder().encode(home));
            request.setConfig(RequestConfig.copy(context).setRedirectsEnabled(false).build());
            final Header location = client.execute(request, new ValidatingResponseHandler<Header>() {
                @Override
                public Header handleResponse(final HttpResponse response) throws IOException {
                    if (response.getStatusLine().getStatusCode() == HttpStatus.SC_MOVED_PERMANENTLY) {
                        return response.getFirstHeader(HttpHeaders.LOCATION);
                    }
                    return null;
                }
            });
            // Reset default redirect configuration in context
            client.context().setRequestConfig(RequestConfig.copy(context).setRedirectsEnabled(true).build());
            if (null != location) {
                final URL url = new URL(location.getValue());
                if (StringUtils.equals(Scheme.https.name(), url.getProtocol())) {
                    try {
                        callback.warn(host,
                                MessageFormat.format(LocaleFactory.localizedString("Unsecured {0} connection",
                                        "Credentials"), host.getProtocol().getName()),
                                MessageFormat.format("{0} {1}.",
                                        MessageFormat.format(LocaleFactory.localizedString(
                                                "The server supports encrypted connections. Do you want to switch to {0}?",
                                                "Credentials"), new DAVSSLProtocol().getName()),
                                        LocaleFactory.localizedString(
                                                "Please contact your web hosting service provider for assistance",
                                                "Support")),
                                LocaleFactory.localizedString("Continue", "Credentials"),
                                LocaleFactory.localizedString("Change", "Credentials"),
                                String.format("connection.unsecure.%s", host.getHostname()));
                        // Continue chosen. Login using plain FTP.
                    } catch (LoginCanceledException e) {
                        // Protocol switch
                        host.setHostname(url.getHost());
                        host.setProtocol(ProtocolFactory.get().forScheme(Scheme.davs));
                        return false;
                    }
                }
            }
            // Continue with default alert
        } catch (SardineException e) {
            // Ignore failure
            log.warn(String.format("Ignore failed HEAD request to %s with %s.", host, e.getResponsePhrase()));
        } catch (IOException e) {
            throw new HttpExceptionMappingService().map(e);
        }
        return preferences.getBoolean("webdav.basic.preemptive");
    }
    return false;
}