List of usage examples for org.apache.http.entity BasicHttpEntity setChunked
public void setChunked(boolean z)
From source file:org.apache.axis2.transport.nhttp.ClientHandler.java
/** * Process a response received for the request sent out * @param conn the connection being processed *//* w w w .ja v a2 s. co m*/ public void responseReceived(final NHttpClientConnection conn) { HttpContext context = conn.getContext(); HttpResponse response = conn.getHttpResponse(); try { Pipe responsePipe = Pipe.open(); context.setAttribute(RESPONSE_SINK_CHANNEL, responsePipe.sink()); BasicHttpEntity entity = new BasicHttpEntity(); if (response.getStatusLine().getHttpVersion().greaterEquals(HttpVersion.HTTP_1_1)) { entity.setChunked(true); } response.setEntity(entity); context.setAttribute(HttpContext.HTTP_RESPONSE, response); workerPool.execute(new ClientWorker(cfgCtx, Channels.newInputStream(responsePipe.source()), (MessageContext) context.getAttribute(OUTGOING_MESSAGE_CONTEXT))); } catch (IOException e) { handleException("I/O Error : " + e.getMessage(), e, conn); } }
From source file:org.apache.axis2.transport.nhttp.ServerHandler.java
/** * Process a new incoming request//from w w w .j av a 2 s. c o m * @param conn the connection */ public void requestReceived(final NHttpServerConnection conn) { HttpContext context = conn.getContext(); HttpRequest request = conn.getHttpRequest(); context.setAttribute(HttpContext.HTTP_REQUEST, request); // allocate temporary buffers to process this request context.setAttribute(REQUEST_BUFFER, ByteBuffer.allocate(2048)); context.setAttribute(RESPONSE_BUFFER, ByteBuffer.allocate(2048)); try { Pipe requestPipe = Pipe.open(); // the pipe used to process the request Pipe responsePipe = Pipe.open(); // the pipe used to process the response context.setAttribute(REQUEST_SINK_CHANNEL, requestPipe.sink()); context.setAttribute(RESPONSE_SOURCE_CHANNEL, responsePipe.source()); // create the default response to this request HttpVersion httpVersion = request.getRequestLine().getHttpVersion(); HttpResponse response = responseFactory.newHttpResponse(httpVersion, HttpStatus.SC_OK, context); response.setParams(this.params); // create a basic HttpEntity using the source channel of the response pipe BasicHttpEntity entity = new BasicHttpEntity(); entity.setContent(Channels.newInputStream(responsePipe.source())); if (httpVersion.greaterEquals(HttpVersion.HTTP_1_1)) { entity.setChunked(true); } response.setEntity(entity); // hand off processing of the request to a thread off the pool workerPool.execute( new ServerWorker(cfgCtx, conn, this, request, Channels.newInputStream(requestPipe.source()), response, Channels.newOutputStream(responsePipe.sink()))); } catch (IOException e) { handleException("Error processing request received for : " + request.getRequestLine().getUri(), e, conn); } }
From source file:org.apache.nifi.remote.util.SiteToSiteRestApiClient.java
public void openConnectionForSend(final String transactionUrl, final Peer peer) throws IOException { final CommunicationsSession commSession = peer.getCommunicationsSession(); final String flowFilesPath = transactionUrl + "/flow-files"; final HttpPost post = createPost(flowFilesPath); // Set uri so that it'll be used as transit uri. ((HttpCommunicationsSession) peer.getCommunicationsSession()).setDataTransferUrl(post.getURI().toString()); post.setHeader("Content-Type", "application/octet-stream"); post.setHeader("Accept", "text/plain"); post.setHeader(HttpHeaders.PROTOCOL_VERSION, String.valueOf(transportProtocolVersionNegotiator.getVersion())); setHandshakeProperties(post);/*w w w. j av a 2s . co m*/ final CountDownLatch initConnectionLatch = new CountDownLatch(1); final URI requestUri = post.getURI(); final PipedOutputStream outputStream = new PipedOutputStream(); final PipedInputStream inputStream = new PipedInputStream(outputStream, DATA_PACKET_CHANNEL_READ_BUFFER_SIZE); final ReadableByteChannel dataPacketChannel = Channels.newChannel(inputStream); final HttpAsyncRequestProducer asyncRequestProducer = new HttpAsyncRequestProducer() { private final ByteBuffer buffer = ByteBuffer.allocate(DATA_PACKET_CHANNEL_READ_BUFFER_SIZE); private int totalRead = 0; private int totalProduced = 0; private boolean requestHasBeenReset = false; @Override public HttpHost getTarget() { return URIUtils.extractHost(requestUri); } @Override public HttpRequest generateRequest() throws IOException, HttpException { // Pass the output stream so that Site-to-Site client thread can send // data packet through this connection. logger.debug("sending data to {} has started...", flowFilesPath); ((HttpOutput) commSession.getOutput()).setOutputStream(outputStream); initConnectionLatch.countDown(); final BasicHttpEntity entity = new BasicHttpEntity(); entity.setChunked(true); entity.setContentType("application/octet-stream"); post.setEntity(entity); return post; } private final AtomicBoolean bufferHasRemainingData = new AtomicBoolean(false); /** * If the proxy server requires authentication, the same POST request has to be sent again. * The first request will result 407, then the next one will be sent with auth headers and actual data. * This method produces a content only when it's need to be sent, to avoid producing the flow-file contents twice. * Whether we need to wait auth is determined heuristically by the previous POST request which creates transaction. * See {@link SiteToSiteRestApiClient#initiateTransactionForSend(HttpPost)} for further detail. */ @Override public void produceContent(final ContentEncoder encoder, final IOControl ioControl) throws IOException { if (shouldCheckProxyAuth() && proxyAuthRequiresResend.get() && !requestHasBeenReset) { logger.debug("Need authentication with proxy server. Postpone producing content."); encoder.complete(); return; } if (bufferHasRemainingData.get()) { // If there's remaining buffer last time, send it first. writeBuffer(encoder); if (bufferHasRemainingData.get()) { return; } } int read; // This read() blocks until data becomes available, // or corresponding outputStream is closed. if ((read = dataPacketChannel.read(buffer)) > -1) { logger.trace("Read {} bytes from dataPacketChannel. {}", read, flowFilesPath); totalRead += read; buffer.flip(); writeBuffer(encoder); } else { final long totalWritten = commSession.getOutput().getBytesWritten(); logger.debug( "sending data to {} has reached to its end. produced {} bytes by reading {} bytes from channel. {} bytes written in this transaction.", flowFilesPath, totalProduced, totalRead, totalWritten); if (totalRead != totalWritten || totalProduced != totalWritten) { final String msg = "Sending data to %s has reached to its end, but produced : read : wrote byte sizes (%d : %d : %d) were not equal. Something went wrong."; throw new RuntimeException( String.format(msg, flowFilesPath, totalProduced, totalRead, totalWritten)); } transferDataLatch.countDown(); encoder.complete(); dataPacketChannel.close(); } } private void writeBuffer(ContentEncoder encoder) throws IOException { while (buffer.hasRemaining()) { final int written = encoder.write(buffer); logger.trace("written {} bytes to encoder.", written); if (written == 0) { logger.trace("Buffer still has remaining. {}", buffer); bufferHasRemainingData.set(true); return; } totalProduced += written; } bufferHasRemainingData.set(false); buffer.clear(); } @Override public void requestCompleted(final HttpContext context) { logger.debug("Sending data to {} completed.", flowFilesPath); debugProxyAuthState(context); } @Override public void failed(final Exception ex) { final String msg = String.format("Failed to send data to %s due to %s", flowFilesPath, ex.toString()); logger.error(msg, ex); eventReporter.reportEvent(Severity.WARNING, EVENT_CATEGORY, msg); } @Override public boolean isRepeatable() { // In order to pass authentication, request has to be repeatable. return true; } @Override public void resetRequest() throws IOException { logger.debug("Sending data request to {} has been reset...", flowFilesPath); requestHasBeenReset = true; } @Override public void close() throws IOException { logger.debug("Closing sending data request to {}", flowFilesPath); closeSilently(outputStream); closeSilently(dataPacketChannel); stopExtendingTtl(); } }; postResult = getHttpAsyncClient().execute(asyncRequestProducer, new BasicAsyncResponseConsumer(), null); try { // Need to wait the post request actually started so that we can write to its output stream. if (!initConnectionLatch.await(connectTimeoutMillis, TimeUnit.MILLISECONDS)) { throw new IOException("Awaiting initConnectionLatch has been timeout."); } // Started. transferDataLatch = new CountDownLatch(1); startExtendingTtl(transactionUrl, dataPacketChannel, null); } catch (final InterruptedException e) { throw new IOException("Awaiting initConnectionLatch has been interrupted.", e); } }
From source file:org.apache.synapse.transport.nhttp.HttpCoreNIOSender.java
/** * Send the passed in response message, asynchronously * @param msgContext the message context to be sent * @throws AxisFault on error/*from w w w. j a va 2 s .com*/ */ private void sendAsyncResponse(MessageContext msgContext) throws AxisFault { int contentLength = extractContentLength(msgContext); // remove unwanted HTTP headers (if any from the current message) removeUnwantedHeaders(msgContext); Map transportHeaders = (Map) msgContext.getProperty(MessageContext.TRANSPORT_HEADERS); ServerWorker worker = (ServerWorker) msgContext.getProperty(Constants.OUT_TRANSPORT_INFO); HttpResponse response = worker.getResponse(); OMOutputFormat format = NhttpUtil.getOMOutputFormat(msgContext); MessageFormatter messageFormatter = MessageFormatterDecoratorFactory .createMessageFormatterDecorator(msgContext); Boolean noEntityBody = (Boolean) msgContext.getProperty(NhttpConstants.NO_ENTITY_BODY); if (noEntityBody == null || Boolean.FALSE == noEntityBody) { response.setHeader(HTTP.CONTENT_TYPE, messageFormatter.getContentType(msgContext, format, msgContext.getSoapAction())); } else if (Boolean.TRUE == noEntityBody) { ((BasicHttpEntity) response.getEntity()).setChunked(false); ((BasicHttpEntity) response.getEntity()).setContentLength(0); // Since HTTP HEAD request doesn't contain message body content length of the is set to be 0. To handle // content length 0 while serving head method, content length of the backend response is set as the content // as synapse cannot calculate content length without providing message body. if (transportHeaders.get(NhttpConstants.HTTP_REQUEST_METHOD) != null && NhttpConstants.HTTP_HEAD.equals(transportHeaders.get(NhttpConstants.HTTP_REQUEST_METHOD)) && transportHeaders.get(NhttpConstants.ORIGINAL_CONTENT_LEN) != null) { ((BasicHttpEntity) response.getEntity()).setContentLength( Long.parseLong(String.valueOf(transportHeaders.get(NhttpConstants.ORIGINAL_CONTENT_LEN)))); transportHeaders.remove(NhttpConstants.ORIGINAL_CONTENT_LEN); transportHeaders.remove(NhttpConstants.HTTP_REQUEST_METHOD); } } response.setStatusCode(determineHttpStatusCode(msgContext, response)); //Override the Standard Reason Phrase if (msgContext.getProperty(NhttpConstants.HTTP_REASON_PHRASE) != null && !msgContext.getProperty(NhttpConstants.HTTP_REASON_PHRASE).equals("")) { response.setReasonPhrase(msgContext.getProperty(NhttpConstants.HTTP_REASON_PHRASE).toString()); } // set any transport headers if (transportHeaders != null && !transportHeaders.values().isEmpty()) { Iterator iter = transportHeaders.keySet().iterator(); while (iter.hasNext()) { Object header = iter.next(); Object value = transportHeaders.get(header); if (value != null && header instanceof String && value instanceof String) { response.addHeader((String) header, (String) value); String excessProp = NhttpConstants.EXCESS_TRANSPORT_HEADERS; Map map = (Map) msgContext.getProperty(excessProp); if (map != null && map.get(header) != null) { log.debug("Number of excess values for " + header + " header is : " + ((Collection) (map.get(header))).size()); for (Iterator iterator = map.keySet().iterator(); iterator.hasNext();) { String key = (String) iterator.next(); for (String excessVal : (Collection<String>) map.get(key)) { if (header.equals(key)) { response.addHeader((String) header, (String) excessVal); } } } } } } } boolean forceContentLength = msgContext.isPropertyTrue(NhttpConstants.FORCE_HTTP_CONTENT_LENGTH); boolean forceContentLengthCopy = msgContext .isPropertyTrue(NhttpConstants.COPY_CONTENT_LENGTH_FROM_INCOMING); BasicHttpEntity entity = (BasicHttpEntity) response.getEntity(); MetricsCollector lstMetrics = worker.getServiceHandler().getMetrics(); try { if (forceContentLength) { entity.setChunked(false); if (forceContentLengthCopy && contentLength > 0) { entity.setContentLength(contentLength); } else { setStreamAsTempData(entity, messageFormatter, msgContext, format); } } worker.getServiceHandler().commitResponse(worker.getConn(), response); lstMetrics.reportResponseCode(response.getStatusLine().getStatusCode()); OutputStream out = worker.getOutputStream(); /* * if this is a dummy message to handle http 202 case with non-blocking IO * write an empty byte array as body */ if (msgContext.isPropertyTrue(NhttpConstants.SC_ACCEPTED) || Boolean.TRUE == noEntityBody) { out.write(new byte[0]); } else { if (forceContentLength) { if (forceContentLengthCopy && contentLength > 0) { messageFormatter.writeTo(msgContext, format, out, false); } else { writeMessageFromTempData(out, msgContext); } } else { messageFormatter.writeTo(msgContext, format, out, false); } } out.close(); if (lstMetrics != null) { lstMetrics.incrementMessagesSent(); } } catch (ProtocolException e) { log.error(e + " (Synapse may be trying to send an exact response more than once )"); } catch (HttpException e) { if (lstMetrics != null) { lstMetrics.incrementFaultsSending(); } handleException("Unexpected HTTP protocol error sending response to : " + worker.getRemoteAddress(), e); } catch (ConnectionClosedException e) { if (lstMetrics != null) { lstMetrics.incrementFaultsSending(); } log.warn("Connection closed by client : " + worker.getRemoteAddress()); } catch (IllegalStateException e) { if (lstMetrics != null) { lstMetrics.incrementFaultsSending(); } log.warn("Connection closed by client : " + worker.getRemoteAddress()); } catch (IOException e) { if (lstMetrics != null) { lstMetrics.incrementFaultsSending(); } handleException("IO Error sending response message to : " + worker.getRemoteAddress(), e); } catch (Exception e) { if (lstMetrics != null) { lstMetrics.incrementFaultsSending(); } handleException("General Error sending response message to : " + worker.getRemoteAddress(), e); } InputStream is = worker.getIs(); if (is != null) { try { is.close(); } catch (IOException ignore) { } } }
From source file:org.apache.synapse.transport.nhttp.ServerHandler.java
/** * Process a new incoming request//from www . ja va2s .co m * @param conn the connection */ public void requestReceived(final NHttpServerConnection conn) { HttpContext context = conn.getContext(); context.setAttribute(NhttpConstants.REQ_ARRIVAL_TIME, System.currentTimeMillis()); context.setAttribute(NhttpConstants.REQ_FROM_CLIENT_READ_START_TIME, System.currentTimeMillis()); HttpRequest request = conn.getHttpRequest(); context.setAttribute(ExecutionContext.HTTP_REQUEST, request); context.setAttribute(NhttpConstants.MESSAGE_IN_FLIGHT, "true"); // prepare to collect debug information conn.getContext().setAttribute(ServerHandler.SERVER_CONNECTION_DEBUG, new ServerConnectionDebug(conn)); NHttpConfiguration cfg = NHttpConfiguration.getInstance(); try { InputStream is; // Only create an input buffer and ContentInputStream if the request has content if (request instanceof HttpEntityEnclosingRequest) { // Mark request as not yet fully read, to detect timeouts from harmless keepalive deaths conn.getContext().setAttribute(NhttpConstants.REQUEST_READ, Boolean.FALSE); ContentInputBuffer inputBuffer = new SharedInputBuffer(cfg.getBufferSize(), conn, allocator); context.setAttribute(REQUEST_SINK_BUFFER, inputBuffer); is = new ContentInputStream(inputBuffer); } else { is = null; conn.getContext().removeAttribute(NhttpConstants.REQUEST_READ); } ContentOutputBuffer outputBuffer = new SharedOutputBuffer(cfg.getBufferSize(), conn, allocator); context.setAttribute(RESPONSE_SOURCE_BUFFER, outputBuffer); OutputStream os = new ContentOutputStream(outputBuffer); // create the default response to this request ProtocolVersion httpVersion = request.getRequestLine().getProtocolVersion(); HttpResponse response = responseFactory.newHttpResponse(httpVersion, HttpStatus.SC_OK, context); // create a basic HttpEntity using the source channel of the response pipe BasicHttpEntity entity = new BasicHttpEntity(); if (httpVersion.greaterEquals(HttpVersion.HTTP_1_1)) { entity.setChunked(true); } response.setEntity(entity); if (metrics != null) { metrics.incrementMessagesReceived(); } // hand off processing of the request to a thread off the pool ServerWorker worker = new ServerWorker(cfgCtx, scheme.getName(), metrics, conn, this, request, is, response, os, listenerContext.isRestDispatching(), listenerContext.getHttpGetRequestProcessor()); if (workerPool != null) { workerPool.execute(worker); } else if (executor != null) { Map<String, String> headers = new HashMap<String, String>(); for (Header header : request.getAllHeaders()) { headers.put(header.getName(), header.getValue()); } EvaluatorContext evaluatorContext = new EvaluatorContext(request.getRequestLine().getUri(), headers); int priority = parser.parse(evaluatorContext); executor.execute(worker, priority); } // See if the client expects a 100-Continue Header expect = request.getFirstHeader(HTTP.EXPECT_DIRECTIVE); if (expect != null && HTTP.EXPECT_CONTINUE.equalsIgnoreCase(expect.getValue())) { HttpResponse ack = new BasicHttpResponse(request.getProtocolVersion(), HttpStatus.SC_CONTINUE, "Continue"); conn.submitResponse(ack); if (log.isDebugEnabled()) { log.debug(conn + ": Expect :100 Continue hit, sending ack back to the server"); } return; } } catch (Exception e) { if (metrics != null) { metrics.incrementFaultsReceiving(); } handleException("Error processing request received for : " + request.getRequestLine().getUri(), e, conn); } }
From source file:org.apache.synapse.transport.passthru.ServerWorker.java
/** * Get Uri of underlying SourceRequest and calculate service prefix and add to message context * create response buffers for HTTP GET, DELETE, OPTION and HEAD methods * @param msgContext Axis2MessageContext of the request * @param method HTTP Method of the request *//* www . ja v a 2s .c o m*/ public void processHttpRequestUri(MessageContext msgContext, String method) { String servicePrefixIndex = "://"; ConfigurationContext cfgCtx = sourceConfiguration.getConfigurationContext(); msgContext.setProperty(Constants.Configuration.HTTP_METHOD, request.getMethod()); //String uri = request.getUri(); String oriUri = request.getUri(); String restUrlPostfix = NhttpUtil.getRestUrlPostfix(oriUri, cfgCtx.getServicePath()); String servicePrefix = oriUri.substring(0, oriUri.indexOf(restUrlPostfix)); if (servicePrefix.indexOf(servicePrefixIndex) == -1) { HttpInetConnection inetConn = (HttpInetConnection) request.getConnection(); InetAddress localAddr = inetConn.getLocalAddress(); if (localAddr != null) { servicePrefix = sourceConfiguration.getScheme().getName() + servicePrefixIndex + localAddr.getHostAddress() + ":" + inetConn.getLocalPort() + servicePrefix; } } msgContext.setProperty(PassThroughConstants.SERVICE_PREFIX, servicePrefix); msgContext.setTo(new EndpointReference(restUrlPostfix)); msgContext.setProperty(PassThroughConstants.REST_URL_POSTFIX, restUrlPostfix); if (HttpMethod.GET.equals(method) || HttpMethod.DELETE.equals(method) || HttpMethod.HEAD.equals(method) || "OPTIONS".equals(method)) { HttpResponse response = sourceConfiguration.getResponseFactory().newHttpResponse(request.getVersion(), HttpStatus.SC_OK, request.getConnection().getContext()); // create a basic HttpEntity using the source channel of the response pipe BasicHttpEntity entity = new BasicHttpEntity(); if (request.getVersion().greaterEquals(HttpVersion.HTTP_1_1)) { entity.setChunked(true); } response.setEntity(entity); httpGetRequestProcessor.process(request.getRequest(), response, msgContext, request.getConnection(), os, isRestDispatching); } }
From source file:org.apache.synapse.transport.passthru.SourceResponse.java
/** * Starts the response by writing the headers * @param conn connection//from w ww. j a va 2s . co m * @throws java.io.IOException if an error occurs * @throws org.apache.http.HttpException if an error occurs */ public void start(NHttpServerConnection conn) throws IOException, HttpException { // create the response response = sourceConfiguration.getResponseFactory().newHttpResponse(request.getVersion(), this.status, request.getConnection().getContext()); if (statusLine != null) { response.setStatusLine(version, status, statusLine); } else { response.setStatusCode(status); } BasicHttpEntity entity = null; if (canResponseHaveBody(request.getRequest(), response)) { entity = new BasicHttpEntity(); int contentLength = -1; String contentLengthHeader = null; if (headers.get(HTTP.CONTENT_LEN) != null && headers.get(HTTP.CONTENT_LEN).size() > 0) { contentLengthHeader = headers.get(HTTP.CONTENT_LEN).first(); } if (contentLengthHeader != null) { contentLength = Integer.parseInt(contentLengthHeader); headers.remove(HTTP.CONTENT_LEN); } if (contentLength != -1) { entity.setChunked(false); entity.setContentLength(contentLength); } else { entity.setChunked(true); } } response.setEntity(entity); // set any transport headers Set<Map.Entry<String, TreeSet<String>>> entries = headers.entrySet(); for (Map.Entry<String, TreeSet<String>> entry : entries) { if (entry.getKey() != null) { Iterator<String> i = entry.getValue().iterator(); while (i.hasNext()) { response.addHeader(entry.getKey(), i.next()); } } } response.setParams(new DefaultedHttpParams(response.getParams(), sourceConfiguration.getHttpParams())); SourceContext.updateState(conn, ProtocolState.RESPONSE_HEAD); // Pre-process HTTP response conn.getContext().setAttribute(ExecutionContext.HTTP_CONNECTION, conn); conn.getContext().setAttribute(ExecutionContext.HTTP_RESPONSE, response); conn.getContext().setAttribute(ExecutionContext.HTTP_REQUEST, SourceContext.getRequest(conn).getRequest()); sourceConfiguration.getHttpProcessor().process(response, conn.getContext()); conn.submitResponse(response); // Handle non entity body responses if (entity == null) { hasEntity = false; // Reset connection state sourceConfiguration.getSourceConnections().releaseConnection(conn); // Make ready to deal with a new request conn.requestInput(); } }
From source file:org.apache.synapse.transport.passthru.TargetRequest.java
public void start(NHttpClientConnection conn) throws IOException, HttpException { if (pipe != null) { TargetContext.get(conn).setWriter(pipe); }/*w ww . ja va2s . c om*/ String path = fullUrl || (route.getProxyHost() != null && !route.isTunnelled()) ? url.toString() : url.getPath() + (url.getQuery() != null ? "?" + url.getQuery() : ""); long contentLength = -1; String contentLengthHeader = null; if (headers.get(HTTP.CONTENT_LEN) != null && headers.get(HTTP.CONTENT_LEN).size() > 0) { contentLengthHeader = headers.get(HTTP.CONTENT_LEN).first(); } if (contentLengthHeader != null) { contentLength = Integer.parseInt(contentLengthHeader); headers.remove(HTTP.CONTENT_LEN); } MessageContext requestMsgCtx = TargetContext.get(conn).getRequestMsgCtx(); if (requestMsgCtx.getProperty(PassThroughConstants.PASSTROUGH_MESSAGE_LENGTH) != null) { contentLength = (Long) requestMsgCtx.getProperty(PassThroughConstants.PASSTROUGH_MESSAGE_LENGTH); } //fix for POST_TO_URI if (requestMsgCtx.isPropertyTrue(NhttpConstants.POST_TO_URI)) { path = url.toString(); } //fix GET request empty body if ((("GET").equals(requestMsgCtx.getProperty(Constants.Configuration.HTTP_METHOD))) || (("DELETE").equals(requestMsgCtx.getProperty(Constants.Configuration.HTTP_METHOD)))) { hasEntityBody = false; MessageFormatter formatter = MessageProcessorSelector.getMessageFormatter(requestMsgCtx); OMOutputFormat format = PassThroughTransportUtils.getOMOutputFormat(requestMsgCtx); if (formatter != null && format != null) { URL _url = formatter.getTargetAddress(requestMsgCtx, format, url); if (_url != null && !_url.toString().isEmpty()) { if (requestMsgCtx.getProperty(NhttpConstants.POST_TO_URI) != null && Boolean.TRUE.toString() .equals(requestMsgCtx.getProperty(NhttpConstants.POST_TO_URI))) { path = _url.toString(); } else { path = _url.getPath() + ((_url.getQuery() != null && !_url.getQuery().isEmpty()) ? ("?" + _url.getQuery()) : ""); } } headers.remove(HTTP.CONTENT_TYPE); } } Object o = requestMsgCtx.getProperty(MessageContext.TRANSPORT_HEADERS); if (o != null && o instanceof TreeMap) { Map _headers = (Map) o; String trpContentType = (String) _headers.get(HTTP.CONTENT_TYPE); if (trpContentType != null && !trpContentType.equals("")) { if (!trpContentType.contains(PassThroughConstants.CONTENT_TYPE_MULTIPART_RELATED)) { addHeader(HTTP.CONTENT_TYPE, trpContentType); } } } if (hasEntityBody) { request = new BasicHttpEntityEnclosingRequest(method, path, version != null ? version : HttpVersion.HTTP_1_1); BasicHttpEntity entity = new BasicHttpEntity(); boolean forceContentLength = requestMsgCtx.isPropertyTrue(NhttpConstants.FORCE_HTTP_CONTENT_LENGTH); boolean forceContentLengthCopy = requestMsgCtx .isPropertyTrue(PassThroughConstants.COPY_CONTENT_LENGTH_FROM_INCOMING); if (forceContentLength) { entity.setChunked(false); if (forceContentLengthCopy && contentLength > 0) { entity.setContentLength(contentLength); } } else { if (contentLength != -1) { entity.setChunked(false); entity.setContentLength(contentLength); } else { entity.setChunked(chunk); } } ((BasicHttpEntityEnclosingRequest) request).setEntity(entity); } else { request = new BasicHttpRequest(method, path, version != null ? version : HttpVersion.HTTP_1_1); } Set<Map.Entry<String, TreeSet<String>>> entries = headers.entrySet(); for (Map.Entry<String, TreeSet<String>> entry : entries) { if (entry.getKey() != null) { Iterator<String> i = entry.getValue().iterator(); while (i.hasNext()) { request.addHeader(entry.getKey(), i.next()); } } } //setup wsa action.. if (request != null) { String soapAction = requestMsgCtx.getSoapAction(); if (soapAction == null) { soapAction = requestMsgCtx.getWSAAction(); } if (soapAction == null) { requestMsgCtx.getAxisOperation().getInputAction(); } if (requestMsgCtx.isSOAP11() && soapAction != null && soapAction.length() > 0) { Header existingHeader = request.getFirstHeader(HTTPConstants.HEADER_SOAP_ACTION); if (existingHeader != null) { request.removeHeader(existingHeader); } MessageFormatter messageFormatter = MessageFormatterDecoratorFactory .createMessageFormatterDecorator(requestMsgCtx); request.setHeader(HTTPConstants.HEADER_SOAP_ACTION, messageFormatter.formatSOAPAction(requestMsgCtx, null, soapAction)); //request.setHeader(HTTPConstants.USER_AGENT,"Synapse-PT-HttpComponents-NIO"); } } request.setParams(new DefaultedHttpParams(request.getParams(), targetConfiguration.getHttpParams())); //Chucking is not performed for request has "http 1.0" and "GET" http method if (!((request.getProtocolVersion().equals(HttpVersion.HTTP_1_0)) || (("GET").equals(requestMsgCtx.getProperty(Constants.Configuration.HTTP_METHOD))) || (("DELETE").equals(requestMsgCtx.getProperty(Constants.Configuration.HTTP_METHOD))))) { this.processChunking(conn, requestMsgCtx); } if (!keepAlive) { request.setHeader(HTTP.CONN_DIRECTIVE, HTTP.CONN_CLOSE); } // Pre-process HTTP request conn.getContext().setAttribute(ExecutionContext.HTTP_CONNECTION, conn); conn.getContext().setAttribute(ExecutionContext.HTTP_TARGET_HOST, new HttpHost(url.getHost(), port)); conn.getContext().setAttribute(ExecutionContext.HTTP_REQUEST, request); // start the request targetConfiguration.getHttpProcessor().process(request, conn.getContext()); if (targetConfiguration.getProxyAuthenticator() != null && route.getProxyHost() != null && !route.isTunnelled()) { targetConfiguration.getProxyAuthenticator().authenticatePreemptively(request, conn.getContext()); } conn.submitRequest(request); if (hasEntityBody) { TargetContext.updateState(conn, ProtocolState.REQUEST_HEAD); } else { TargetContext.updateState(conn, ProtocolState.REQUEST_DONE); } }
From source file:org.apache.synapse.transport.passthru.TargetRequest.java
/** * Handles the chuking messages in Passthough context, create a temporary buffer and calculate the message * size before writing to the external buffer, which is required the context of handling DISABLED chunking * messages/*from w ww . j a v a 2 s . c o m*/ * * @param conn * @param requestMsgCtx * @throws IOException * @throws AxisFault */ private void processChunking(NHttpClientConnection conn, MessageContext requestMsgCtx) throws IOException, AxisFault { String disableChunking = (String) requestMsgCtx.getProperty(PassThroughConstants.DISABLE_CHUNKING); String forceHttp10 = (String) requestMsgCtx.getProperty(PassThroughConstants.FORCE_HTTP_1_0); if ("true".equals(disableChunking) || "true".equals(forceHttp10)) { if (requestMsgCtx.getEnvelope().getBody().getFirstElement() == null) { BasicHttpEntity entity = (BasicHttpEntity) ((BasicHttpEntityEnclosingRequest) request).getEntity(); try { RelayUtils.buildMessage(requestMsgCtx); this.hasEntityBody = true; Pipe pipe = (Pipe) requestMsgCtx.getProperty(PassThroughConstants.PASS_THROUGH_PIPE); if (pipe != null) { pipe.attachConsumer(conn); this.connect(pipe); if (Boolean.TRUE .equals(requestMsgCtx.getProperty(PassThroughConstants.MESSAGE_BUILDER_INVOKED))) { ByteArrayOutputStream out = new ByteArrayOutputStream(); MessageFormatter formatter = MessageProcessorSelector .getMessageFormatter(requestMsgCtx); OMOutputFormat format = PassThroughTransportUtils.getOMOutputFormat(requestMsgCtx); formatter.writeTo(requestMsgCtx, format, out, false); OutputStream _out = pipe.getOutputStream(); IOUtils.write(out.toByteArray(), _out); entity.setContentLength(new Long(out.toByteArray().length)); entity.setChunked(false); } } // pipe.setSerializationComplete(true); } catch (XMLStreamException e) { e.printStackTrace(); } } } }