Example usage for org.apache.http.client ClientProtocolException ClientProtocolException

List of usage examples for org.apache.http.client ClientProtocolException ClientProtocolException

Introduction

In this page you can find the example usage for org.apache.http.client ClientProtocolException ClientProtocolException.

Prototype

public ClientProtocolException(final Throwable cause) 

Source Link

Usage

From source file:com.couchbase.jdbc.core.ProtocolImpl.java

public CouchResponse handleResponse(String sql, CloseableHttpResponse response)
        throws SQLException, IOException {
    int status = response.getStatusLine().getStatusCode();
    HttpEntity entity = response.getEntity();

    ObjectMapper mapper = JsonFactory.create();

    CouchResponse couchResponse = new CouchResponse();

    String strResponse = EntityUtils.toString(entity);
    //        logger.trace( "Response to query {} {}", sql, strResponse );

    Object foo = mapper.readValue(strResponse, Map.class);
    Map<String, Object> rootAsMap = null;
    if (foo instanceof Map) {
        //noinspection unchecked
        rootAsMap = (Map<String, Object>) foo;
    } else {//from   w  w  w  . ja  va  2  s. c o  m
        logger.debug("error");
    }
    couchResponse.status = (String) rootAsMap.get("status");
    couchResponse.requestId = (String) rootAsMap.get("requestID");
    Object signature = rootAsMap.get("signature");

    if (signature instanceof Map) {
        //noinspection unchecked
        couchResponse.signature = (Map) signature;
        //noinspection unchecked
        couchResponse.results = (List) rootAsMap.get("results");
    } else if (signature instanceof String) {
        couchResponse.signature = new HashMap<String, String>();
        couchResponse.signature.put("$1", (String) signature);

        Iterator iterator = ((List) rootAsMap.get("results")).iterator();

        couchResponse.results = new ArrayList<>();
        while (iterator.hasNext()) {
            Object object = iterator.next();

            HashMap entry = new HashMap();
            //noinspection unchecked
            entry.put("$1", object);
            //noinspection unchecked
            couchResponse.results.add(entry);
        }

    } else if (signature != null) {
        throw new SQLException("Error reading signature" + signature);
    }
    //noinspection unchecked
    couchResponse.metrics = MapObjectConversion.fromMap((Map) rootAsMap.get("metrics"), CouchMetrics.class);
    List errorList = (List) rootAsMap.get("errors");
    if (errorList != null) {
        //noinspection unchecked,unchecked
        couchResponse.errors = MapObjectConversion.convertListOfMapsToObjects(CouchError.class, errorList);
    }
    List warningList = (List) rootAsMap.get("warnings");
    if (warningList != null) {
        //noinspection unchecked,unchecked
        couchResponse.warnings = MapObjectConversion.convertListOfMapsToObjects(CouchError.class, warningList);

        for (CouchError warning : couchResponse.warnings) {
            if (sqlWarning != null) {
                sqlWarning = new SQLWarning(warning.msg, null, warning.code);
            } else {
                sqlWarning.setNextWarning(new SQLWarning(warning.msg, null, warning.code));
            }
        }
    }

    //JsonObject jsonObject = jsonReader.readObject();
    //logger.trace( "response from query {} {}", sql, jsonObject.toString());

    //String statusString = (String)jsonObject.get("status");

    Integer iStatus = statusStrings.get(couchResponse.status);
    String message;

    switch (status) {
    case 200:
        switch (iStatus.intValue()) {
        case N1QL_ERROR:
            List<CouchError> errors = couchResponse.errors;
            throw new SQLException(errors.get(0).msg);

        case N1QL_SUCCESS:
            return couchResponse;

        case N1QL_COMPLETED:
        case N1QL_FATAL:
        case N1QL_RUNNING:
        case N1QL_STOPPED:
        case N1QL_TIMEOUT:
            message = "Invalid Status";
            fillSQLException(message, couchResponse);

        default:
            logger.error("Unexpected status string {} for query {}", couchResponse.status, sql);
            throw new SQLException("Unexpected status: " + couchResponse.status);

        }
    case 400:
        message = "Bad Request";
        fillSQLException(message, couchResponse);
    case 401:
        message = "Unauthorized Request credentials are missing or invalid";
        fillSQLException(message, couchResponse);
    case 403:
        message = "Forbidden Request: read only violation or client unauthorized to modify";
        fillSQLException(message, couchResponse);
    case 404:
        message = "Not found: Request references an invalid keyspace or there is no primary key";
        fillSQLException(message, couchResponse);
    case 405:
        message = "Method not allowed: The REST method type in request is supported";
        fillSQLException(message, couchResponse);
    case 409:
        message = "Conflict: attempt to create a keyspace or index that already exists";
        fillSQLException(message, couchResponse);
    case 410:
        message = "Gone: The server is doing a graceful shutdown";
        fillSQLException(message, couchResponse);
    case 500:
        message = "Internal server error: unforeseen problem processing the request";
        fillSQLException(message, couchResponse);
    case 503:
        message = "Service Unavailable: there is an issue preventing the request from being serviced";
        logger.debug("Error with the request {}", message);

        CouchError errors, warnings;

        if (couchResponse.metrics.errorCount > 0) {
            errors = couchResponse.errors.get(0);
            logger.error("Error Code: {} Message: {} for query {} ", errors.code, errors.msg, sql);
        }
        if (couchResponse.metrics.warningCount > 0) {
            warnings = couchResponse.warnings.get(0);
            logger.error("Warning Code: {} Message: {} for query {}", warnings.code, warnings.msg, sql);
        }

        fillSQLException(message, couchResponse);

    default:
        throw new ClientProtocolException("Unexpected response status: " + status);

    }
}

