Search in sources :

Example 6 with Builder

use of org.apache.http.client.config.RequestConfig.Builder in project webtools.sourceediting by eclipse.

the class HttpClientProvider method getLastModified.

private static long getLastModified(URL url) {
    CloseableHttpClient httpclient = HttpClients.createDefault();
    CloseableHttpResponse response = null;
    try {
        HttpHost target = new HttpHost(url.getHost(), url.getPort(), url.getProtocol());
        Builder builder = RequestConfig.custom();
        HttpHost proxy = getProxy(target);
        if (proxy != null) {
            builder = builder.setProxy(proxy);
        }
        RequestConfig config = builder.build();
        HttpHead request = new HttpHead(url.toURI());
        request.setConfig(config);
        response = httpclient.execute(target, request);
        Header[] s = response.getHeaders("last-modified");
        if (s != null && s.length > 0) {
            String lastModified = s[0].getValue();
            return new Date(lastModified).getTime();
        }
    } catch (Exception e) {
        logWarning(e);
        return -1;
    } finally {
        if (response != null) {
            try {
                response.close();
            } catch (IOException e) {
            }
        }
        try {
            httpclient.close();
        } catch (IOException e) {
        }
    }
    return -1;
}
Also used : CloseableHttpClient(org.apache.http.impl.client.CloseableHttpClient) RequestConfig(org.apache.http.client.config.RequestConfig) Header(org.apache.http.Header) HttpHost(org.apache.http.HttpHost) Builder(org.apache.http.client.config.RequestConfig.Builder) CloseableHttpResponse(org.apache.http.client.methods.CloseableHttpResponse) IOException(java.io.IOException) HttpHead(org.apache.http.client.methods.HttpHead) Date(java.util.Date) URISyntaxException(java.net.URISyntaxException) IOException(java.io.IOException)

Example 7 with Builder

use of org.apache.http.client.config.RequestConfig.Builder in project janusgraph by JanusGraph.

the class RestClientSetupTest method testConnectAndSocketTimeout.

@Test
public void testConnectAndSocketTimeout() throws Exception {
    final RestClientBuilder.RequestConfigCallback rcc = configCallbackTestBase(ImmutableMap.<String, String>builder().put("index." + INDEX_NAME + ".elasticsearch.connect-timeout", "5000").put("index." + INDEX_NAME + ".elasticsearch.socket-timeout", "60000").build());
    // verifying that the custom callback is in the chain
    final RequestConfig.Builder rccb = mock(RequestConfig.Builder.class);
    when(rccb.setConnectTimeout(any(Integer.class))).thenReturn(rccb);
    ArgumentCaptor<Integer> connectArgumentCaptor = ArgumentCaptor.forClass(Integer.class);
    ArgumentCaptor<Integer> socketArgumentCaptor = ArgumentCaptor.forClass(Integer.class);
    rcc.customizeRequestConfig(rccb);
    verify(rccb).setConnectTimeout(connectArgumentCaptor.capture());
    verify(rccb).setSocketTimeout(socketArgumentCaptor.capture());
    assertEquals(5000, connectArgumentCaptor.getValue());
    assertEquals(60000, socketArgumentCaptor.getValue());
}
Also used : AtomicInteger(java.util.concurrent.atomic.AtomicInteger) RequestConfig(org.apache.http.client.config.RequestConfig) Builder(org.apache.http.client.config.RequestConfig.Builder) RestClientBuilder(org.elasticsearch.client.RestClientBuilder) Mockito.anyString(org.mockito.Mockito.anyString) Test(org.junit.jupiter.api.Test)

Example 8 with Builder

use of org.apache.http.client.config.RequestConfig.Builder in project joynr by bmwcarit.

the class HttpMessageSender method sendMessage.

