private HttpRequest createHttpRequest(ClientRequest request) { Object entity = request.getEntity(); if (entity == null) { return HttpRequest.createBodyless(request.getMethod(), request.getUri()); } RequestEntityProcessing entityProcessing = request.resolveProperty( ClientProperties.REQUEST_ENTITY_PROCESSING, RequestEntityProcessing.class); HttpRequest httpRequest; if (entityProcessing != null && entityProcessing == RequestEntityProcessing.CHUNKED) { httpRequest = HttpRequest.createChunked(request.getMethod(), request.getUri(), connectorConfiguration.getChunkSize()); } else { httpRequest = HttpRequest.createBuffered(request.getMethod(), request.getUri()); } return httpRequest; }
private byte[] bufferEntity(final ClientRequest requestContext) { final ByteArrayOutputStream baos = new ByteArrayOutputStream(512); requestContext.setStreamProvider(new OutboundMessageContext.StreamProvider() { @Override public OutputStream getOutputStream(final int contentLength) throws IOException { return baos; } }); try { requestContext.writeEntity(); } catch (final IOException ioe) { throw new ProcessingException("Error buffering the entity.", ioe); } return baos.toByteArray(); }
/** * Set message encoding. * * @param encoding message encoding to be set. */ public void encoding(final String encoding) { if (encoding == null) { getHeaders().remove(HttpHeaders.CONTENT_ENCODING); } else { getHeaders().putSingle(HttpHeaders.CONTENT_ENCODING, encoding); } }
/** * {@inheritDoc} */ @Override public void writeTo(final OutputStream outputStream) throws IOException { clientRequest.setStreamProvider(contentLength -> outputStream); clientRequest.writeEntity(); }
/** * Enable a buffering of serialized entity. The buffering will be configured from runtime configuration * associated with this request. The property determining the size of the buffer * is {@link org.glassfish.jersey.CommonProperties#OUTBOUND_CONTENT_LENGTH_BUFFER}. * <p/> * The buffering functionality is by default disabled and could be enabled by calling this method. In this case * this method must be called before first bytes are written to the {@link #getEntityStream() entity stream}. * */ public void enableBuffering() { enableBuffering(getConfiguration()); }
@Override public ClientResponse apply(final ClientRequest clientRequest) throws ProcessingException { final HttpUriRequest request = getUriHttpRequest(clientRequest); final Map<String, String> clientHeadersSnapshot = writeOutBoundHeaders(clientRequest.getHeaders(), request); clientRequest.resolveProperty(ApacheClientProperties.CREDENTIALS_PROVIDER, CredentialsProvider.class); if (credentialsProvider != null) { context.setCredentialsProvider(credentialsProvider); HeaderUtils.checkHeaderChanges(clientHeadersSnapshot, clientRequest.getHeaders(), this.getClass().getName()); : Statuses.from(response.getStatusLine().getStatusCode(), response.getStatusLine().getReasonPhrase()); final ClientResponse responseContext = new ClientResponse(status, clientRequest); final List<URI> redirectLocations = context.getRedirectLocations(); if (redirectLocations != null && !redirectLocations.isEmpty()) { responseContext.setResolvedRequestUri(redirectLocations.get(redirectLocations.size() - 1)); headers.put(headerName, list); if (headers.get(HttpHeaders.CONTENT_LENGTH) == null) { headers.add(HttpHeaders.CONTENT_LENGTH, String.valueOf(entity.getContentLength())); throw new ProcessingException(e);
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.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); final long length = request.getLengthLong(); if (fixLengthStreaming && length > 0) { uc.setFixedLengthStreamingMode(request.getLength()); } else { uc.setFixedLengthStreamingMode(length); request.setStreamProvider(contentLength -> {
@Override public OutputStream getOutputStream(int contentLength) throws IOException { final MultivaluedMap<String, Object> clientHeaders = clientRequest.getHeaders(); if (contentLength != -1 && !clientHeaders.containsKey(HttpHeaders.CONTENT_LENGTH)) { containerRequest.getHeaders().putSingle(HttpHeaders.CONTENT_LENGTH, String.valueOf(contentLength)); } return clientOutput; } });
/** * Add new cache control entry to the message headers. * * @param cacheControl cache control entry to be added. */ public void cacheControl(final CacheControl cacheControl) { getHeaders().add(HttpHeaders.CACHE_CONTROL, cacheControl); }
final URI requestUri = jerseyRequest.getUri(); String host = requestUri.getHost(); int port = requestUri.getPort() != -1 ? requestUri.getPort() : "https".equals(requestUri.getScheme()) ? 443 : 80; Integer connectTimeout = ClientProperties.getValue(jerseyRequest.getConfiguration().getProperties(), ClientProperties.CONNECT_TIMEOUT, 0); if (connectTimeout > 0) { if (jerseyRequest.hasEntity()) { nettyRequest = new DefaultHttpRequest(HttpVersion.HTTP_1_1, HttpMethod.valueOf(jerseyRequest.getMethod()), requestUri.getRawPath()); } else { nettyRequest = new DefaultFullHttpRequest(HttpVersion.HTTP_1_1, HttpMethod.valueOf(jerseyRequest.getMethod()), requestUri.getRawPath()); for (final Map.Entry<String, List<String>> e : jerseyRequest.getStringHeaders().entrySet()) { nettyRequest.headers().add(e.getKey(), e.getValue()); nettyRequest.headers().add(HttpHeaderNames.HOST, jerseyRequest.getUri().getHost()); if (jerseyRequest.hasEntity()) { if (jerseyRequest.getLengthLong() == -1) { HttpUtil.setTransferEncodingChunked(nettyRequest, true); } else { nettyRequest.headers().add(HttpHeaderNames.CONTENT_LENGTH, jerseyRequest.getLengthLong()); if (jerseyRequest.hasEntity()) {
try { entityStream = writeWorkers.writeTo( getEntity(), entityType.getRawType(), entityType.getType(), getEntityAnnotations(), getMediaType(), getHeaders(), getPropertiesDelegate(), getEntityStream(), writerInterceptors); setEntityStream(entityStream); } catch (final IOException e) { commitStream(); } catch (final IOException e) { ExceptionUtils.conditionallyReThrow(e, !runtimeException, LOGGER,
/** * Build a new Apache's {@link org.apache.http.client.methods.HttpUriRequest} * from Jersey's {@link org.glassfish.jersey.client.ClientRequest} * <p> * Convert a method, URI, body, headers and override a user-agent if necessary * </p> * * @param jerseyRequest representation of an HTTP request in Jersey * @return a new {@link org.apache.http.client.methods.HttpUriRequest} */ private HttpUriRequest buildApacheRequest(ClientRequest jerseyRequest) { final RequestBuilder builder = RequestBuilder .create(jerseyRequest.getMethod()) .setUri(jerseyRequest.getUri()) .setEntity(getHttpEntity(jerseyRequest)); for (String headerName : jerseyRequest.getHeaders().keySet()) { builder.addHeader(headerName, jerseyRequest.getHeaderString(headerName)); } final Optional<RequestConfig> requestConfig = addJerseyRequestConfig(jerseyRequest); requestConfig.ifPresent(builder::setConfig); return builder.build(); }
clientRequest.getUri(), clientRequest.getMethod(), null, propertiesDelegate); containerRequest.getHeaders().putAll(clientRequest.getStringHeaders()); if (clientRequest.getEntity() != null) { clientRequest.setStreamProvider(new OutboundMessageContext.StreamProvider() { @Override public OutputStream getOutputStream(int contentLength) throws IOException { clientRequest.enableBuffering(); clientRequest.writeEntity(); } catch (IOException e) { final String msg = "Error while writing entity to the output stream."; LOGGER.log(Level.SEVERE, msg, e); throw new ProcessingException(msg, e); boolean followRedirects = ClientProperties.getValue(clientRequest.getConfiguration().getProperties(), ClientProperties.FOLLOW_REDIRECTS, true); clientRequest, inMemoryResponseWriter), new ClientRequest(clientRequest));
@Override public ClientResponse apply(final ClientRequest jerseyRequest) throws ProcessingException { final Request jettyRequest = translateRequest(jerseyRequest); final Map<String, String> clientHeadersSnapshot = writeOutBoundHeaders(jerseyRequest.getHeaders(), jettyRequest); final ContentProvider entity = getBytesProvider(jerseyRequest); if (entity != null) { jettyRequest.content(entity); } try { final ContentResponse jettyResponse = jettyRequest.send(); HeaderUtils.checkHeaderChanges(clientHeadersSnapshot, jerseyRequest.getHeaders(), JettyConnector.this.getClass().getName()); final javax.ws.rs.core.Response.StatusType status = jettyResponse.getReason() == null ? Statuses.from(jettyResponse.getStatus()) : Statuses.from(jettyResponse.getStatus(), jettyResponse.getReason()); final ClientResponse jerseyResponse = new ClientResponse(status, jerseyRequest); processResponseHeaders(jettyResponse.getHeaders(), jerseyResponse); try { jerseyResponse.setEntityStream(new HttpClientResponseInputStream(jettyResponse)); } catch (final IOException e) { LOGGER.log(Level.SEVERE, null, e); } return jerseyResponse; } catch (final Exception e) { throw new ProcessingException(e); } }
private ContentProvider getBytesProvider(final ClientRequest clientRequest) { final Object entity = clientRequest.getEntity(); if (entity == null) { return null; } final ByteArrayOutputStream outputStream = new ByteArrayOutputStream(); clientRequest.setStreamProvider(new OutboundMessageContext.StreamProvider() { @Override public OutputStream getOutputStream(final int contentLength) throws IOException { return outputStream; } }); try { clientRequest.writeEntity(); } catch (final IOException e) { throw new ProcessingException("Failed to write request entity.", e); } return new BytesContentProvider(outputStream.toByteArray()); }
@Override public Invocation.Builder acceptEncoding(final String... encodings) { requestContext.getHeaders().addAll(HttpHeaders.ACCEPT_ENCODING, (Object[]) encodings); return this; }
@Override public ClientResponse apply(ClientRequest request) { RequestRunner<ClientRequest> requestRunner = new RequestRunner<>(retryComponents, headerSetter, request.getUri(), request.getMethod()); while ( requestRunner.shouldContinue() ) { URI uri = requestRunner.prepareRequest(request); request.setUri(uri); try { ClientResponse response = connector.apply(request); if ( requestRunner.isSuccessResponse(response.getStatus()) ) { return response; } } catch ( Exception e ) { if ( !requestRunner.shouldBeRetried(e) ) { throw new ProcessingException(e); } } } throw new ProcessingException("Retries expired: " + requestRunner.getOriginalUri()); }
private void validateHttpMethodAndEntity(final ClientRequest request) { boolean suppressExceptions; suppressExceptions = PropertiesHelper.isProperty( request.getConfiguration().getProperty(ClientProperties.SUPPRESS_HTTP_COMPLIANCE_VALIDATION)); final Object shcvProperty = request.getProperty(ClientProperties.SUPPRESS_HTTP_COMPLIANCE_VALIDATION); if (shcvProperty != null) { // override global configuration with request-specific suppressExceptions = PropertiesHelper.isProperty(shcvProperty); } final String method = request.getMethod(); final EntityPresence entityPresence = METHODS.get(method.toUpperCase()); if (entityPresence == EntityPresence.MUST_BE_NULL && request.hasEntity()) { if (suppressExceptions) { LOGGER.warning(LocalizationMessages.ERROR_HTTP_METHOD_ENTITY_NOT_NULL(method)); } else { throw new IllegalStateException(LocalizationMessages.ERROR_HTTP_METHOD_ENTITY_NOT_NULL(method)); } } else if (entityPresence == EntityPresence.MUST_BE_PRESENT && !request.hasEntity()) { if (suppressExceptions) { LOGGER.warning(LocalizationMessages.ERROR_HTTP_METHOD_ENTITY_NULL(method)); } else { throw new IllegalStateException(LocalizationMessages.ERROR_HTTP_METHOD_ENTITY_NULL(method)); } } }
private com.ning.http.client.Request translate(final ClientRequest requestContext) { final String strMethod = requestContext.getMethod(); final URI uri = requestContext.getUri(); builder.setFollowRedirects(requestContext.resolveProperty(ClientProperties.FOLLOW_REDIRECTS, true)); if (requestContext.hasEntity()) { requestContext.resolveProperty(ClientProperties.REQUEST_ENTITY_PROCESSING, RequestEntityProcessing.class); } else { final FeedableBodyGenerator bodyGenerator = new FeedableBodyGenerator(); final Integer chunkSize = requestContext.resolveProperty( ClientProperties.CHUNKED_ENCODING_SIZE, ClientProperties.DEFAULT_CHUNK_SIZE); bodyGenerator.setMaxPendingBytes(chunkSize); requestContext.setStreamProvider(new OutboundMessageContext.StreamProvider() { final GrizzlyConnectorProvider.RequestCustomizer requestCustomizer = requestContext.resolveProperty( GrizzlyConnectorProvider.REQUEST_CUSTOMIZER, GrizzlyConnectorProvider.RequestCustomizer.class);
public ClientResponse apply(final ClientRequest request) { final Request connectorRequest = translate(request); final Map<String, String> clientHeadersSnapshot = writeOutBoundHeaders(request.getHeaders(), connectorRequest); } catch (ExecutionException ex) { Throwable e = ex.getCause() == null ? ex : ex.getCause(); throw new ProcessingException(e.getMessage(), e); } catch (InterruptedException ex) { throw new ProcessingException(ex.getMessage(), ex);