Search in sources :

Example 1 with HttpResponseException

use of org.apache.http.client.HttpResponseException in project XobotOS by xamarin.

the class BasicResponseHandler method handleResponse.

/**
     * Returns the response body as a String if the response was successful (a
     * 2xx status code). If no response body exists, this returns null. If the
     * response was unsuccessful (>= 300 status code), throws an
     * {@link HttpResponseException}.
     */
public String handleResponse(final HttpResponse response) throws HttpResponseException, IOException {
    StatusLine statusLine = response.getStatusLine();
    if (statusLine.getStatusCode() >= 300) {
        throw new HttpResponseException(statusLine.getStatusCode(), statusLine.getReasonPhrase());
    }
    HttpEntity entity = response.getEntity();
    return entity == null ? null : EntityUtils.toString(entity);
}
Also used : StatusLine(org.apache.http.StatusLine) HttpEntity(org.apache.http.HttpEntity) HttpResponseException(org.apache.http.client.HttpResponseException)

Example 2 with HttpResponseException

use of org.apache.http.client.HttpResponseException in project uavstack by uavorg.

the class PackageDownloadAction method tryDownloadFile.

/**
 * Try to download file, if download server is handling too many requests, will retry to download file after a few
 * seconds again, the max retry count and retry-after time are set in the profile.
 */
private void tryDownloadFile(String fileName, Path destination) throws Exception {
    if (log.isTraceEnable()) {
        log.info(this, "try to download file " + fileName + " to " + destination);
    }
    DownloadResult result = DownloadResult.FAILURE;
    this.retryCount = DataConvertHelper.toInt(this.getConfigManager().getFeatureConfiguration(this.feature, "download.retry.count"), 20);
    while (retryCount-- > 0) {
        try {
            if (downloadFile(fileName, destination)) {
                result = DownloadResult.SUCCESS;
                if (log.isTraceEnable()) {
                    log.info(this, "Download file: " + fileName + " successfully");
                }
                break;
            }
        } catch (Exception ex) {
            if (ex instanceof HttpResponseException) {
                HttpResponseException hre = (HttpResponseException) ex;
                if (hre.getStatusCode() != UpgradeConstants.HTTP_CODE_TOO_MANY_REQUESTS) {
                    throw ex;
                }
                if (log.isTraceEnable()) {
                    log.info(this, "Server now is handling too many download requests, so need one more retry after " + retryAfter + " seconds");
                }
                ThreadHelper.suspend(retryAfter * 1000);
                result = DownloadResult.SERVER_BUSY;
                continue;
            } else {
                result = DownloadResult.FAILURE;
                break;
            }
        }
    }
    if (result == DownloadResult.SERVER_BUSY) {
        if (log.isTraceEnable()) {
            log.err(this, "Reached the max value of retry count, so download task was failed");
        }
        throw new Exception("Server busy");
    } else if (result == DownloadResult.FAILURE) {
        if (log.isTraceEnable()) {
            log.err(this, "Failed to download file: " + fileName);
        }
        throw new Exception("Failed to download");
    }
}
Also used : HttpResponseException(org.apache.http.client.HttpResponseException) ClientProtocolException(org.apache.http.client.ClientProtocolException) HttpResponseException(org.apache.http.client.HttpResponseException) IOException(java.io.IOException) UpgradeException(com.creditease.uav.feature.upgrade.exception.UpgradeException)

Example 3 with HttpResponseException

use of org.apache.http.client.HttpResponseException in project hale by halestudio.

the class AbstractResourceManager method create.

/**
 * @see eu.esdihumboldt.hale.io.geoserver.rest.ResourceManager#create(java.util.Map)
 */
