Search in sources :

Example 1 with RequestAbortedException

use of org.apache.http.impl.execchain.RequestAbortedException in project SEPA by arces-wot.

the class SPARQL11Protocol method executeRequest.

/*
	 * http://hc.apache.org/httpcomponents-client-4.5.x/tutorial/html/fundamentals.
	 * html#d5e279
	 * 
	 * 1.5. Exception handling
	 * 
	 * HTTP protocol processors can throw two types of exceptions:
	 * 
	 * 1) java.io.IOException in case of an I/O failure such as socket timeout or an
	 * socket reset 2) HttpException that signals an HTTP failure such as a
	 * violation of the HTTP protocol.
	 * 
	 * Usually I/O errors are considered non-fatal and recoverable, whereas HTTP
	 * protocol errors are considered fatal and cannot be automatically recovered
	 * from. Please note that HttpClient implementations re-throw HttpExceptions as
	 * ClientProtocolException, which is a subclass of java.io.IOException. This
	 * enables the users of HttpClient to handle both I/O errors and protocol
	 * violations from a single catch clause.
	 */
/*
	 * {"error":"IOException","status_code":500,
	 * "error_description":"Connect to mml.arces.unibo.it:8666 [mml.arces.unibo.it/137.204.143.19] failed: Operation timed out"
	 * }
	 * 
	 * extended by java.io.IOException extended by java.net.SocketException extended
	 * by java.net.ConnectException extended by
	 * org.apache.http.conn.HttpHostConnectException
	 * 
	 */
