Search in sources :

Example 1 with ConnectTimeoutException

use of org.apache.hc.client5.http.ConnectTimeoutException in project dialogue by palantir.

the class ApacheHttpClientBlockingChannel method execute.

@Override
public Response execute(Endpoint endpoint, Request request) throws IOException {
    // Create base request given the URL
    URL target = baseUrl.render(endpoint, request);
    ClassicRequestBuilder builder = ClassicRequestBuilder.create(endpoint.httpMethod().name()).setUri(target.toString());
    // Fill headers
    request.headerParams().forEach(builder::addHeader);
    if (request.body().isPresent()) {
        Preconditions.checkArgument(endpoint.httpMethod() != HttpMethod.GET, "GET endpoints must not have a request body");
        Preconditions.checkArgument(endpoint.httpMethod() != HttpMethod.HEAD, "HEAD endpoints must not have a request body");
        Preconditions.checkArgument(endpoint.httpMethod() != HttpMethod.OPTIONS, "OPTIONS endpoints must not have a request body");
        RequestBody body = request.body().get();
        setBody(builder, body);
    } else if (requiresEmptyBody(endpoint)) {
        builder.setEntity(EmptyHttpEntity.INSTANCE);
    }
    long startTime = System.nanoTime();
    try {
        CloseableHttpResponse httpClientResponse = client.apacheClient().execute(builder.build());
        // Defensively ensure that resources are closed if failures occur within this block,
        // for example HttpClientResponse allocation may throw an OutOfMemoryError.
        boolean close = true;
        try {
            Response dialogueResponse = new HttpClientResponse(client, httpClientResponse);
            Response leakDetectingResponse = responseLeakDetector.wrap(dialogueResponse, endpoint);
            close = false;
            return leakDetectingResponse;
        } finally {
            if (close) {
                httpClientResponse.close();
            }
        }
    } catch (ConnectTimeoutException e) {
        // cleaner metrics.
        throw new SafeConnectTimeoutException(e, failureDiagnosticArgs(endpoint, request, startTime));
    } catch (NoHttpResponseException e) {
        // NoHttpResponseException may be thrown immediately when a request is sent if a pooled persistent
        // connection has been closed by the target server, or an intermediate proxy. In this case it's
        // important that we retry the request with a fresh connection.
        // The other possibility is that a remote server or proxy may time out an active request due
        // to inactivity and close the connection without a response, in this case the request mustn't
        // be retried.
        // We attempt to differentiate these two cases based on request duration, we expect most of
        // the prior case to occur within a couple milliseconds, however we must use a larger value
        // to account for large garbage collections.
        long durationNanos = System.nanoTime() - startTime;
        Arg<?>[] diagnosticArgs = failureDiagnosticArgs(endpoint, request, startTime);
        if (durationNanos < TimeUnit.SECONDS.toNanos(5)) {
            e.addSuppressed(new Diagnostic(diagnosticArgs));
            throw e;
        }
        throw new SafeSocketTimeoutException("Received a NoHttpResponseException", e, diagnosticArgs);
    } catch (Throwable t) {
        // We can't wrap all potential exception types, that would cause the failure to lose some amount of type
        // information. Instead, we add a suppressed throwable with no stack trace which acts as a courier
        // for our diagnostic information, ensuring it can be recorded in the logs.
        t.addSuppressed(new Diagnostic(failureDiagnosticArgs(endpoint, request, startTime)));
        throw t;
    }
}
Also used : NoHttpResponseException(org.apache.hc.core5.http.NoHttpResponseException) URL(java.net.URL) CloseableHttpResponse(org.apache.hc.client5.http.impl.classic.CloseableHttpResponse) Response(com.palantir.dialogue.Response) ClassicRequestBuilder(org.apache.hc.core5.http.io.support.ClassicRequestBuilder) CloseableHttpResponse(org.apache.hc.client5.http.impl.classic.CloseableHttpResponse) RequestBody(com.palantir.dialogue.RequestBody) ConnectTimeoutException(org.apache.hc.client5.http.ConnectTimeoutException)

Example 2 with ConnectTimeoutException

use of org.apache.hc.client5.http.ConnectTimeoutException in project sms-java-client by altiria.

the class AltiriaClient method sendSms.

/**
 * Send a SMS.
 * @param textMessage this object contains the SMS data. See AltiriaModelTextMessage class.
 * @return Json response.
 * @throws Exception
 */