@Override
public URL create(Map<String, String> parameters) {
    checkResourceSet();
    try {
        URI requestUri = buildRequestUri(getResourceListURL(), parameters);
        ByteArrayEntity entity = new ByteArrayEntity(resource.asByteArray());
        entity.setContentType(resource.contentType().getMimeType());
        return executor.execute(Request.Post(requestUri).body(entity)).handleResponse(new ResponseHandler<URL>() {

            /**
             * @see org.apache.http.client.ResponseHandler#handleResponse(org.apache.http.HttpResponse)
             */
            @Override
            public URL handleResponse(HttpResponse response) throws ClientProtocolException, IOException {
                StatusLine statusLine = response.getStatusLine();
                if (statusLine.getStatusCode() >= 300) {
                    throw new HttpResponseException(statusLine.getStatusCode(), statusLine.getReasonPhrase());
                }
                if (statusLine.getStatusCode() == 201) {
                    Header locationHeader = response.getFirstHeader("Location");
                    if (locationHeader != null) {
                        return new URL(locationHeader.getValue());
                    }
                }
                return null;
            }
        });
    } catch (Exception e) {
        throw new ResourceException(e);
    }
}
Also used : HttpResponse(org.apache.http.HttpResponse) HttpResponseException(org.apache.http.client.HttpResponseException) IOException(java.io.IOException) URI(java.net.URI) URL(java.net.URL) ClientProtocolException(org.apache.http.client.ClientProtocolException) URISyntaxException(java.net.URISyntaxException) MalformedURLException(java.net.MalformedURLException) HttpResponseException(org.apache.http.client.HttpResponseException) IOException(java.io.IOException) ParserConfigurationException(javax.xml.parsers.ParserConfigurationException) SAXException(org.xml.sax.SAXException) ClientProtocolException(org.apache.http.client.ClientProtocolException) StatusLine(org.apache.http.StatusLine) ByteArrayEntity(org.apache.http.entity.ByteArrayEntity) Header(org.apache.http.Header)

Example 4 with HttpResponseException

use of org.apache.http.client.HttpResponseException in project hale by halestudio.

the class InspireCodeListAdvisor method copyResource.

@Override
public void copyResource(LocatableInputSupplier<? extends InputStream> resource, final Path target, IContentType resourceType, boolean includeRemote, IOReporter reporter) throws IOException {
    URI uri = resource.getLocation();
    String uriScheme = uri.getScheme();
    if (uriScheme.equals("http")) {
        // Get the response for the given uri
        Response response = INSPIRECodeListReader.getResponse(uri);
        // Handle the fluent response
        response.handleResponse(new ResponseHandler<Boolean>() {

            @Override
            public Boolean handleResponse(HttpResponse response) throws ClientProtocolException, IOException {
                StatusLine status = response.getStatusLine();
                HttpEntity entity = response.getEntity();
                if (status.getStatusCode() >= 300) {
                    throw new HttpResponseException(status.getStatusCode(), status.getReasonPhrase());
                }
                if (entity == null) {
                    throw new ClientProtocolException();
                }
                // Copy the resource file to the target path
                Files.copy(entity.getContent(), target);
                return true;
            }
        });
    } else {
        super.copyResource(resource, target, resourceType, includeRemote, reporter);
    }
}
Also used : HttpResponse(org.apache.http.HttpResponse) Response(org.apache.http.client.fluent.Response) StatusLine(org.apache.http.StatusLine) HttpEntity(org.apache.http.HttpEntity) HttpResponse(org.apache.http.HttpResponse) HttpResponseException(org.apache.http.client.HttpResponseException) IOException(java.io.IOException) URI(java.net.URI) ClientProtocolException(org.apache.http.client.ClientProtocolException)

Example 5 with HttpResponseException

use of org.apache.http.client.HttpResponseException in project sling by apache.

the class SimpleHttpDistributionTransport method deliverPackage.