public void sendMessage(ChannelAddress address, byte[] serializedMessage, SuccessAction successAction, FailureAction failureAction) {
    // check if messageReceiver is ready to receive replies otherwise delay request by at least 100 ms
    if (!messageReceiver.isReady()) {
        long delay_ms = DELAY_RECEIVER_NOT_STARTED_MS;
        failureAction.execute(new JoynrDelayMessageException(delay_ms, RECEIVER_NOT_STARTED_REASON));
    }
    String sendUrl = urlResolver.getSendUrl(address.getMessagingEndpointUrl());
    logger.trace("SENDING: channelId: {} message: {}", sendUrl, serializedMessage);
    HttpContext context = new BasicHttpContext();
    // execute http command to send
    CloseableHttpResponse response = null;
    try {
        HttpPost httpPost = httpRequestFactory.createHttpPost(URI.create(sendUrl));
        httpPost.addHeader(new BasicHeader(httpConstants.getHEADER_CONTENT_TYPE(), httpConstants.getAPPLICATION_JSON() + ";charset=UTF-8"));
        httpPost.setEntity(new ByteArrayEntity(serializedMessage));
        // Clone the default config
        Builder requestConfigBuilder = RequestConfig.copy(defaultRequestConfig);
        requestConfigBuilder.setConnectionRequestTimeout(httpConstants.getSEND_MESSAGE_REQUEST_TIMEOUT());
        httpPost.setConfig(requestConfigBuilder.build());
        response = httpclient.execute(httpPost, context);
        StatusLine statusLine = response.getStatusLine();
        int statusCode = statusLine.getStatusCode();
        String statusText = statusLine.getReasonPhrase();
        switch(statusCode) {
            case HttpURLConnection.HTTP_OK:
            case HttpURLConnection.HTTP_CREATED:
                logger.trace("SENT: channelId {} message: {}", sendUrl, serializedMessage);
                successAction.execute();
                break;
            case HttpURLConnection.HTTP_BAD_REQUEST:
                HttpEntity entity = response.getEntity();
                if (entity == null) {
                    failureAction.execute(new JoynrCommunicationException("Error in HttpMessageSender. No further reason found in message body"));
                    return;
                }
                String body = EntityUtils.toString(entity, "UTF-8");
                JoynrMessagingError error = objectMapper.readValue(body, JoynrMessagingError.class);
                JoynrMessagingErrorCode joynrMessagingErrorCode = JoynrMessagingErrorCode.getJoynrMessagingErrorCode(error.getCode());
                logger.error(error.toString());
                switch(joynrMessagingErrorCode) {
                    case JOYNRMESSAGINGERROR_CHANNELNOTFOUND:
                        failureAction.execute(new JoynrChannelMissingException("Channel does not exist. Status: " + statusCode + " error: " + error.getCode() + "reason:" + error.getReason()));
                        break;
                    default:
                        failureAction.execute(new JoynrCommunicationException("Error in HttpMessageSender: " + statusText + body + " error: " + error.getCode() + "reason:" + error.getReason()));
                        break;
                }
                break;
            default:
                failureAction.execute(new JoynrCommunicationException("Unknown Error in HttpMessageSender: " + statusText + " statusCode: " + statusCode));
                break;
        }
    } catch (JoynrShutdownException e) {
        failureAction.execute(new JoynrMessageNotSentException("Message not sent to: " + address, e));
    } catch (Exception e) {
        // An exception occured - this could still be a communication error (e.g Connection refused)
        failureAction.execute(new JoynrCommunicationException(e.getClass().getName() + "Exception while communicating. error: " + e.getMessage()));
    } finally {
        if (response != null) {
            try {
                response.close();
            } catch (IOException e) {
            }
        }
    }
}
Also used : HttpPost(io.joynr.messaging.http.operation.HttpPost) HttpEntity(org.apache.http.HttpEntity) BasicHttpContext(org.apache.http.protocol.BasicHttpContext) Builder(org.apache.http.client.config.RequestConfig.Builder) BasicHttpContext(org.apache.http.protocol.BasicHttpContext) HttpContext(org.apache.http.protocol.HttpContext) JoynrMessagingErrorCode(io.joynr.messaging.datatypes.JoynrMessagingErrorCode) IOException(java.io.IOException) JoynrCommunicationException(io.joynr.exceptions.JoynrCommunicationException) JoynrShutdownException(io.joynr.exceptions.JoynrShutdownException) JoynrMessageNotSentException(io.joynr.exceptions.JoynrMessageNotSentException) JoynrChannelMissingException(io.joynr.exceptions.JoynrChannelMissingException) IOException(java.io.IOException) JoynrDelayMessageException(io.joynr.exceptions.JoynrDelayMessageException) JoynrCommunicationException(io.joynr.exceptions.JoynrCommunicationException) StatusLine(org.apache.http.StatusLine) JoynrChannelMissingException(io.joynr.exceptions.JoynrChannelMissingException) ByteArrayEntity(org.apache.http.entity.ByteArrayEntity) JoynrDelayMessageException(io.joynr.exceptions.JoynrDelayMessageException) JoynrMessagingError(io.joynr.messaging.datatypes.JoynrMessagingError) JoynrShutdownException(io.joynr.exceptions.JoynrShutdownException) CloseableHttpResponse(org.apache.http.client.methods.CloseableHttpResponse) BasicHeader(org.apache.http.message.BasicHeader) JoynrMessageNotSentException(io.joynr.exceptions.JoynrMessageNotSentException)

