Example usage for org.apache.http.client HttpResponseException getStatusCode

List of usage examples for org.apache.http.client HttpResponseException getStatusCode

Introduction

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

Prototype

public int getStatusCode() 

Source Link

Usage

From source file:cn.hi321.browser.weave.client.WeaveException.java

public static boolean isAuthFailure(HttpResponseException e) {
    int statusCode = e.getStatusCode();
    if (WeaveConstants.UNAUTHORIZED_HTTP_STATUS_CODE == statusCode)
        return true;
    return false;
}

From source file:com.github.horrorho.inflatabledonkey.cloud.auth.Authenticator.java

public static Auth authenticate(HttpClient httpClient, String id, String password) throws IOException {
    logger.trace("<< authenticate() < id: {} password: {}", id, password);

    AuthenticationRequestFactory authenticationRequestFactory = AuthenticationRequestFactory.instance();
    PropertyListResponseHandler<NSDictionary> nsDictionaryResponseHandler = PropertyListResponseHandler
            .nsDictionaryResponseHandler();

    try {/*from   www. j a  v  a 2  s. c  om*/
        HttpUriRequest request = authenticationRequestFactory.apply(id, password);
        NSDictionary authentication = httpClient.execute(request, nsDictionaryResponseHandler);
        logger.debug("-- authenticate() - authentication: {}", authentication.toASCIIPropertyList());

        NSDictionary appleAccountInfo = PLists.getAs(authentication, "appleAccountInfo", NSDictionary.class);
        String dsPrsID = PLists.getAs(appleAccountInfo, "dsPrsID", NSNumber.class).toString();

        NSDictionary tokens = PLists.getAs(authentication, "tokens", NSDictionary.class);
        String mmeAuthToken = PLists.getAs(tokens, "mmeAuthToken", NSString.class).getContent();

        logger.debug("-- authenticate() -  dsPrsID: {}", dsPrsID);
        logger.debug("-- authenticate() -  mmeAuthToken: {}", mmeAuthToken);

        Auth auth = new Auth(dsPrsID, mmeAuthToken);

        logger.trace(">> authenticate() > auth: {}", auth);
        return auth;

    } catch (HttpResponseException ex) {
        int statusCode = ex.getStatusCode();

        if (statusCode == 401) {
            throw new HttpResponseException(statusCode, "Bad appleId/ password or not an iCloud account?");
        }

        if (statusCode == 409) {
            throw new HttpResponseException(statusCode,
                    "Two-step enabled or partial iCloud account activation?");
        }

        throw ex;
    }
}

From source file:io.openkit.OKHTTPClient.java

public static boolean isErrorCodeInFourHundreds(Throwable e) {
    if (e instanceof HttpResponseException) {
        HttpResponseException responseException = (HttpResponseException) e;
        int statusCode = responseException.getStatusCode();

        return (statusCode >= 400 && statusCode < 500);
    } else {/*  w w  w.  j  a v  a 2  s  .c  o  m*/
        return false;
    }
}

From source file:io.openkit.user.OKUserUtilities.java

public static void checkIfErrorIsUnsubscribedUserError(Throwable e) {
    if (e == null) {
        return;//from  ww w . j  a  va  2 s. c  om
    }

    if (e instanceof HttpResponseException) {
        HttpResponseException responseException = (HttpResponseException) e;
        if (responseException.getStatusCode() == OKHTTPClient.UNSUBSCRIBED_USER_ERROR_CODE) {
            // Logout current user if we get an unsubscribed user error
            OKLog.v("Unsubscribed user, log out the user, error is: " + e);
            OKManager.INSTANCE.logoutCurrentUserWithoutClearingFB();
        }
    }
}

From source file:org.eclipse.lyo.testsuite.server.trsutils.FetchUtil.java

/**
 * Fetches a resource. In case of success, this method
 * returns an instance of the {@link Model}. 
 * //  w  ww .  j a va  2s  .c om
 * @param uri
 *            resource uri to fetch
 * @param httpClient
 *            client used to fetch the resource
 * @param httpContext
 *            http context to use for the call
 * @param acceptType 
 *            value to use in the accept header
 * @throws InterruptedException
 *             if the thread is interrupted
 * @throws FetchException
 *             if an error occurs while fetching the resource.
 * @throws IOException
 *             if an error occurs while updating the retryable error
 *             information into the error handler
 */
