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);
}
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");
}
}
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);
}
}
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);
}
}
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);
}
}
}
Aggregations