public String sendSms(AltiriaModelTextMessage textMessage) throws Exception {
    log.debug("Altiria-sendSms CMD: " + textMessage.toString());
    String jsonResponse = null;
    try {
        JsonObject jsonObject = new JsonObject();
        JsonObject credentialsJsonObject = new JsonObject();
        JsonObject messageJsonObject = new JsonObject();
        JsonArray destinationsJsonArray = null;
        if (this.login == null) {
            log.error("ERROR: The login parameter is mandatory");
            throw new JsonException("LOGIN_NOT_NULL");
        }
        if (this.passwd == null) {
            log.error("ERROR: The password parameter is mandatory");
            throw new JsonException("PASSWORD_NOT_NULL");
        }
        if (textMessage.getDestination() == null || textMessage.getDestination().trim().isEmpty()) {
            log.error("ERROR: The destination parameter is mandatory");
            throw new AltiriaGwException("INVALID_DESTINATION", "015");
        } else {
            destinationsJsonArray = new JsonArray();
            destinationsJsonArray.add(new JsonPrimitive(new String(textMessage.getDestination())));
        }
        if (textMessage.getMessage() == null || textMessage.getMessage().trim().isEmpty()) {
            log.error("ERROR: The message parameter is mandatory");
            throw new AltiriaGwException("EMPTY_MESSAGE", "017");
        } else
            messageJsonObject.addProperty("msg", textMessage.getMessage());
        if (textMessage.getSenderId() != null && !textMessage.getSenderId().trim().isEmpty())
            messageJsonObject.addProperty("senderId", textMessage.getSenderId());
        if (textMessage.isAck()) {
            messageJsonObject.addProperty("ack", true);
            if (textMessage.getIdAck() != null && !textMessage.getIdAck().trim().isEmpty())
                messageJsonObject.addProperty("idAck", textMessage.getIdAck());
        }
        if (textMessage.isConcat())
            messageJsonObject.addProperty("concat", true);
        if (textMessage.isCertDelivery())
            messageJsonObject.addProperty("certDelivery", true);
        if (textMessage.getEncoding() != null && textMessage.getEncoding().equals("unicode"))
            messageJsonObject.addProperty("encoding", "unicode");
        credentialsJsonObject.addProperty(this.isApiKey ? "apikey" : "login", this.login);
        credentialsJsonObject.addProperty(this.isApiKey ? "apisecret" : "passwd", this.passwd);
        jsonObject.add("credentials", credentialsJsonObject);
        jsonObject.add("destination", destinationsJsonArray);
        jsonObject.add("message", messageJsonObject);
        jsonObject.addProperty("source", source);
        RequestConfig config = RequestConfig.custom().setConnectTimeout(this.connectionTimeout, TimeUnit.MILLISECONDS).setResponseTimeout(this.timeout, TimeUnit.MILLISECONDS).build();
        HttpClientBuilder builder = HttpClientBuilder.create();
        builder.setDefaultRequestConfig(config);
        CloseableHttpClient httpClient = builder.build();
        HttpPost request = new HttpPost(this.urlBase + "/sendSms");
        final HttpEntity[] entity = { HttpEntities.create(jsonObject.toString(), ContentType.APPLICATION_JSON.withCharset(StandardCharsets.UTF_8)) };
        request.setEntity(entity[0]);
        CloseableHttpResponse httpResponse = null;
        try {
            httpResponse = httpClient.execute(request);
            jsonResponse = EntityUtils.toString(httpResponse.getEntity());
            log.debug("HTTP status:" + httpResponse.getCode());
            log.debug("HTTP body:" + jsonResponse);
            LinkedTreeMap<String, Object> mapBody = gson.fromJson(jsonResponse, new TypeToken<LinkedTreeMap<String, Object>>() {
            }.getType());
            if (httpResponse.getCode() != 200) {
                log.error("ERROR: Invalid request: " + jsonResponse);
                String errorMsg = (String) mapBody.get("error");
                throw new JsonException(errorMsg);
            } else {
                String status = (String) mapBody.get("status");
                if (!status.equals("000")) {
                    String errorMsg = getStatus(status);
                    log.error("ERROR: Invalid parameter. Error message: " + errorMsg + ", Status: " + status);
                    throw new AltiriaGwException(errorMsg, status);
                }
            }
        } catch (ConnectTimeoutException cte) {
            log.error("ERROR: Connection timeout");
            throw new ConnectionException("CONNECTION_TIMEOUT");
        } catch (SocketTimeoutException ste) {
            log.error("ERROR: Response timeout");
            throw new ConnectionException("RESPONSE_TIMEOUT");
        } finally {
            try {
                if (httpResponse != null)
                    httpResponse.close();
                if (httpClient != null)
                    httpClient.close();
            } catch (IOException ioe) {
                log.error("ERROR closing resources");
            }
        }
    } catch (GeneralAltiriaException e) {
        throw e;
    } catch (Exception e) {
        log.error("ERROR: Unexpected error", e);
        throw new AltiriaGwException("GENERAL_ERROR", "001");
    }
    return jsonResponse;
}
Also used : JsonException(com.altiria.app.exception.JsonException) RequestConfig(org.apache.hc.client5.http.config.RequestConfig) CloseableHttpClient(org.apache.hc.client5.http.impl.classic.CloseableHttpClient) HttpPost(org.apache.hc.client5.http.classic.methods.HttpPost) HttpEntity(org.apache.hc.core5.http.HttpEntity) JsonPrimitive(com.google.gson.JsonPrimitive) JsonObject(com.google.gson.JsonObject) HttpClientBuilder(org.apache.hc.client5.http.impl.classic.HttpClientBuilder) IOException(java.io.IOException) GeneralAltiriaException(com.altiria.app.exception.GeneralAltiriaException) SocketTimeoutException(java.net.SocketTimeoutException) ConnectTimeoutException(org.apache.hc.client5.http.ConnectTimeoutException) AltiriaGwException(com.altiria.app.exception.AltiriaGwException) ConnectionException(com.altiria.app.exception.ConnectionException) IOException(java.io.IOException) JsonException(com.altiria.app.exception.JsonException) JsonArray(com.google.gson.JsonArray) GeneralAltiriaException(com.altiria.app.exception.GeneralAltiriaException) SocketTimeoutException(java.net.SocketTimeoutException) TypeToken(com.google.gson.reflect.TypeToken) CloseableHttpResponse(org.apache.hc.client5.http.impl.classic.CloseableHttpResponse) AltiriaGwException(com.altiria.app.exception.AltiriaGwException) JsonObject(com.google.gson.JsonObject) ConnectionException(com.altiria.app.exception.ConnectionException) ConnectTimeoutException(org.apache.hc.client5.http.ConnectTimeoutException)