public static Model fetchResource(String uri, HttpClient httpClient, HttpContext httpContext, String acceptType)
        throws InterruptedException, FetchException {
    if (uri == null)
        throw new IllegalArgumentException(Messages.getServerString("fetch.util.uri.null")); //$NON-NLS-1$
    if (httpClient == null)
        throw new IllegalArgumentException(Messages.getServerString("fetch.util.httpclient.null")); //$NON-NLS-1$

    Model model = null;

    try {
        new URL(uri); // Make sure URL is valid

        HttpGet get = new HttpGet(uri);

        get.setHeader(HttpConstants.ACCEPT, acceptType);

        // Caches must revalidate with origin server. This is to prevent a cache
        // from serving stale data. We may still get a cached response if the
        // origin server responds to the revalidation with a 304.
        // See Unspecified end-to-end revalidation:
        // http://www.w3.org/Protocols/rfc2616/rfc2616-sec14.html#sec14.9.4
        get.addHeader(HttpConstants.CACHE_CONTROL, "max-age=0"); //$NON-NLS-1$

        RDFModelResponseHandler handler = new RDFModelResponseHandler(uri);

        // Try to access the uri directly.  If this fails attempt to retry
        // using authentication.
        try {
            model = httpClient.execute(get, handler, httpContext);
        } catch (HttpResponseException e1) {
            if (e1.getStatusCode() == HttpStatus.SC_UNAUTHORIZED) {
                model = attemptAuthentication(uri, httpClient, httpContext, model, get, handler);
            }
        }
    } catch (Exception e) {
        String uriLocation = Messages.getServerString("fetch.util.uri.unidentifiable"); //$NON-NLS-1$

        if (uri != null && !uri.isEmpty()) {
            uriLocation = uri;
        }

        throw new FetchException(MessageFormat.format(Messages.getServerString("fetch.util.retrieve.error"), //$NON-NLS-1$
                uriLocation), e);
    }

    return model;
}

From source file:com.helger.peppol.httpclient.AbstractGenericSMPClient.java

/**
 * Convert the passed generic HTTP exception into a more specific exception.
 *
 * @param ex//from w  w  w .j  ava2s  .  co  m
 *        The generic exception. May not be <code>null</code>.
 * @return A new SMP specific exception, using the passed exception as the
 *         cause.
 */
@Nonnull
public static SMPClientException getConvertedException(@Nonnull final Exception ex) {
    if (ex instanceof SMPClientException)
        return (SMPClientException) ex;

    if (ex instanceof HttpResponseException) {
        final HttpResponseException hex = (HttpResponseException) ex;
        final int nHttpStatus = hex.getStatusCode();
        switch (nHttpStatus) {
        case HttpStatus.SC_BAD_REQUEST:
            return new SMPClientBadRequestException(hex);
        case HttpStatus.SC_FORBIDDEN:
            return new SMPClientUnauthorizedException(hex);
        case HttpStatus.SC_NOT_FOUND:
            return new SMPClientNotFoundException(hex);
        }
        return new SMPClientException("Error thrown with HTTP status code " + nHttpStatus, hex);
    }

    // Special case
    if (ex instanceof UnknownHostException)
        return new SMPClientNotFoundException((UnknownHostException) ex);

    // Generic version
    return new SMPClientException("Unknown error thrown by SMP server (" + ex.getMessage() + ")", ex);
}

From source file:com.helger.httpclient.HttpDebugger.java

/**
 * Call after an invocation.//  www . j a  va2  s.co  m
 *
 * @param aRequest
 *        The source request. May not be modified internally. May not be
 *        <code>null</code>.
 * @param aResponse
 *        The response object retrieved. May be anything including
 *        <code>null</code> (e.g. in case of exception).
 * @param aCaughtException
 *        The caught exception. May be <code>null</code>.
 * @since 8.8.2
 */