private Response executeRequest(HttpUriRequest req, Request request) {
    CloseableHttpResponse httpResponse = null;
    HttpEntity responseEntity = null;
    int responseCode = 0;
    String responseBody = null;
    ErrorResponse errorResponse = null;
    try {
        // Execute HTTP request
        logger.trace(req.toString() + " " + request.toString() + " (timeout: " + request.getTimeout() + " ms) ");
        long start = Timings.getTime();
        httpResponse = httpClient.execute(req);
        long stop = Timings.getTime();
        if (request.getClass().equals(UpdateRequest.class))
            Timings.log("HTTP_UPDATE_TIME", start, stop);
        else
            Timings.log("HTTP_QUERY_TIME", start, stop);
        // Status code
        responseCode = httpResponse.getStatusLine().getStatusCode();
        // Body
        responseEntity = httpResponse.getEntity();
        responseBody = EntityUtils.toString(responseEntity, Charset.forName("UTF-8"));
        logger.trace(String.format("Response code: %d", responseCode));
        EntityUtils.consume(responseEntity);
    } catch (Exception e) {
        errorResponse = new ErrorResponse(HttpStatus.SC_INTERNAL_SERVER_ERROR, e.getClass().getName(), e.getMessage());
        // Considered as *** TIMEOUTS ***
        if (e instanceof HttpHostConnectException || e instanceof SocketTimeoutException || e instanceof ConnectTimeoutException || e instanceof RequestAbortedException)
            errorResponse = new ErrorResponse(HttpStatus.SC_REQUEST_TIMEOUT, e.getClass().getName(), e.getMessage() + " [timeout: " + request.getTimeout() + " ms retry: " + request.getNRetry() + "]");
    } finally {
        try {
            if (httpResponse != null)
                httpResponse.close();
        } catch (IOException e) {
            logger.error(e.getMessage());
            return new ErrorResponse(HttpStatus.SC_INTERNAL_SERVER_ERROR, "IOException", e.getMessage());
        }
        responseEntity = null;
    }
    if (responseCode >= 400 && errorResponse == null) {
        // http://mml.arces.unibo.it/TR/sparql11-se-protocol.html#ErrorResponses
        try {
            JsonObject ret = new JsonParser().parse(responseBody).getAsJsonObject();
            errorResponse = new ErrorResponse(ret.get("status_code").getAsInt(), ret.get("error").getAsString(), ret.get("error_description").getAsString());
        } catch (Exception e) {
            // E.g. parsing response from a "common" SPARQL endpoint
            logger.warn(e.getMessage() + " response code:" + responseCode + " response body: " + responseBody);
            if (responseBody.equals(""))
                responseBody = httpResponse.toString();
            errorResponse = new ErrorResponse(responseCode, "sparql11_endpoint", responseBody);
        }
    }
    if (errorResponse != null) {
        logger.error(errorResponse + " Token expired: " + errorResponse.isTokenExpiredError() + " Security manager: " + (sm != null) + " nRetry: " + request.getNRetry());
        // TOKEN EXPIRED
        if (errorResponse.isTokenExpiredError()) {
            try {
                logger.info("Refresh token");
                Response ret = sm.refreshToken();
                if (ret.isError())
                    return ret;
                JWTResponse token = (JWTResponse) ret;
                logger.debug(token.getAccessToken());
                req.setHeader("Authorization", token.getTokenType() + " " + token.getAccessToken());
            // request.setAuthorizationHeader(token.getTokenType()+"
            // "+token.getAccessToken());
            } catch (SEPAPropertiesException | SEPASecurityException e) {
                logger.error("Failed to refresh token. " + e.getMessage());
                return errorResponse;
            }
            return executeRequest(req, request);
        } else // TIMEOUT
        if (errorResponse.isTimeout() && request.getNRetry() > 0) {
            logger.warn(errorResponse);
            logger.warn("*** TIMEOUT RETRY " + request.getNRetry() + " ***");
            request.retry();
            return executeRequest(req, request);
        }
        return errorResponse;
    }
    return (request.getClass().equals(UpdateRequest.class) ? new UpdateResponse(responseBody) : new QueryResponse(responseBody));
}
Also used : HttpEntity(org.apache.http.HttpEntity) SEPAPropertiesException(it.unibo.arces.wot.sepa.commons.exceptions.SEPAPropertiesException) JsonObject(com.google.gson.JsonObject) SEPASecurityException(it.unibo.arces.wot.sepa.commons.exceptions.SEPASecurityException) IOException(java.io.IOException) URISyntaxException(java.net.URISyntaxException) RequestAbortedException(org.apache.http.impl.execchain.RequestAbortedException) HttpHostConnectException(org.apache.http.conn.HttpHostConnectException) SEPAPropertiesException(it.unibo.arces.wot.sepa.commons.exceptions.SEPAPropertiesException) ConnectTimeoutException(org.apache.http.conn.ConnectTimeoutException) SocketTimeoutException(java.net.SocketTimeoutException) SEPASecurityException(it.unibo.arces.wot.sepa.commons.exceptions.SEPASecurityException) IOException(java.io.IOException) UnsupportedEncodingException(java.io.UnsupportedEncodingException) ErrorResponse(it.unibo.arces.wot.sepa.commons.response.ErrorResponse) Response(it.unibo.arces.wot.sepa.commons.response.Response) CloseableHttpResponse(org.apache.http.client.methods.CloseableHttpResponse) QueryResponse(it.unibo.arces.wot.sepa.commons.response.QueryResponse) UpdateResponse(it.unibo.arces.wot.sepa.commons.response.UpdateResponse) ErrorResponse(it.unibo.arces.wot.sepa.commons.response.ErrorResponse) JWTResponse(it.unibo.arces.wot.sepa.commons.response.JWTResponse) UpdateResponse(it.unibo.arces.wot.sepa.commons.response.UpdateResponse) SocketTimeoutException(java.net.SocketTimeoutException) QueryResponse(it.unibo.arces.wot.sepa.commons.response.QueryResponse) CloseableHttpResponse(org.apache.http.client.methods.CloseableHttpResponse) HttpHostConnectException(org.apache.http.conn.HttpHostConnectException) RequestAbortedException(org.apache.http.impl.execchain.RequestAbortedException) ConnectTimeoutException(org.apache.http.conn.ConnectTimeoutException) JsonParser(com.google.gson.JsonParser) JWTResponse(it.unibo.arces.wot.sepa.commons.response.JWTResponse)

Aggregations

JsonObject (com.google.gson.JsonObject)1 JsonParser (com.google.gson.JsonParser)1 SEPAPropertiesException (it.unibo.arces.wot.sepa.commons.exceptions.SEPAPropertiesException)1 SEPASecurityException (it.unibo.arces.wot.sepa.commons.exceptions.SEPASecurityException)1 ErrorResponse (it.unibo.arces.wot.sepa.commons.response.ErrorResponse)1 JWTResponse (it.unibo.arces.wot.sepa.commons.response.JWTResponse)1 QueryResponse (it.unibo.arces.wot.sepa.commons.response.QueryResponse)1 Response (it.unibo.arces.wot.sepa.commons.response.Response)1 UpdateResponse (it.unibo.arces.wot.sepa.commons.response.UpdateResponse)1 IOException (java.io.IOException)1 UnsupportedEncodingException (java.io.UnsupportedEncodingException)1 SocketTimeoutException (java.net.SocketTimeoutException)1 URISyntaxException (java.net.URISyntaxException)1 HttpEntity (org.apache.http.HttpEntity)1 CloseableHttpResponse (org.apache.http.client.methods.CloseableHttpResponse)1 ConnectTimeoutException (org.apache.http.conn.ConnectTimeoutException)1 HttpHostConnectException (org.apache.http.conn.HttpHostConnectException)1 RequestAbortedException (org.apache.http.impl.execchain.RequestAbortedException)1