public void deliverPackage(@Nonnull ResourceResolver resourceResolver, @Nonnull DistributionPackage distributionPackage, @Nonnull DistributionTransportContext distributionContext) throws DistributionException {
    String hostAndPort = getHostAndPort(distributionEndpoint.getUri());
    DistributionPackageInfo info = distributionPackage.getInfo();
    URI packageOrigin = info.get(PACKAGE_INFO_PROPERTY_ORIGIN_URI, URI.class);
    if (packageOrigin != null && hostAndPort.equals(getHostAndPort(packageOrigin))) {
        log.debug("skipping distribution of package {} to same origin {}", distributionPackage.getId(), hostAndPort);
    } else {
        try {
            Executor executor = getExecutor(distributionContext);
            Request req = Request.Post(distributionEndpoint.getUri()).connectTimeout(httpConfiguration.getConnectTimeout()).socketTimeout(httpConfiguration.getSocketTimeout()).addHeader(HTTP.CONN_DIRECTIVE, HTTP.CONN_CLOSE).useExpectContinue();
            // add the message body digest, see https://tools.ietf.org/html/rfc3230#section-4.3.2
            if (distributionPackage instanceof AbstractDistributionPackage) {
                AbstractDistributionPackage adb = (AbstractDistributionPackage) distributionPackage;
                if (adb.getDigestAlgorithm() != null && adb.getDigestMessage() != null) {
                    req.addHeader(DIGEST_HEADER, String.format("%s=%s", adb.getDigestAlgorithm(), adb.getDigestMessage()));
                }
            }
            InputStream inputStream = null;
            try {
                inputStream = DistributionPackageUtils.createStreamWithHeader(distributionPackage);
                req = req.bodyStream(inputStream, ContentType.APPLICATION_OCTET_STREAM);
                Response response = executor.execute(req);
                // throws an error if HTTP status is >= 300
                response.returnContent();
            } finally {
                IOUtils.closeQuietly(inputStream);
            }
            log.debug("delivered packageId={}, endpoint={}", distributionPackage.getId(), distributionEndpoint.getUri());
        } catch (HttpHostConnectException e) {
            throw new RecoverableDistributionException("endpoint not available " + distributionEndpoint.getUri(), e);
        } catch (HttpResponseException e) {
            int statusCode = e.getStatusCode();
            if (statusCode == 404 || statusCode == 401) {
                throw new RecoverableDistributionException("not enough rights for " + distributionEndpoint.getUri(), e);
            }
            throw new DistributionException(e);
        } catch (Exception e) {
            throw new DistributionException(e);
        }
    }
}
Also used : DistributionPackageInfo(org.apache.sling.distribution.packaging.DistributionPackageInfo) InputStream(java.io.InputStream) Request(org.apache.http.client.fluent.Request) DistributionRequest(org.apache.sling.distribution.DistributionRequest) HttpResponseException(org.apache.http.client.HttpResponseException) URI(java.net.URI) DistributionException(org.apache.sling.distribution.common.DistributionException) HttpHostConnectException(org.apache.http.conn.HttpHostConnectException) RecoverableDistributionException(org.apache.sling.distribution.common.RecoverableDistributionException) HttpResponseException(org.apache.http.client.HttpResponseException) Response(org.apache.http.client.fluent.Response) Executor(org.apache.http.client.fluent.Executor) RecoverableDistributionException(org.apache.sling.distribution.common.RecoverableDistributionException) HttpHostConnectException(org.apache.http.conn.HttpHostConnectException) DistributionException(org.apache.sling.distribution.common.DistributionException) RecoverableDistributionException(org.apache.sling.distribution.common.RecoverableDistributionException) AbstractDistributionPackage(org.apache.sling.distribution.packaging.impl.AbstractDistributionPackage)

Aggregations

HttpResponseException (org.apache.http.client.HttpResponseException)69 IOException (java.io.IOException)29 StatusLine (org.apache.http.StatusLine)27 HttpEntity (org.apache.http.HttpEntity)22 HttpGet (org.apache.http.client.methods.HttpGet)11 HttpResponse (org.apache.http.HttpResponse)10 ClientProtocolException (org.apache.http.client.ClientProtocolException)9 BasicResponseHandler (org.apache.http.impl.client.BasicResponseHandler)9 URISyntaxException (java.net.URISyntaxException)8 ArrayList (java.util.ArrayList)8 Header (org.apache.http.Header)8 URI (java.net.URI)7 Document (org.jsoup.nodes.Document)7 Test (org.junit.Test)6 InputStream (java.io.InputStream)5 HttpClient (org.apache.http.client.HttpClient)5 Element (org.jsoup.nodes.Element)5 SubstitutionSchedule (me.vertretungsplan.objects.SubstitutionSchedule)4 HttpPost (org.apache.http.client.methods.HttpPost)4 BufferedHttpEntity (org.apache.http.entity.BufferedHttpEntity)4