From source file:org.gege.caldavsyncadapter.caldav.CaldavFacade.java

private void checkStatus(HttpResponse response)
        throws AuthenticationException, FileNotFoundException, ClientProtocolException {
    final int statusCode = response.getStatusLine().getStatusCode();
    lastStatusCode = statusCode;/*from w w  w .j a  v  a  2 s .  c  o  m*/
    if (response.containsHeader("ETag"))
        lastETag = response.getFirstHeader("ETag").getValue();
    else
        lastETag = "";
    if (response.containsHeader("DAV"))
        lastDav = response.getFirstHeader("DAV").getValue();
    else
        lastDav = "";

    switch (statusCode) {
    case 401:
        throw new AuthenticationException();
    case 404:
        throw new FileNotFoundException();
    case 409: //Conflict
    case 412:
    case 200:
    case 201:
    case 204:
    case 207:
        return;
    default:
        throw new ClientProtocolException("StatusCode: " + statusCode);
    }
}

From source file:com.couchbase.jdbc.core.ProtocolImpl.java

public int[] executeBatch() throws SQLException {
    try {/*from   ww w  .j  av  a2s . c  om*/
        Instance instance = getNextEndpoint();
        String url = instance.getEndpointURL(ssl);

        HttpPost httpPost = new HttpPost(url);
        httpPost.setHeader("Accept", "application/json");

        Map<String, Object> parameters = new HashMap<String, Object>();
        addOptions(parameters);
        for (String query : batchStatements) {
            parameters.put(STATEMENT, query);
        }

        CloseableHttpResponse response = httpClient.execute(httpPost);
        int status = response.getStatusLine().getStatusCode();

        if (status >= 200 && status < 300) {
            HttpEntity entity = response.getEntity();
            ObjectMapper mapper = JsonFactory.create();
            @SuppressWarnings("unchecked")
            Map<String, Object> jsonObject = (Map) mapper.fromJson(EntityUtils.toString(entity));

            String statusString = (String) jsonObject.get("status");

            if (statusString.equals("errors")) {
                List errors = (List) jsonObject.get("errors");
                Map error = (Map) errors.get(0);
                throw new SQLException((String) error.get("msg"));
            } else if (statusString.equals("success")) {
                Map metrics = (Map) jsonObject.get("metrics");
                if (metrics.containsKey("mutationCount")) {
                    updateCount = (int) metrics.get("mutationCount");
                    return new int[0];
                }
                if (metrics.containsKey("resultCount")) {
                    // TODO FIX ME resultSet = new CBResultSet(jsonObject);
                    return new int[0];
                }
            } else if (statusString.equals("running")) {
                return new int[0];
            } else if (statusString.equals("completed")) {
                return new int[0];
            } else if (statusString.equals("stopped")) {
                return new int[0];
            } else if (statusString.equals("timeout")) {
                return new int[0];
            } else if (statusString.equals("fatal")) {
                return new int[0];
            }

            else {
                //logger.error("Unexpected status string {} for query {}", statusString, query);
                throw new SQLException("Unexpected status: " + statusString);
            }
        }

        else {
            throw new ClientProtocolException("Unexpected response status: " + status);
        }
    } catch (Exception ex) {
        //logger.error ("Error executing update query {} {}", query, ex.getMessage());
        throw new SQLException("Error executing update", ex.getCause());
    }
    return new int[0];

}

