List of usage examples for org.apache.http.entity BasicHttpEntity setContentLength
public void setContentLength(long j)
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// w w w.j av a 2 s . c o m */ 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.passthru.SourceResponse.java
/** * Starts the response by writing the headers * @param conn connection//from w w w.ja v a2s .c om * @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); }/*from ww w .ja v a2 s . com*/ 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//w w w .ja v a2s. 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(); } } } }
From source file:org.jenkinsci.plugins.skytap.ConnectToVPNTunnelStep.java
private String connectVPNToConfiguration(String confId, String networkId, String vpnId) { // build url//from w w w .ja v a 2s .com String reqUrl = this.buildConnectRequestURL(confId, networkId, vpnId); // create request HttpPut hp = SkytapUtils.buildHttpPutRequest(reqUrl, this.authCredentials); // add content to request - vpn identifier BasicHttpEntity he = new BasicHttpEntity(); he.setContentEncoding("gzip"); he.setContentType("application/json"); // json string for connected attribute String jsonString = "{\"connected\" :true}"; InputStream stream; try { stream = new ByteArrayInputStream(jsonString.getBytes("UTF-8")); Integer len = jsonString.getBytes("UTF-8").length; long llen = len.longValue(); he.setContent(stream); he.setContentLength(llen); } catch (UnsupportedEncodingException e) { JenkinsLogger.error("Error encoding json string for connected attribute: " + e.getMessage()); } hp.setEntity(he); String response = ""; try { response = SkytapUtils.executeHttpRequest(hp); } catch (SkytapException e) { JenkinsLogger.error("Skytap Exception: " + e.getMessage()); } return response; }
From source file:org.jenkinsci.plugins.skytap.ConnectToVPNTunnelStep.java
private String attachVPNToConfiguration(String confId, String networkId, String vpnId) { // build url//w w w. j a v a 2s .c o m String requestUrl = this.buildRequestURL(confId, networkId); // create request HttpPost hp = SkytapUtils.buildHttpPostRequest(requestUrl, this.authCredentials); // add content to request - vpn identifier BasicHttpEntity he = new BasicHttpEntity(); he.setContentEncoding("gzip"); he.setContentType("application/json"); // json string for vpn id String jsonString = "{\"id\":\"" + vpnId + "\"}"; InputStream stream; try { stream = new ByteArrayInputStream(jsonString.getBytes("UTF-8")); Integer len = jsonString.getBytes("UTF-8").length; long llen = len.longValue(); he.setContent(stream); he.setContentLength(llen); } catch (UnsupportedEncodingException e) { JenkinsLogger.error("Error encoding json string for vpn id: " + e.getMessage()); } hp.setEntity(he); JenkinsLogger.log("HTTP POST request: " + hp.toString()); // execute request String httpRespBody = ""; try { httpRespBody = SkytapUtils.executeHttpRequest(hp); } catch (SkytapException e) { JenkinsLogger.error("Skytap Exception: " + e.getMessage()); } // return response return httpRespBody; }
From source file:ste.web.http.api.ApiHandler.java
/** * Note that we expect response to have a body entity set (@see HttpEntiry) * //from w ww.jav a 2 s . c o m * @param request * @param response * @param context * * @throws HttpException * @throws IOException */ @Override public void handle(HttpRequest request, HttpResponse response, HttpContext context) throws HttpException, IOException { RRequest rr = null; File actionScript = null, applicationScript = null; try { rr = new RRequest(reduce(request.getRequestLine())); if (log.isLoggable(Level.FINE)) { log.fine(String.format("serving %s", rr.getPath())); } applicationScript = new File(apiroot, getApplicationScript(rr)); actionScript = new File(apiroot, getActionScript(rr)); if (log.isLoggable(Level.FINE)) { log.fine(String.format("application script path: %s", applicationScript.getAbsolutePath())); log.fine(String.format("action script path: %s", actionScript.getAbsolutePath())); } Interpreter bsh = new Interpreter(); BeanShellUtils.setup(bsh, request, response, (HttpSessionContext) context); bsh.set(VAR_SOURCE, actionScript.getAbsolutePath()); bsh.set(VAR_RREQUEST, rr); if (applicationScript.exists()) { bsh.eval(BeanShellUtils.getScript(applicationScript)); } bsh.eval(BeanShellUtils.getScript(actionScript)); Object body = bsh.get(rr.getHandler()); AbstractHttpEntity e = (AbstractHttpEntity) response.getEntity(); if (e.getContentType() == null) { e.setContentType("application/json"); } if (body != null) { if (body instanceof File) { File f = (File) body; e = new FileEntity(f); response.setEntity(e); String mimeType = MimeUtils.getInstance().getMimeType(f); e.setContentType( MimeUtils.MIME_UNKNOWN.equals(mimeType) ? "application/octet-stream" : mimeType); } else { String bodyString = String.valueOf(body); byte[] buf = bodyString.getBytes(); ByteArrayInputStream is = new ByteArrayInputStream(buf); BasicHttpEntity basicEntity = (BasicHttpEntity) e; basicEntity.setContent(is); basicEntity.setContentLength(buf.length); if (e.getContentType() == null) { e.setContentType("application/json"); } } } BeanShellUtils.cleanup(bsh, request); BeanShellUtils.setVariablesAttributes(bsh, context); } catch (FileNotFoundException e) { response.setStatusLine(HttpVersion.HTTP_1_1, HttpStatus.SC_NOT_FOUND, "Script " + actionScript + " not found."); } catch (EvalError x) { String msg = x.getMessage(); if (log.isLoggable(Level.SEVERE)) { log.severe(String.format("error evaluating: %s: %s", actionScript, msg)); log.throwing(getClass().getName(), "handleError", x); } // // We shall not expose to the client any details of a server error // throw new HttpException("server erorr processing the resource - see server log for details", x); } catch (URISyntaxException x) { response.setStatusLine(HttpVersion.HTTP_1_1, HttpStatus.SC_BAD_REQUEST, StringEscapeUtils.escapeHtml4(x.getMessage())); } catch (Exception x) { response.setStatusLine(HttpVersion.HTTP_1_1, HttpStatus.SC_INTERNAL_SERVER_ERROR, StringEscapeUtils.escapeHtml4(x.getMessage())); } }