Example 9 with Builder

use of org.apache.http.client.config.RequestConfig.Builder in project joynr by bmwcarit.

the class LongPollChannel method setChannelUrl.

public void setChannelUrl(String channelUrl) {
    this.httpget = httpRequestFactory.createHttpGet(URI.create(channelUrl));
    Builder requestConfigBuilder = RequestConfig.copy(defaultRequestConfig);
    httpget.setConfig(requestConfigBuilder.build());
    httpget.setHeader(httpConstants.getHEADER_X_ATMOSPHERE_TRACKING_ID(), receiverId);
    if (channelUrl.length() > 15) {
        this.id = "..." + channelUrl.substring(channelUrl.length() - 15);
    } else {
        this.id = channelUrl;
    }
}
Also used : ThreadFactoryBuilder(com.google.common.util.concurrent.ThreadFactoryBuilder) Builder(org.apache.http.client.config.RequestConfig.Builder)

Example 10 with Builder

use of org.apache.http.client.config.RequestConfig.Builder in project scout.rt by eclipse.

the class ApacheHttpRequest method setTimeout.

@Override
public void setTimeout(int connectTimeout, int readTimeout) throws IOException {
    super.setTimeout(connectTimeout, readTimeout);
    RequestConfig config = m_request.getConfig();
    Builder configBuilder = config != null ? RequestConfig.copy(config) : RequestConfig.custom();
    configBuilder.setConnectTimeout(connectTimeout);
    configBuilder.setSocketTimeout(readTimeout);
    m_request.setConfig(configBuilder.build());
}
Also used : RequestConfig(org.apache.http.client.config.RequestConfig) Builder(org.apache.http.client.config.RequestConfig.Builder)

Aggregations

Builder (org.apache.http.client.config.RequestConfig.Builder)11 IOException (java.io.IOException)5 RequestConfig (org.apache.http.client.config.RequestConfig)5 RegistryBuilder (org.apache.http.config.RegistryBuilder)4 HttpClientBuilder (org.apache.http.impl.client.HttpClientBuilder)4 URISyntaxException (java.net.URISyntaxException)3 HttpHost (org.apache.http.HttpHost)3 CloseableHttpResponse (org.apache.http.client.methods.CloseableHttpResponse)3 CloseableHttpClient (org.apache.http.impl.client.CloseableHttpClient)2 HttpContext (org.apache.http.protocol.HttpContext)2 ThreadFactoryBuilder (com.google.common.util.concurrent.ThreadFactoryBuilder)1 JoynrChannelMissingException (io.joynr.exceptions.JoynrChannelMissingException)1 JoynrCommunicationException (io.joynr.exceptions.JoynrCommunicationException)1 JoynrDelayMessageException (io.joynr.exceptions.JoynrDelayMessageException)1 JoynrMessageNotSentException (io.joynr.exceptions.JoynrMessageNotSentException)1 JoynrShutdownException (io.joynr.exceptions.JoynrShutdownException)1 JoynrMessagingError (io.joynr.messaging.datatypes.JoynrMessagingError)1 JoynrMessagingErrorCode (io.joynr.messaging.datatypes.JoynrMessagingErrorCode)1 HttpPost (io.joynr.messaging.http.operation.HttpPost)1 BufferedOutputStream (java.io.BufferedOutputStream)1