Example 3 with ConnectTimeoutException

use of org.apache.hc.client5.http.ConnectTimeoutException in project sms-java-client by altiria.

the class AltiriaClient method getCredit.

/**
 * Get the user credit.
 * @return credit
 * @throws Exception
 */
public String getCredit() throws Exception {
    log.debug("Altiria-getCredit CMD");
    String credit = null;
    try {
        if (this.login == null) {
            log.error("ERROR: The login parameter is mandatory");
            throw new JsonException("LOGIN_NOT_NULL");
        }
        if (this.passwd == null) {
            log.error("ERROR: The password parameter is mandatory");
            throw new JsonException("PASSWORD_NOT_NULL");
        }
        JsonObject jsonObject = new JsonObject();
        JsonObject credentialsJsonObject = new JsonObject();
        credentialsJsonObject.addProperty(this.isApiKey ? "apikey" : "login", this.login);
        credentialsJsonObject.addProperty(this.isApiKey ? "apisecret" : "passwd", this.passwd);
        jsonObject.add("credentials", credentialsJsonObject);
        jsonObject.addProperty("source", source);
        RequestConfig config = RequestConfig.custom().setConnectTimeout(this.connectionTimeout, TimeUnit.MILLISECONDS).setResponseTimeout(this.timeout, TimeUnit.MILLISECONDS).build();
        HttpClientBuilder builder = HttpClientBuilder.create();
        builder.setDefaultRequestConfig(config);
        CloseableHttpClient httpClient = builder.build();
        HttpPost request = new HttpPost(this.urlBase + "/getCredit");
        final HttpEntity[] entity = { HttpEntities.create(jsonObject.toString(), ContentType.APPLICATION_JSON.withCharset(StandardCharsets.UTF_8)) };
        request.setEntity(entity[0]);
        CloseableHttpResponse httpResponse = null;
        try {
            httpResponse = httpClient.execute(request);
            String jsonResponse = EntityUtils.toString(httpResponse.getEntity());
            log.debug("HTTP status:" + httpResponse.getCode());
            log.debug("HTTP body:" + jsonResponse);
            LinkedTreeMap<String, Object> mapBody = gson.fromJson(jsonResponse, new TypeToken<LinkedTreeMap<String, Object>>() {
            }.getType());
            if (httpResponse.getCode() != 200) {
                log.error("ERROR: Invalid request: " + jsonResponse);
                String errorMsg = (String) mapBody.get("error");
                throw new JsonException(errorMsg);
            } else {
                String status = (String) mapBody.get("status");
                if (!status.equals("000")) {
                    String errorMsg = getStatus(status);
                    log.error("ERROR: Invalid parameter. Error message: " + errorMsg + ", Status: " + status);
                    throw new AltiriaGwException(errorMsg, status);
                } else
                    credit = (String) mapBody.get("credit");
            }
        } catch (ConnectTimeoutException cte) {
            log.error("ERROR: Connection timeout");
            throw new ConnectionException("CONNECTION_TIMEOUT");
        } catch (SocketTimeoutException ste) {
            log.error("ERROR: Response timeout");
            throw new ConnectionException("RESPONSE_TIMEOUT");
        } finally {
            try {
                if (httpResponse != null)
                    httpResponse.close();
                if (httpClient != null)
                    httpClient.close();
            } catch (IOException ioe) {
                log.error("ERROR closing resources");
            }
        }
    } catch (GeneralAltiriaException e) {
        throw e;
    } catch (Exception e) {
        log.error("ERROR: Unexpected error", e);
        throw new AltiriaGwException("GENERAL_ERROR", "001");
    }
    return credit;
}
Also used : JsonException(com.altiria.app.exception.JsonException) RequestConfig(org.apache.hc.client5.http.config.RequestConfig) CloseableHttpClient(org.apache.hc.client5.http.impl.classic.CloseableHttpClient) HttpPost(org.apache.hc.client5.http.classic.methods.HttpPost) HttpEntity(org.apache.hc.core5.http.HttpEntity) JsonObject(com.google.gson.JsonObject) HttpClientBuilder(org.apache.hc.client5.http.impl.classic.HttpClientBuilder) IOException(java.io.IOException) GeneralAltiriaException(com.altiria.app.exception.GeneralAltiriaException) SocketTimeoutException(java.net.SocketTimeoutException) ConnectTimeoutException(org.apache.hc.client5.http.ConnectTimeoutException) AltiriaGwException(com.altiria.app.exception.AltiriaGwException) ConnectionException(com.altiria.app.exception.ConnectionException) IOException(java.io.IOException) JsonException(com.altiria.app.exception.JsonException) GeneralAltiriaException(com.altiria.app.exception.GeneralAltiriaException) SocketTimeoutException(java.net.SocketTimeoutException) TypeToken(com.google.gson.reflect.TypeToken) CloseableHttpResponse(org.apache.hc.client5.http.impl.classic.CloseableHttpResponse) JsonObject(com.google.gson.JsonObject) AltiriaGwException(com.altiria.app.exception.AltiriaGwException) ConnectionException(com.altiria.app.exception.ConnectionException) ConnectTimeoutException(org.apache.hc.client5.http.ConnectTimeoutException)

