List of usage examples for org.apache.http.client ClientProtocolException ClientProtocolException
public ClientProtocolException(final Throwable cause)
From source file:ss.udapi.sdk.services.HttpServices.java
protected String retrieveBody(ServiceRequest request, String relation, String name, String entity) throws Exception { if (request == null) throw new IllegalArgumentException("request object cannot be null"); if (name == null) throw new IllegalArgumentException("name cannot be null"); CloseableHttpClient httpClient = HttpClients.custom().setKeepAliveStrategy(requestTimeout).build(); Exception lastraisedexception = null; // Double check we do have an actual usable service RestItem serviceDetails = getRestItems(request, name); if (serviceDetails == null) { logger.error("No details found for: " + relation + " on " + name); return null; }// w ww . ja va2 s . c o m // The retrieve that service's end-point RestLink link = getLink(serviceDetails, relation); if (link == null) { logger.error("No links found for: " + relation + " on " + name); return null; } String responseBody = ""; try { // Prepare the HTTP request depending on whether it's an echo // (POST), then send the request. if (relation.equals("http://api.sportingsolutions.com/rels/stream/batchecho")) { HttpPost httpPost = new HttpPost(link.getHref()); httpPost.setHeader("X-Auth-Token", request.getAuthToken()); httpPost.setHeader("Content-Type", "application/json"); if (compressionEnabled == true) { httpPost.setHeader("Accept-Encoding", "gzip"); } HttpEntity myEntity = new StringEntity(entity); httpPost.setEntity(myEntity); CloseableHttpResponse httpResponse = httpClient.execute(httpPost); if (httpResponse.getStatusLine().getStatusCode() != 202) { throw new ClientProtocolException("Unexpected response status for echo request: " + httpResponse.getStatusLine().getStatusCode()); } HttpEntity responseEntity = httpResponse.getEntity(); if (responseEntity != null) { responseBody = new String(EntityUtils.toByteArray(responseEntity)); } // Or anything else (GET), then send the request. } else { HttpGet httpGet = new HttpGet(link.getHref()); httpGet.setHeader("X-Auth-Token", request.getAuthToken()); if (compressionEnabled == true) { httpGet.setHeader("Accept-Encoding", "gzip"); } logger.debug("Sending request for relation:[" + relation + "] name:[" + name + "] to href:[" + link.getHref() + "]"); ResponseHandler<String> responseHandler = getResponseHandler(200); responseBody = httpClient.execute(httpGet, responseHandler); } } catch (ClientProtocolException protEx) { logger.error("Invalid Client Protocol: " + protEx.getMessage() + " while processing : " + name); lastraisedexception = protEx; } catch (IOException ioEx) { logger.error("Communication error: " + ioEx.getMessage() + " while processing : " + name); lastraisedexception = ioEx; } finally { try { httpClient.close(); } catch (IOException ex) { // Can safely be ignored, either the server closed the // connection or we didn't open it so there's nothing to do } } if (lastraisedexception != null) throw lastraisedexception; // Then return the response we got from Sporting Solutions. return responseBody; }
From source file:org.commonjava.aprox.client.core.AproxClientHttp.java
public void putWithStream(final String path, final InputStream stream, final int... responseCodes) throws AproxClientException { connect();/*from ww w . j av a2 s.c o m*/ final HttpPut put = newRawPut(buildUrl(baseUrl, path)); final CloseableHttpClient client = newClient(); try { put.setEntity(new InputStreamEntity(stream)); client.execute(put, new ResponseHandler<Void>() { @Override public Void handleResponse(final HttpResponse response) throws ClientProtocolException, IOException { try { final StatusLine sl = response.getStatusLine(); if (!validResponseCode(sl.getStatusCode(), responseCodes)) { throw new ClientProtocolException( String.format("Error in response from: %s. Status was: %d %s (%s)", path, sl.getStatusCode(), sl.getReasonPhrase(), sl.getProtocolVersion())); } return null; } finally { cleanupResources(put, response, client); } } }); } catch (final IOException e) { throw new AproxClientException("AProx request failed: %s", e, e.getMessage()); } }
From source file:org.dataconservancy.ui.services.EZIDServiceImplTest.java
/** * Tests exceptional conditions when calling the delete method, including bad return code and unexpect return format * @throws ClientProtocolException// w w w . j av a 2 s . c o m * @throws IOException */ @Test public void testDeleteExceptions() throws ClientProtocolException, IOException { HttpResponse mockResponse = new BasicHttpResponse(new HttpVersion(1, 1), 200, "ok"); StringEntity entity = new StringEntity("success: namespace:id"); mockResponse.setEntity(entity); HttpClient mockHttpClient = mock(HttpClient.class); when(mockHttpClient.execute(any(HttpPost.class))) .thenThrow(new ClientProtocolException("Expected exception")); ezidService.setHttpClient(mockHttpClient); boolean caughtException = false; try { ezidService.deleteID("www.test.com/id/namespace:id"); } catch (EZIDServiceException e) { caughtException = true; assertEquals("org.apache.http.client.ClientProtocolException: Expected exception", e.getMessage()); } assertTrue(caughtException); mockResponse = new BasicHttpResponse(new HttpVersion(1, 1), 404, "not found"); mockResponse.setEntity(entity); mockHttpClient = mock(HttpClient.class); when(mockHttpClient.execute(any(HttpPost.class))).thenReturn(mockResponse); ezidService.setHttpClient(mockHttpClient); caughtException = false; try { ezidService.deleteID("www.test.com/id/namespace:id"); } catch (EZIDServiceException e) { caughtException = true; assertTrue(e.getMessage().contains("not found")); } assertTrue(caughtException); mockResponse = new BasicHttpResponse(new HttpVersion(1, 1), 200, "ok"); entity = new StringEntity("namespace:id"); mockResponse.setEntity(entity); mockHttpClient = mock(HttpClient.class); when(mockHttpClient.execute(any(HttpPost.class))).thenReturn(mockResponse); ezidService.setHttpClient(mockHttpClient); caughtException = false; try { ezidService.deleteID("www.test.com/id/namespace:id"); } catch (EZIDServiceException e) { caughtException = true; assertEquals("Unexpected response: namespace:id", e.getMessage()); } assertTrue(caughtException); }
From source file:org.commonjava.propulsor.client.http.ClientHttpSupport.java
public void putWithStream(final String path, final InputStream stream, final int... responseCodes) throws ClientHttpException { connect();//from ww w . j a v a 2s. c o m final HttpPut put = newRawPut(buildUrl(baseUrl, path)); final CloseableHttpClient client = newClient(); CloseableHttpResponse response = null; try { put.setEntity(new InputStreamEntity(stream)); response = client.execute(put); final StatusLine sl = response.getStatusLine(); if (!validResponseCode(sl.getStatusCode(), responseCodes)) { throw new ClientProtocolException(new ClientHttpException(sl.getStatusCode(), "Error in response from: %s.\n%s", path, new ClientHttpResponseErrorDetails(response))); } } catch (final ClientProtocolException e) { final Throwable cause = e.getCause(); if (cause != null && (cause instanceof ClientHttpException)) { throw (ClientHttpException) cause; } throw new ClientHttpException("Client request failed: %s", e, e.getMessage()); } catch (final IOException e) { throw new ClientHttpException("Client request failed: %s", e, e.getMessage()); } finally { cleanupResources(put, response, client); } }
From source file:es.upv.grycap.coreutils.fiber.http.HttpDataFetcher.java
/** * Allows fetching and saving a bunch of objects to the specified directory from a server that uses a REST or REST-like API * where each object is retrieved from the URL formed appending the object's identifier to the path of the the base URL, and * optionally from a server that uses a parameter to identify the objects. Supports additional configuration options to name * the fetched objects.// www. ja va 2 s . c o m * @param baseUrl - base URL from where the objects will be fetched * @param queryParam - if defined, a query parameter will be appended to the base URL with the identifier of the request * @param ids - a list with the identifiers of the all requests that will be attempted * @param prefix - optionally prepend this prefix to the filenames of the saved files * @param suffix - optionally append this suffix to the filenames of the saved files * @param outdir - directory where the files will be stored * @return A {@link CompletableFuture} that allows cancellation. Once each fetch operation is completed, its status is updated * in the future with one of the possible values provided by the enumeration {@link FetchStatus}. * @throws IOException If an error occurs during the execution of the method that prevents fetching or saving the files. */ public FecthFuture fetchToDir(final URL baseUrl, final @Nullable String queryParam, final List<String> ids, final @Nullable String prefix, final @Nullable String suffix, final File outdir) throws IOException { // check mandatory parameters requireNonNull(baseUrl, "A valid URL expected"); final FecthFuture toBeCompleted = new FecthFuture( requireNonNull(ids, "A valid list of identifiers expected").stream().map(StringUtils::trimToNull) .filter(Objects::nonNull).distinct().collect(Collectors.toList())); requireNonNull(outdir, "A valid output directory expected"); checkArgument((outdir.isDirectory() && outdir.canWrite()) || outdir.mkdirs(), new StringBuilder("Cannot write to the output directory: ").append(outdir.getAbsolutePath()) .toString()); // get optional parameters final Optional<String> queryParam2 = ofNullable(trimToNull(queryParam)); final String prefix2 = ofNullable(prefix).orElse(""); final String suffix2 = ofNullable(suffix).orElse(""); try (final CloseableHttpAsyncClient asyncHttpClient = createFiberCloseableHttpAsyncClient()) { asyncHttpClient.start(); final UrlBuilder urlBuilder = getUrlBuilder(baseUrl); // an explanation is needed since this code is instrumented by Quasar and Comsat: requests are created during the first part of // this lambda expression (map), but they are not executed until the get() method is called in the second part of the expression // (forEach). Here that parallel stream is used to block and wait for the requests to complete. In case that a single stream is // used, each request will be created and executed sequentially. Therefore, the alternative to parallel stream is to separate // the lambda expression in two loops, creating the requests in the first loop and calling get() in the second one. toBeCompleted.monList.parallelStream().map(m -> { try { // create output file final File outfile = new File(outdir, new StringBuilder(prefix2).append(m.id).append(suffix2).append(".partial").toString()); checkState(outfile.createNewFile(), new StringBuilder("Cannot create the output file: ") .append(outfile.getAbsolutePath()).toString()); // create the HTTP request final HttpHost target = URIUtils.extractHost(baseUrl.toURI()); final HttpRequest request = new BasicHttpRequest("GET", urlBuilder.buildRelativeUrl(queryParam2.isPresent() ? null : m.id, queryParam2.isPresent() ? of(queryParam2.get(), m.id) : null)); final HttpAsyncRequestProducer producer = new BasicAsyncRequestProducer(target, request); // create the consumer final ZeroCopyConsumer<File> consumer = new ZeroCopyConsumer<File>(outfile) { @Override protected File process(final HttpResponse response, final File file, final ContentType contentType) throws Exception { final StatusLine status = response.getStatusLine(); if (LOGGER.isDebugEnabled()) LOGGER.debug( new StringBuilder("Got file: statusCode=").append(status.getStatusCode()) .append(", file=").append(file.getAbsolutePath()).toString()); if (status.getStatusCode() != HttpStatus.SC_OK) throw new ClientProtocolException( new StringBuilder("Object fetch failed: ").append(status).toString()); return file; } }; // prepare request m.future = asyncHttpClient.execute(producer, consumer, new FutureCallback<File>() { @Override public void cancelled() { toBeCompleted.update(m.id, FetchStatus.CANCELLED); LOGGER.info("Task cancelled"); } @Override public void completed(final File result) { try { final Path path = result.toPath(); Files.move(path, path.resolveSibling(removeEnd(result.getName(), ".partial")), REPLACE_EXISTING); toBeCompleted.update(m.id, FetchStatus.COMPLETED); } catch (IOException ex) { toBeCompleted.update(m.id, FetchStatus.FAILED); LOGGER.error("Fecth failed to move file to its final destination with error", ex); } } @Override public void failed(final Exception ex) { toBeCompleted.update(m.id, FetchStatus.FAILED); LOGGER.error("Fecth failed with error", ex); } }); } catch (Exception e) { LOGGER.error(new StringBuilder("Failed to fetch object with id: ").append(m.id).toString(), e); } return m; }).forEach(m -> { try { // submit requests and wait for completion m.future.get(); } catch (Exception ignore) { /* exceptions are handled in the callback functions */ } }); } return toBeCompleted; }
From source file:com.helger.peppol.httpclient.SMPHttpResponseHandlerSigned.java
@Override @Nonnull/*w w w .ja va 2 s. c o m*/ public T handleEntity(@Nonnull final HttpEntity aEntity) throws IOException { // Get complete response as one big byte buffer final byte[] aResponseBytes = StreamHelper.getAllBytes(aEntity.getContent()); if (ArrayHelper.isEmpty(aResponseBytes)) throw new ClientProtocolException("Could not read SMP server response content"); try { // Check the signature if (!_checkSignature(new NonBlockingByteArrayInputStream(aResponseBytes))) throw new ClientProtocolException("Signature returned from SMP server was not valid"); } catch (final Exception ex) { throw new ClientProtocolException("Error in validating signature returned from SMP server", ex); } // Finally convert to domain object final T ret = m_aMarshaller.read(aResponseBytes); if (ret == null) throw new ClientProtocolException("Malformed XML document returned from SMP server"); return ret; }
From source file:com.jaspersoft.studio.server.protocol.restv2.CASUtil.java
private static String readData(Executor exec, Request req, IProgressMonitor monitor) throws IOException { String obj = null;//from w ww. j av a 2s .c o m ConnectionManager.register(monitor, req); try { obj = exec.execute(req).handleResponse(new ResponseHandler<String>() { public String handleResponse(final HttpResponse response) throws IOException { HttpEntity entity = response.getEntity(); InputStream in = null; String res = null; try { StatusLine statusLine = response.getStatusLine(); // System.out // .println("---------------------------------------------------------------------------"); // System.out.println(response.toString()); // for (Header h : response.getAllHeaders()) { // System.out.println(h.toString()); // } switch (statusLine.getStatusCode()) { case 200: in = getContent(entity); res = IOUtils.toString(in); break; default: throw new HttpResponseException(statusLine.getStatusCode(), statusLine.getReasonPhrase()); } } finally { FileUtils.closeStream(in); } return res; } protected InputStream getContent(HttpEntity entity) throws ClientProtocolException, IOException { if (entity == null) throw new ClientProtocolException("Response contains no content"); return entity.getContent(); } }); } catch (IOException e) { e.printStackTrace(); throw e; } finally { ConnectionManager.unregister(req); } return obj; }
From source file:com.helger.peppol.smpclient.SMPHttpResponseHandlerSigned.java
@Nonnull public T handleResponse(@Nonnull final HttpResponse aHttpResponse) throws IOException { final StatusLine aStatusLine = aHttpResponse.getStatusLine(); final HttpEntity aEntity = aHttpResponse.getEntity(); if (aStatusLine.getStatusCode() >= 300) throw new HttpResponseException(aStatusLine.getStatusCode(), aStatusLine.getReasonPhrase()); if (aEntity == null) throw new ClientProtocolException("Response from SMP server contains no content"); // Get complete response as one big byte buffer final byte[] aResponseBytes = StreamHelper.getAllBytes(aEntity.getContent()); if (ArrayHelper.isEmpty(aResponseBytes)) throw new ClientProtocolException("Could not read SMP server response content"); try {/*from ww w . j av a2 s . co m*/ // Check the signature if (!_checkSignature(new NonBlockingByteArrayInputStream(aResponseBytes))) throw new ClientProtocolException("Signature returned from SMP server was not valid"); } catch (final Exception ex) { throw new ClientProtocolException("Error in validating signature returned from SMP server", ex); } // Finally convert to domain object final T ret = m_aMarshaller.read(aResponseBytes); if (ret == null) throw new ClientProtocolException("Malformed XML document returned from SMP server"); return ret; }
From source file:com.couchbase.jdbc.core.ProtocolImpl.java
@SuppressWarnings({ "unchecked", "rawtypes" }) public Cluster handleClusterResponse(CloseableHttpResponse response) throws IOException { int status = response.getStatusLine().getStatusCode(); HttpEntity entity = response.getEntity(); String string = EntityUtils.toString(entity); logger.trace("Cluster response {}", string); ObjectMapper mapper = JsonFactory.create(); // has to be an object here since we can get a 404 back which is a string Object jsonArray = mapper.fromJson(string); String message = ""; switch (status) { case 200://from w w w . ja va2s . c o m //noinspection unchecked rewriteURLs((List<Map>) jsonArray); return new Cluster((List) jsonArray, ssl); case 400: message = "Bad Request"; break; case 401: message = "Unauthorized Request credentials are missing or invalid"; break; case 403: message = "Forbidden Request: read only violation or client unauthorized to modify"; break; case 404: message = "Not found: Check the URL"; break; case 405: message = "Method not allowed: The REST method type in request is supported"; break; case 409: message = "Conflict: attempt to create a keyspace or index that already exists"; break; case 410: message = "Gone: The server is doing a graceful shutdown"; break; case 500: message = "Internal server error: unforeseen problem processing the request"; break; case 503: message = "Service Unavailable: there is an issue preventing the request from being serv serviced"; break; } throw new ClientProtocolException(message + ": " + status); }
From source file:org.commonjava.indy.client.core.IndyClientHttp.java
public void putWithStream(final String path, final InputStream stream, final int... responseCodes) throws IndyClientException { connect();//from ww w. j a va 2 s . co m final HttpPut put = newRawPut(buildUrl(baseUrl, path)); final CloseableHttpClient client = newClient(); CloseableHttpResponse response = null; try { put.setEntity(new InputStreamEntity(stream)); response = client.execute(put, newContext()); final StatusLine sl = response.getStatusLine(); if (!validResponseCode(sl.getStatusCode(), responseCodes)) { throw new ClientProtocolException(new IndyClientException(sl.getStatusCode(), "Error in response from: %s.\n%s", path, new IndyResponseErrorDetails(response))); } } catch (final ClientProtocolException e) { final Throwable cause = e.getCause(); if (cause != null && (cause instanceof IndyClientException)) { throw (IndyClientException) cause; } throw new IndyClientException("Indy request failed: %s", e, e.getMessage()); } catch (final IOException e) { throw new IndyClientException("Indy request failed: %s", e, e.getMessage()); } finally { cleanupResources(put, response, client); } }