use of org.glassfish.jersey.client.ClientResponse in project dropwizard by dropwizard.
the class DropwizardApacheConnectorTest method multiple_headers_with_the_same_name_are_processed_successfully.
@Test
public void multiple_headers_with_the_same_name_are_processed_successfully() throws Exception {
final CloseableHttpClient client = mock(CloseableHttpClient.class);
final DropwizardApacheConnector dropwizardApacheConnector = new DropwizardApacheConnector(client, null, false);
final Header[] apacheHeaders = { new BasicHeader("Set-Cookie", "test1"), new BasicHeader("Set-Cookie", "test2") };
final CloseableHttpResponse apacheResponse = mock(CloseableHttpResponse.class);
when(apacheResponse.getStatusLine()).thenReturn(new BasicStatusLine(new ProtocolVersion("HTTP", 1, 1), 200, "OK"));
when(apacheResponse.getAllHeaders()).thenReturn(apacheHeaders);
when(client.execute(Mockito.any())).thenReturn(apacheResponse);
final ClientRequest jerseyRequest = mock(ClientRequest.class);
when(jerseyRequest.getUri()).thenReturn(URI.create("http://localhost"));
when(jerseyRequest.getMethod()).thenReturn("GET");
when(jerseyRequest.getHeaders()).thenReturn(new MultivaluedHashMap<>());
final ClientResponse jerseyResponse = dropwizardApacheConnector.apply(jerseyRequest);
assertThat(jerseyResponse.getStatus()).isEqualTo(apacheResponse.getStatusLine().getStatusCode());
}
use of org.glassfish.jersey.client.ClientResponse in project dropwizard by dropwizard.
the class DropwizardApacheConnector method apply.
/**
* {@inheritDoc}
*/
@Override
public ClientResponse apply(ClientRequest jerseyRequest) {
try {
final HttpUriRequest apacheRequest = buildApacheRequest(jerseyRequest);
final CloseableHttpResponse apacheResponse = client.execute(apacheRequest);
final StatusLine statusLine = apacheResponse.getStatusLine();
final Response.StatusType status = Statuses.from(statusLine.getStatusCode(), firstNonNull(statusLine.getReasonPhrase(), ""));
final ClientResponse jerseyResponse = new ClientResponse(status, jerseyRequest);
for (Header header : apacheResponse.getAllHeaders()) {
final List<String> headerValues = jerseyResponse.getHeaders().get(header.getName());
if (headerValues == null) {
jerseyResponse.getHeaders().put(header.getName(), Lists.newArrayList(header.getValue()));
} else {
headerValues.add(header.getValue());
}
}
final HttpEntity httpEntity = apacheResponse.getEntity();
jerseyResponse.setEntityStream(httpEntity != null ? httpEntity.getContent() : new ByteArrayInputStream(new byte[0]));
return jerseyResponse;
} catch (Exception e) {
throw new ProcessingException(e);
}
}
use of org.glassfish.jersey.client.ClientResponse in project jersey by jersey.
the class HttpUrlConnector method _apply.
private ClientResponse _apply(final ClientRequest request) throws IOException {
final HttpURLConnection uc;
uc = this.connectionFactory.getConnection(request.getUri().toURL());
uc.setDoInput(true);
final String httpMethod = request.getMethod();
if (request.resolveProperty(HttpUrlConnectorProvider.SET_METHOD_WORKAROUND, setMethodWorkaround)) {
setRequestMethodViaJreBugWorkaround(uc, httpMethod);
} else {
uc.setRequestMethod(httpMethod);
}
uc.setInstanceFollowRedirects(request.resolveProperty(ClientProperties.FOLLOW_REDIRECTS, true));
uc.setConnectTimeout(request.resolveProperty(ClientProperties.CONNECT_TIMEOUT, uc.getConnectTimeout()));
uc.setReadTimeout(request.resolveProperty(ClientProperties.READ_TIMEOUT, uc.getReadTimeout()));
secureConnection(request.getClient(), uc);
final Object entity = request.getEntity();
if (entity != null) {
RequestEntityProcessing entityProcessing = request.resolveProperty(ClientProperties.REQUEST_ENTITY_PROCESSING, RequestEntityProcessing.class);
if (entityProcessing == null || entityProcessing != RequestEntityProcessing.BUFFERED) {
final long length = request.getLengthLong();
if (fixLengthStreaming && length > 0) {
// uc.setFixedLengthStreamingMode(long) was introduced in JDK 1.7 and Jersey client supports 1.6+
if ("1.6".equals(Runtime.class.getPackage().getSpecificationVersion())) {
uc.setFixedLengthStreamingMode(request.getLength());
} else {
uc.setFixedLengthStreamingMode(length);
}
} else if (entityProcessing == RequestEntityProcessing.CHUNKED) {
uc.setChunkedStreamingMode(chunkSize);
}
}
uc.setDoOutput(true);
if ("GET".equalsIgnoreCase(httpMethod)) {
final Logger logger = Logger.getLogger(HttpUrlConnector.class.getName());
if (logger.isLoggable(Level.INFO)) {
logger.log(Level.INFO, LocalizationMessages.HTTPURLCONNECTION_REPLACES_GET_WITH_ENTITY());
}
}
request.setStreamProvider(contentLength -> {
setOutboundHeaders(request.getStringHeaders(), uc);
return uc.getOutputStream();
});
request.writeEntity();
} else {
setOutboundHeaders(request.getStringHeaders(), uc);
}
final int code = uc.getResponseCode();
final String reasonPhrase = uc.getResponseMessage();
final Response.StatusType status = reasonPhrase == null ? Statuses.from(code) : Statuses.from(code, reasonPhrase);
final URI resolvedRequestUri;
try {
resolvedRequestUri = uc.getURL().toURI();
} catch (URISyntaxException e) {
throw new ProcessingException(e);
}
ClientResponse responseContext = new ClientResponse(status, request, resolvedRequestUri);
responseContext.headers(uc.getHeaderFields().entrySet().stream().filter(stringListEntry -> stringListEntry.getKey() != null).collect(Collectors.toMap(Map.Entry::getKey, Map.Entry::getValue)));
responseContext.setEntityStream(getInputStream(uc));
return responseContext;
}
use of org.glassfish.jersey.client.ClientResponse in project jersey by jersey.
the class EncodingFilterTest method testClosingClientResponseStreamRetrievedByResponseOnError.
/**
* Reproducer for JERSEY-2028.
*
* @see #testClosingClientResponseStreamRetrievedByValueOnError
*/
@Test
public void testClosingClientResponseStreamRetrievedByResponseOnError() {
final TestInputStream responseStream = new TestInputStream();
Client client = ClientBuilder.newClient(new ClientConfig().connectorProvider(new TestConnector() {
@Override
public ClientResponse apply(ClientRequest requestContext) throws ProcessingException {
final ClientResponse responseContext = new ClientResponse(Response.Status.OK, requestContext);
responseContext.header(CONTENT_ENCODING, "gzip");
responseContext.setEntityStream(responseStream);
return responseContext;
}
}).register(new EncodingFeature(GZipEncoder.class, DeflateEncoder.class)));
final Response response = client.target(UriBuilder.fromUri("/").build()).request().get();
assertEquals(Response.Status.OK.getStatusCode(), response.getStatus());
assertEquals("gzip", response.getHeaderString(CONTENT_ENCODING));
try {
response.readEntity(String.class);
fail("Exception caused by invalid gzip stream expected.");
} catch (ProcessingException ex) {
assertTrue("Response input stream not closed when exception is thrown.", responseStream.isClosed);
}
}
use of org.glassfish.jersey.client.ClientResponse in project jersey by jersey.
the class InMemoryConnector method apply.
@Override
public Future<?> apply(final ClientRequest request, final AsyncConnectorCallback callback) {
CompletableFuture<ClientResponse> future = new CompletableFuture<>();
try {
ClientResponse response = apply(request);
callback.response(response);
future.complete(response);
} catch (ProcessingException ex) {
future.completeExceptionally(ex);
} catch (Throwable t) {
callback.failure(t);
future.completeExceptionally(t);
}
return future;
}
Aggregations