Aggregations

ConnectTimeoutException (org.apache.hc.client5.http.ConnectTimeoutException)3 CloseableHttpResponse (org.apache.hc.client5.http.impl.classic.CloseableHttpResponse)3 AltiriaGwException (com.altiria.app.exception.AltiriaGwException)2 ConnectionException (com.altiria.app.exception.ConnectionException)2 GeneralAltiriaException (com.altiria.app.exception.GeneralAltiriaException)2 JsonException (com.altiria.app.exception.JsonException)2 JsonObject (com.google.gson.JsonObject)2 TypeToken (com.google.gson.reflect.TypeToken)2 IOException (java.io.IOException)2 SocketTimeoutException (java.net.SocketTimeoutException)2 HttpPost (org.apache.hc.client5.http.classic.methods.HttpPost)2 RequestConfig (org.apache.hc.client5.http.config.RequestConfig)2 CloseableHttpClient (org.apache.hc.client5.http.impl.classic.CloseableHttpClient)2 HttpClientBuilder (org.apache.hc.client5.http.impl.classic.HttpClientBuilder)2 HttpEntity (org.apache.hc.core5.http.HttpEntity)2 JsonArray (com.google.gson.JsonArray)1 JsonPrimitive (com.google.gson.JsonPrimitive)1 RequestBody (com.palantir.dialogue.RequestBody)1 Response (com.palantir.dialogue.Response)1 URL (java.net.URL)1