From source file:com.nononsenseapps.notepad.sync.googleapi.GoogleAPITalker.java

/**
 * Parses a httpresponse and returns the string body of it. Throws
 * exceptions for select status codes.//from   w  ww  . j a v  a 2s.c om
 *
  * @throws ClientProtocolException
 * @throws PreconditionException
 */
private static String parseResponse(HttpResponse response)
        throws ClientProtocolException, PreconditionException {
    String page = "";
    BufferedReader in = null;

    Log.d(TAG, "HTTP Response Code: " + response.getStatusLine().getStatusCode());

    if (response.getStatusLine().getStatusCode() == 403) {
        // Invalid authtoken
        throw new ClientProtocolException("Status: 403, Invalid authcode");
    }

    else if (response.getStatusLine().getStatusCode() == 412) { //
        /*
         * Precondition failed. Object has been modified on server, can't do
         * update
         */
        throw new PreconditionException(
                "Etags don't match, can not perform update. Resolve the conflict then update without etag");
    }

    /*
     * else if (response.getStatusLine().getStatusCode() == 304) { throw new
     * NotModifiedException(); }
     */
    else if (response.getStatusLine().getStatusCode() == 400) {
        // Warning: can happen for a legitimate case
        // This happens if you try to delete the default list.
        // Resolv it by considering the delete successful. List will still
        // exist on server, but all tasks will be deleted from it.
        // A successful delete returns an empty response.
        // Make a log entry about it anyway though
        Log.d(TAG, "Response was 400. Either we deleted the default list in app or did something really bad");
        throw new PreconditionException("Tried to delete default list, undelete it");
    } else if (response.getStatusLine().getStatusCode() == 204) {
        // Successful delete of a tasklist. return empty string as that is
        // expected from delete

        Log.d(TAG, "Response was 204: Successful delete");
        return "";
    } else {

        try {
            if (response.getEntity() != null) {
                // Only call getContent ONCE
                InputStream content = AndroidHttpClient.getUngzippedContent(response.getEntity());
                if (content != null) {
                    in = new BufferedReader(new InputStreamReader(content));
                    StringBuilder sb = new StringBuilder("");
                    String line;
                    String NL = System.getProperty("line.separator");
                    while ((line = in.readLine()) != null) {
                        sb.append(line).append(NL);
                    }
                    in.close();
                    page = sb.toString();
                    //
                    // System.out.println(page);
                }
            }
        } catch (IOException ignored) {
        } finally {
            if (in != null) {
                try {
                    in.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }

    return page;
}

From source file:org.apache.http.impl.client.AbstractHttpClient.java

@Override
protected final CloseableHttpResponse doExecute(final HttpHost target, final HttpRequest request,
        final HttpContext context) throws IOException, ClientProtocolException {

    Args.notNull(request, "HTTP request");
    // a null target may be acceptable, this depends on the route planner
    // a null context is acceptable, default context created below

    HttpContext execContext = null;
    RequestDirector director = null;/*from  www  .  ja v a 2s  .  co  m*/
    HttpRoutePlanner routePlanner = null;
    ConnectionBackoffStrategy connectionBackoffStrategy = null;
    BackoffManager backoffManager = null;

    // Initialize the request execution context making copies of
    // all shared objects that are potentially threading unsafe.
    synchronized (this) {

        final HttpContext defaultContext = createHttpContext();
        if (context == null) {
            execContext = defaultContext;
        } else {
            execContext = new DefaultedHttpContext(context, defaultContext);
        }
        final HttpParams params = determineParams(request);
        final RequestConfig config = HttpClientParamConfig.getRequestConfig(params);
        execContext.setAttribute(ClientContext.REQUEST_CONFIG, config);

        // Create a director for this request
        director = createClientRequestDirector(getRequestExecutor(), getConnectionManager(),
                getConnectionReuseStrategy(), getConnectionKeepAliveStrategy(), getRoutePlanner(),
                getProtocolProcessor(), getHttpRequestRetryHandler(), getRedirectStrategy(),
                getTargetAuthenticationStrategy(), getProxyAuthenticationStrategy(), getUserTokenHandler(),
                params);
        routePlanner = getRoutePlanner();
        connectionBackoffStrategy = getConnectionBackoffStrategy();
        backoffManager = getBackoffManager();
    }

    try {
        if (connectionBackoffStrategy != null && backoffManager != null) {
            final HttpHost targetForRoute = (target != null) ? target
                    : (HttpHost) determineParams(request).getParameter(ClientPNames.DEFAULT_HOST);
            final HttpRoute route = routePlanner.determineRoute(targetForRoute, request, execContext);

            final CloseableHttpResponse out;
            try {
                out = CloseableHttpResponseProxy.newProxy(director.execute(target, request, execContext));
            } catch (final RuntimeException re) {
                if (connectionBackoffStrategy.shouldBackoff(re)) {
                    backoffManager.backOff(route);
                }
                throw re;
            } catch (final Exception e) {
                if (connectionBackoffStrategy.shouldBackoff(e)) {
                    backoffManager.backOff(route);
                }
                if (e instanceof HttpException) {
                    throw (HttpException) e;
                }
                if (e instanceof IOException) {
                    throw (IOException) e;
                }
                throw new UndeclaredThrowableException(e);
            }
            if (connectionBackoffStrategy.shouldBackoff(out)) {
                backoffManager.backOff(route);
            } else {
                backoffManager.probe(route);
            }
            return out;
        } else {
            return CloseableHttpResponseProxy.newProxy(director.execute(target, request, execContext));
        }
    } catch (final HttpException httpException) {
        throw new ClientProtocolException(httpException);
    }
}

From source file:org.apache.http.impl.client.AbstractStatisticsGatheringHttpClient.java

private static HttpHost determineTarget(HttpUriRequest request) throws ClientProtocolException {
    // A null target may be acceptable if there is a default target.
    // Otherwise, the null target is detected in the director.
    HttpHost target = null;/*  www .  ja v a  2s.  c o  m*/

    URI requestURI = request.getURI();
    if (requestURI.isAbsolute()) {
        target = URIUtils.extractHost(requestURI);
        if (target == null) {
            throw new ClientProtocolException("URI does not specify a valid host name: " + requestURI);
        }
    }
    return target;
}

From source file:org.apache.http.impl.client.AbstractStatisticsGatheringHttpClient.java

public final HttpResponse execute(HttpHost target, HttpRequest request, HttpContext context)
        throws IOException, ClientProtocolException {

    if (request == null) {
        throw new IllegalArgumentException("Request must not be null.");
    }/*from  ww  w .ja v a2s  .  c  o  m*/
    // a null target may be acceptable, this depends on the route planner
    // a null context is acceptable, default context created below

    HttpContext execContext = null;
    RequestDirector director = null;

    // Initialize the request execution context making copies of
    // all shared objects that are potentially threading unsafe.
    synchronized (this) {

        HttpContext defaultContext = createHttpContext();
        if (context == null) {
            execContext = defaultContext;
        } else {
            execContext = new DefaultedHttpContext(context, defaultContext);
        }

        // Create a director for this request
        director = createClientRequestDirector(getRequestExecutor(), getConnectionManager(),
                getConnectionReuseStrategy(), getConnectionKeepAliveStrategy(), getRoutePlanner(),
                getProtocolProcessor(), getHttpRequestRetryHandler(), getRedirectStrategy(),
                getTargetAuthenticationHandler(), getProxyAuthenticationHandler(), getUserTokenHandler(),
                determineParams(request));
    }

    try {
        return director.execute(target, request, execContext);
    } catch (HttpException httpException) {
        throw new ClientProtocolException(httpException);
    }
}

From source file:org.apache.http.impl.client.cache.CachingHttpAsyncClient.java

private void revalidateCacheEntry(final BasicFuture<HttpResponse> future, final HttpHost target,
        final HttpRequestWrapper request, final HttpCacheContext clientContext, final HttpCacheEntry entry,
        final Date now) throws ClientProtocolException {

    try {/*  w  w  w . j  a v  a2 s. c  o  m*/
        if (this.asynchAsyncRevalidator != null && !staleResponseNotAllowed(request, entry, now)
                && this.validityPolicy.mayReturnStaleWhileRevalidating(entry, now)) {
            this.log.debug("Serving stale with asynchronous revalidation");
            final HttpResponse resp = this.responseGenerator.generateResponse(request, entry);
            resp.addHeader(HeaderConstants.WARNING, "110 localhost \"Response is stale\"");

            this.asynchAsyncRevalidator.revalidateCacheEntry(target, request, clientContext, entry);

            future.completed(resp);
            return;
        }

        final ChainedFutureCallback<HttpResponse> chainedFutureCallback = new ChainedFutureCallback<HttpResponse>(
                future) {

            @Override
            public void failed(final Exception ex) {
                if (ex instanceof IOException) {
                    super.completed(handleRevalidationFailure(request, clientContext, entry, now));
                } else {
                    super.failed(ex);
                }
            }

        };

        final BasicFuture<HttpResponse> compositeFuture = new BasicFuture<HttpResponse>(chainedFutureCallback);
        revalidateCacheEntry(compositeFuture, target, request, clientContext, entry);
    } catch (final ProtocolException e) {
        throw new ClientProtocolException(e);
    }
}

From source file:org.apache.http.impl.client.cache.CachingHttpClient.java

private HttpResponse revalidateCacheEntry(HttpHost target, HttpRequest request, HttpContext context,
        HttpCacheEntry entry, Date now) throws ClientProtocolException {
    log.debug("Revalidating the cache entry");

    try {/*from  w ww.j a  v a  2 s  .  c  o m*/
        if (asynchRevalidator != null && !staleResponseNotAllowed(request, entry, now)
                && validityPolicy.mayReturnStaleWhileRevalidating(entry, now)) {
            final HttpResponse resp = responseGenerator.generateResponse(entry);
            resp.addHeader(HeaderConstants.WARNING, "110 localhost \"Response is stale\"");

            asynchRevalidator.revalidateCacheEntry(target, request, context, entry);

            return resp;
        }
        return revalidateCacheEntry(target, request, context, entry);
    } catch (IOException ioex) {
        return handleRevalidationFailure(request, context, entry, now);
    } catch (ProtocolException e) {
        throw new ClientProtocolException(e);
    }
}