public static void afterRequest(@Nonnull final HttpUriRequest aRequest, @Nullable final Object aResponse,
        @Nullable final Throwable aCaughtException) {
    if (isEnabled())
        if (LOGGER.isInfoEnabled()) {
            final HttpResponseException aHex = aCaughtException instanceof HttpResponseException
                    ? (HttpResponseException) aCaughtException
                    : null;
            LOGGER.info(
                    "After HTTP call: " + aRequest.getMethod()
                            + (aResponse != null ? ". Response: " + aResponse : "")
                            + (aHex != null ? ". Status " + aHex.getStatusCode() : ""),
                    aHex != null ? null : aCaughtException);
        }
}

From source file:org.jboss.pnc.auth.keycloakutil.util.HttpUtil.java

public static void checkSuccess(String url, HeadersBodyStatus response) {
    try {//from   w w w  .  j a v  a 2 s. com
        response.checkSuccess();
    } catch (HttpResponseException e) {
        if (e.getStatusCode() == 404) {
            throw new RuntimeException("Resource not found for url: " + url, e);
        }
        throw e;
    }
}

From source file:com.helger.peppol.bdxrclient.BDXRClientReadOnly.java

/**
 * Convert the passed generic HTTP exception into a more specific exception.
 *
 * @param ex//from   w w w  .  ja  v  a2s .com
 *        The generic exception. May not be <code>null</code>.
 * @return A new SMP specific exception, using the passed exception as the
 *         cause.
 */
@Nonnull
public static SMPClientException getConvertedException(@Nonnull final Exception ex) {
    if (ex instanceof SMPClientException)
        return (SMPClientException) ex;

    if (ex instanceof HttpResponseException) {
        final HttpResponseException hex = (HttpResponseException) ex;
        final int nHttpStatus = hex.getStatusCode();
        switch (nHttpStatus) {
        case HttpStatus.SC_BAD_REQUEST:
            return new SMPClientBadRequestException(hex);
        case HttpStatus.SC_FORBIDDEN:
            return new SMPClientUnauthorizedException(hex);
        case HttpStatus.SC_NOT_FOUND:
            return new SMPClientNotFoundException(hex);
        }
        return new SMPClientException("Error thrown with HTTP status code " + nHttpStatus, hex);
    }

    // Special case
    if (ex instanceof UnknownHostException)
        return new SMPClientNotFoundException((UnknownHostException) ex);

    return new SMPClientException("Unknown error thrown by SMP server (" + ex.getMessage() + ")", ex);
}

From source file:com.unboundid.scim.sdk.SCIMEndpoint.java

/**
 * Tries to deduce the most appropriate HTTP response code from the given
 * exception. This method expects most exceptions to be one of 3 or 4
 * expected runtime exceptions that are common to Wink and the Apache Http
 * Client library./*from ww w  .ja v  a2  s. com*/
 * <p>
 * Note this method can return -1 for the special case of a
 * {@link com.unboundid.scim.sdk.ConnectException}, in which the service
 * provider could not be reached at all.
 *
 * @param t the Exception instance to analyze
 * @return the most appropriate HTTP status code
 */
static int getStatusCode(final Throwable t) {
    Throwable rootCause = t;
    if (rootCause instanceof ClientRuntimeException) {
        //Pull the underlying cause out of the ClientRuntimeException
        rootCause = StaticUtils.getRootCause(t);
    }

    if (rootCause instanceof HttpResponseException) {
        HttpResponseException hre = (HttpResponseException) rootCause;
        return hre.getStatusCode();
    } else if (rootCause instanceof HttpException) {
        if (rootCause instanceof RedirectException) {
            return 300;
        } else if (rootCause instanceof AuthenticationException) {
            return 401;
        } else if (rootCause instanceof MethodNotSupportedException) {
            return 501;
        } else if (rootCause instanceof UnsupportedHttpVersionException) {
            return 505;
        }
    } else if (rootCause instanceof IOException) {
        if (rootCause instanceof NoHttpResponseException) {
            return 503;
        } else if (rootCause instanceof ConnectionClosedException) {
            return 503;
        } else {
            return -1;
        }
    }

    if (t instanceof ClientWebException) {
        ClientWebException cwe = (ClientWebException) t;
        return cwe.getResponse().getStatusCode();
    } else if (t instanceof ClientAuthenticationException) {
        return 401;
    } else if (t instanceof ClientConfigException) {
        return 400;
    } else {
        return 500;
    }
}