List of usage examples for org.apache.http.protocol HttpContext getAttribute
Object getAttribute(String str);
From source file:org.apache.http.impl.nio.client.NHttpClientProtocolHandler.java
private HttpAsyncExchangeHandler<?> getHandler(final HttpContext context) { return (HttpAsyncExchangeHandler<?>) context .getAttribute(DefaultAsyncRequestDirector.HTTP_EXCHANGE_HANDLER); }
From source file:org.apache.http.impl.nio.conn.PoolingNHttpClientConnectionManager.java
private Lookup<SchemeIOSessionStrategy> getIOSessionFactoryRegistry(final HttpContext context) { @SuppressWarnings("unchecked") Lookup<SchemeIOSessionStrategy> reg = (Lookup<SchemeIOSessionStrategy>) context .getAttribute(IOSESSION_FACTORY_REGISTRY); if (reg == null) { reg = this.iosessionFactoryRegistry; }/*w ww. j av a 2 s . c om*/ return reg; }
From source file:org.apache.jmeter.protocol.http.sampler.HTTPHC4Impl.java
@Override protected HTTPSampleResult sample(URL url, String method, boolean areFollowingRedirect, int frameDepth) { if (log.isDebugEnabled()) { log.debug("Start : sample " + url.toString()); log.debug("method " + method + " followingRedirect " + areFollowingRedirect + " depth " + frameDepth); }/*from w w w .j a v a 2 s .c o m*/ HTTPSampleResult res = createSampleResult(url, method); HttpClient httpClient = setupClient(url, res); HttpRequestBase httpRequest = null; try { URI uri = url.toURI(); if (method.equals(HTTPConstants.POST)) { httpRequest = new HttpPost(uri); } else if (method.equals(HTTPConstants.GET)) { httpRequest = new HttpGet(uri); } else if (method.equals(HTTPConstants.PUT)) { httpRequest = new HttpPut(uri); } else if (method.equals(HTTPConstants.HEAD)) { httpRequest = new HttpHead(uri); } else if (method.equals(HTTPConstants.TRACE)) { httpRequest = new HttpTrace(uri); } else if (method.equals(HTTPConstants.OPTIONS)) { httpRequest = new HttpOptions(uri); } else if (method.equals(HTTPConstants.DELETE)) { httpRequest = new HttpDelete(uri); } else if (method.equals(HTTPConstants.PATCH)) { httpRequest = new HttpPatch(uri); } else if (HttpWebdav.isWebdavMethod(method)) { httpRequest = new HttpWebdav(method, uri); } else { throw new IllegalArgumentException("Unexpected method: '" + method + "'"); } setupRequest(url, httpRequest, res); // can throw IOException } catch (Exception e) { res.sampleStart(); res.sampleEnd(); errorResult(e, res); return res; } HttpContext localContext = new BasicHttpContext(); setupClientContextBeforeSample(localContext); res.sampleStart(); final CacheManager cacheManager = getCacheManager(); if (cacheManager != null && HTTPConstants.GET.equalsIgnoreCase(method)) { if (cacheManager.inCache(url)) { return updateSampleResultForResourceInCache(res); } } try { currentRequest = httpRequest; handleMethod(method, res, httpRequest, localContext); // store the SampleResult in LocalContext to compute connect time localContext.setAttribute(SAMPLER_RESULT_TOKEN, res); // perform the sample HttpResponse httpResponse = executeRequest(httpClient, httpRequest, localContext, url); // Needs to be done after execute to pick up all the headers final HttpRequest request = (HttpRequest) localContext.getAttribute(HttpCoreContext.HTTP_REQUEST); extractClientContextAfterSample(localContext); // We've finished with the request, so we can add the LocalAddress to it for display final InetAddress localAddr = (InetAddress) httpRequest.getParams() .getParameter(ConnRoutePNames.LOCAL_ADDRESS); if (localAddr != null) { request.addHeader(HEADER_LOCAL_ADDRESS, localAddr.toString()); } res.setRequestHeaders(getConnectionHeaders(request)); Header contentType = httpResponse.getLastHeader(HTTPConstants.HEADER_CONTENT_TYPE); if (contentType != null) { String ct = contentType.getValue(); res.setContentType(ct); res.setEncodingAndType(ct); } HttpEntity entity = httpResponse.getEntity(); if (entity != null) { res.setResponseData(readResponse(res, entity.getContent(), (int) entity.getContentLength())); } res.sampleEnd(); // Done with the sampling proper. currentRequest = null; // Now collect the results into the HTTPSampleResult: StatusLine statusLine = httpResponse.getStatusLine(); int statusCode = statusLine.getStatusCode(); res.setResponseCode(Integer.toString(statusCode)); res.setResponseMessage(statusLine.getReasonPhrase()); res.setSuccessful(isSuccessCode(statusCode)); res.setResponseHeaders(getResponseHeaders(httpResponse, localContext)); if (res.isRedirect()) { final Header headerLocation = httpResponse.getLastHeader(HTTPConstants.HEADER_LOCATION); if (headerLocation == null) { // HTTP protocol violation, but avoids NPE throw new IllegalArgumentException( "Missing location header in redirect for " + httpRequest.getRequestLine()); } String redirectLocation = headerLocation.getValue(); res.setRedirectLocation(redirectLocation); } // record some sizes to allow HTTPSampleResult.getBytes() with different options HttpConnectionMetrics metrics = (HttpConnectionMetrics) localContext.getAttribute(CONTEXT_METRICS); long headerBytes = res.getResponseHeaders().length() // condensed length (without \r) + httpResponse.getAllHeaders().length // Add \r for each header + 1 // Add \r for initial header + 2; // final \r\n before data long totalBytes = metrics.getReceivedBytesCount(); res.setHeadersSize((int) headerBytes); res.setBodySize((int) (totalBytes - headerBytes)); if (log.isDebugEnabled()) { log.debug("ResponseHeadersSize=" + res.getHeadersSize() + " Content-Length=" + res.getBodySize() + " Total=" + (res.getHeadersSize() + res.getBodySize())); } // If we redirected automatically, the URL may have changed if (getAutoRedirects()) { HttpUriRequest req = (HttpUriRequest) localContext.getAttribute(HttpCoreContext.HTTP_REQUEST); HttpHost target = (HttpHost) localContext.getAttribute(HttpCoreContext.HTTP_TARGET_HOST); URI redirectURI = req.getURI(); if (redirectURI.isAbsolute()) { res.setURL(redirectURI.toURL()); } else { res.setURL(new URL(new URL(target.toURI()), redirectURI.toString())); } } // Store any cookies received in the cookie manager: saveConnectionCookies(httpResponse, res.getURL(), getCookieManager()); // Save cache information if (cacheManager != null) { cacheManager.saveDetails(httpResponse, res); } // Follow redirects and download page resources if appropriate: res = resultProcessing(areFollowingRedirect, frameDepth, res); } catch (IOException e) { log.debug("IOException", e); if (res.getEndTime() == 0) { res.sampleEnd(); } // pick up headers if failed to execute the request if (res.getRequestHeaders() != null) { log.debug("Overwriting request old headers: " + res.getRequestHeaders()); } res.setRequestHeaders( getConnectionHeaders((HttpRequest) localContext.getAttribute(HttpCoreContext.HTTP_REQUEST))); errorResult(e, res); return res; } catch (RuntimeException e) { log.debug("RuntimeException", e); if (res.getEndTime() == 0) { res.sampleEnd(); } errorResult(e, res); return res; } finally { currentRequest = null; JMeterContextService.getContext().getSamplerContext().remove(HTTPCLIENT_TOKEN); } return res; }
From source file:org.apache.nutch.protocol.httpclient.HttpClientRedirectStrategy.java
public URI getLocationURI(final HttpRequest request, final HttpResponse response, final HttpContext context) throws ProtocolException { if (request == null) { throw new IllegalArgumentException("HTTP request may not be null"); }/* ww w . j a va 2 s.c om*/ if (response == null) { throw new IllegalArgumentException("HTTP response may not be null"); } if (context == null) { throw new IllegalArgumentException("HTTP context may not be null"); } //get the location header to find out where to redirect to Header locationHeader = response.getFirstHeader("location"); if (locationHeader == null) { // got a redirect response, but no location header throw new ProtocolException( "Received redirect response " + response.getStatusLine() + " but no location header"); } String location = locationHeader.getValue(); if (this.log.isDebugEnabled()) { this.log.debug("Redirect requested to location '" + location + "'"); } URI uri = createLocationURI(location); HttpParams params = request.getParams(); // rfc2616 demands the location value be a complete URI // Location = "Location" ":" absoluteURI try { // Drop fragment uri = URIUtils.rewriteURI(uri); if (!uri.isAbsolute()) { if (params.isParameterTrue(ClientPNames.REJECT_RELATIVE_REDIRECT)) { throw new ProtocolException("Relative redirect location '" + uri + "' not allowed"); } // Adjust location URI HttpHost target = (HttpHost) context.getAttribute(ExecutionContext.HTTP_TARGET_HOST); if (target == null) { throw new IllegalStateException("Target host not available " + "in the HTTP context"); } URI requestURI = new URI(request.getRequestLine().getUri()); URI absoluteRequestURI = URIUtils.rewriteURI(requestURI, target, true); uri = URIUtils.resolve(absoluteRequestURI, uri); } } catch (URISyntaxException ex) { throw new ProtocolException(ex.getMessage(), ex); } RedirectLocations redirectLocations = (RedirectLocations) context.getAttribute(REDIRECT_LOCATIONS); if (redirectLocations == null) { redirectLocations = new RedirectLocations(); context.setAttribute(REDIRECT_LOCATIONS, redirectLocations); } if (params.isParameterFalse(ClientPNames.ALLOW_CIRCULAR_REDIRECTS)) { if (redirectLocations.contains(uri)) { throw new CircularRedirectException("Circular redirect to '" + uri + "'"); } } redirectLocations.add(uri); return uri; }
From source file:org.apache.synapse.transport.nhttp.ClientHandler.java
public void requestReady(final NHttpClientConnection conn) throws IOException, HttpException { // The connection is ready for submission of a new request HttpContext context = conn.getContext(); ProxyTunnelHandler tunnelHandler = (ProxyTunnelHandler) context.getAttribute(TUNNEL_HANDLER); if (tunnelHandler != null && !tunnelHandler.isCompleted()) { if (!tunnelHandler.isRequested()) { HttpRequest request = tunnelHandler.generateRequest(context); if (proxyauthenticator != null) { proxyauthenticator.authenticatePreemptively(request, context); }// w w w. ja v a 2 s .c o m if (log.isDebugEnabled()) { log.debug(conn + ": Sending CONNECT request to " + tunnelHandler.getProxy()); } conn.submitRequest(request); tunnelHandler.setRequested(); } return; } Axis2HttpRequest axis2Req = (Axis2HttpRequest) context.removeAttribute(ATTACHMENT_KEY); if (axis2Req == null || axis2Req.isCompleted()) { return; } try { processConnection(conn, axis2Req); } catch (ConnectionClosedException e) { metrics.incrementFaultsSending(); handleException("I/O Error submitting request : " + e.getMessage(), e, conn); } }
From source file:org.apache.synapse.transport.nhttp.ClientHandler.java
/** * Process ready input (i.e. response from remote server) * /*from w w w.jav a 2 s . co m*/ * @param conn connection being processed * @param decoder the content decoder in use */ public void inputReady(final NHttpClientConnection conn, final ContentDecoder decoder) { HttpContext context = conn.getContext(); HttpResponse response = conn.getHttpResponse(); ContentInputBuffer inBuf = (ContentInputBuffer) context.getAttribute(RESPONSE_SINK_BUFFER); try { int bytesRead = inBuf.consumeContent(decoder); if (metrics != null && bytesRead > 0) { if (metrics.getLevel() == MetricsCollector.LEVEL_FULL) { metrics.incrementBytesReceived(getMessageContext(conn), bytesRead); } else { metrics.incrementBytesReceived(bytesRead); } } if (decoder.isCompleted()) { setServerContextAttribute(NhttpConstants.RES_ARRIVAL_TIME, System.currentTimeMillis(), conn); setServerContextAttribute(NhttpConstants.RES_FROM_BACKEND_READ_END_TIME, System.currentTimeMillis(), conn); ClientConnectionDebug ccd = (ClientConnectionDebug) conn.getContext() .getAttribute(CLIENT_CONNECTION_DEBUG); if (ccd != null) { ccd.recordResponseCompletionTime(); } if (metrics != null) { if (metrics.getLevel() == MetricsCollector.LEVEL_FULL) { MessageContext mc = getMessageContext(conn); metrics.incrementMessagesReceived(mc); metrics.notifyReceivedMessageSize(mc, conn.getMetrics().getReceivedBytesCount()); metrics.notifySentMessageSize(mc, conn.getMetrics().getSentBytesCount()); metrics.reportResponseCode(mc, response.getStatusLine().getStatusCode()); } else { metrics.incrementMessagesReceived(); metrics.notifyReceivedMessageSize(conn.getMetrics().getReceivedBytesCount()); metrics.notifySentMessageSize(conn.getMetrics().getSentBytesCount()); } } // reset metrics on connection conn.getMetrics().reset(); if (context.getAttribute(NhttpConstants.DISCARD_ON_COMPLETE) != null) { try { // this is a connection we should not re-use connpool.forget(conn); shutdownConnection(conn, false, null); context.removeAttribute(RESPONSE_SINK_BUFFER); context.removeAttribute(REQUEST_SOURCE_BUFFER); } catch (Exception ignore) { } } else if (!connStrategy.keepAlive(response, context)) { shutdownConnection(conn, false, null); context.removeAttribute(RESPONSE_SINK_BUFFER); context.removeAttribute(REQUEST_SOURCE_BUFFER); } else { connpool.release(conn); } } } catch (IOException e) { if (metrics != null) { if (metrics.getLevel() == MetricsCollector.LEVEL_FULL) { metrics.incrementFaultsReceiving(NhttpConstants.SND_IO_ERROR_RECEIVING, getMessageContext(conn)); } else { metrics.incrementFaultsReceiving(); } } handleException("I/O Error at inputReady : " + e.getMessage(), e, conn); } }
From source file:org.apache.synapse.transport.nhttp.ClientHandler.java
/** * Process a response received for the request sent out * //from www . j a va 2s .c o m * @param conn the connection being processed */ public void responseReceived(final NHttpClientConnection conn) { setServerContextAttribute(NhttpConstants.RES_FROM_BACKEND_READ_START_TIME, System.currentTimeMillis(), conn); HttpContext context = conn.getContext(); HttpResponse response = conn.getHttpResponse(); ProxyTunnelHandler tunnelHandler = (ProxyTunnelHandler) context.getAttribute(TUNNEL_HANDLER); if (tunnelHandler != null && !tunnelHandler.isCompleted()) { context.removeAttribute(TUNNEL_HANDLER); tunnelHandler.handleResponse(response, conn); if (tunnelHandler.isSuccessful()) { log.debug(conn + ": Tunnel established"); conn.resetInput(); conn.requestOutput(); return; } else { Axis2HttpRequest axis2Req = (Axis2HttpRequest) context.getAttribute(ATTACHMENT_KEY); context.setAttribute(AXIS2_HTTP_REQUEST, axis2Req); context.setAttribute(OUTGOING_MESSAGE_CONTEXT, axis2Req.getMsgContext()); ContentOutputBuffer outputBuffer = new SharedOutputBuffer(cfg.getBufferSize(), conn, allocator); axis2Req.setOutputBuffer(outputBuffer); context.setAttribute(REQUEST_SOURCE_BUFFER, outputBuffer); context.setAttribute(NhttpConstants.DISCARD_ON_COMPLETE, Boolean.TRUE); } } setServerContextAttribute(NhttpConstants.RES_HEADER_ARRIVAL_TIME, System.currentTimeMillis(), conn); if (response.getStatusLine().getStatusCode() == HttpStatus.SC_CONTINUE) { if (log.isDebugEnabled()) { log.debug(conn + ": Received a 100 Continue response"); } // according to the HTTP 1.1 specification HTTP status 100 continue implies that // the response will be followed, and the client should just ignore the 100 Continue // and wait for the response return; } ClientConnectionDebug ccd = (ClientConnectionDebug) conn.getContext().getAttribute(CLIENT_CONNECTION_DEBUG); if (ccd != null) { ccd.recordResponseStartTime(response.getStatusLine().toString()); } // Have we sent out our request fully in the first place? if not, forget about it now.. Axis2HttpRequest req = (Axis2HttpRequest) conn.getContext().getAttribute(AXIS2_HTTP_REQUEST); if (req != null) { req.setCompleted(true); if (log.isDebugEnabled()) { log.debug(conn + ": Response Received for Request : " + req); } if (!req.isSendingCompleted()) { req.getMsgContext().setProperty(NhttpConstants.ERROR_CODE, NhttpConstants.SEND_ABORT); SharedOutputBuffer outputBuffer = (SharedOutputBuffer) conn.getContext() .getAttribute(REQUEST_SOURCE_BUFFER); if (outputBuffer != null) { outputBuffer.shutdown(); } if (log.isDebugEnabled()) { log.debug(conn + ": Remote server aborted request being sent and replied : " + conn + " for request : " + conn.getContext().getAttribute(NhttpConstants.HTTP_REQ_METHOD)); } context.setAttribute(NhttpConstants.DISCARD_ON_COMPLETE, Boolean.TRUE); if (metrics != null) { metrics.incrementFaultsSending(NhttpConstants.SEND_ABORT, req.getMsgContext()); } } } switch (response.getStatusLine().getStatusCode()) { case HttpStatus.SC_ACCEPTED: { if (log.isDebugEnabled()) { log.debug(conn + ": Received a 202 Accepted response"); } // Process response body if Content-Type header is present in the response // If Content-Type header is null, We will ignore entity body Header contentType = response.getFirstHeader(HTTP.CONTENT_TYPE); if (contentType != null) { processResponse(conn, context, response); return; } // sometimes, some http clients sends an "\r\n" as the content body with a // HTTP 202 OK.. we will just get it into this temp buffer and ignore it.. ContentInputBuffer inputBuffer = new SharedInputBuffer(8, conn, allocator); context.setAttribute(RESPONSE_SINK_BUFFER, inputBuffer); // create a dummy message with an empty SOAP envelope and a property // NhttpConstants.SC_ACCEPTED set to Boolean.TRUE to indicate this is a // placeholder message for the transport to send a HTTP 202 to the // client. Should / would be ignored by any transport other than // nhttp. For example, JMS would not send a reply message for one-way // operations. MessageContext outMsgCtx = (MessageContext) context.getAttribute(OUTGOING_MESSAGE_CONTEXT); MessageReceiver mr = outMsgCtx.getAxisOperation().getMessageReceiver(); // the following check is to support the dual channel invocation. Hence the // response will be sent as a new request to the client over a different channel // client sends back a 202 Accepted response to synapse and we need to neglect that // 202 Accepted message if (!outMsgCtx.isPropertyTrue(NhttpConstants.IGNORE_SC_ACCEPTED)) { try { MessageContext responseMsgCtx = outMsgCtx.getOperationContext() .getMessageContext(WSDL2Constants.MESSAGE_LABEL_IN); if (responseMsgCtx == null || outMsgCtx.getOptions().isUseSeparateListener() || outMsgCtx.getOperationContext().isComplete()) { if (responseMsgCtx != null && responseMsgCtx.getProperty("synapse.send") == null) { return; } } else if (responseMsgCtx == null || outMsgCtx.getOptions().isUseSeparateListener()) { // Since we need to notify the SynapseCallback receiver to remove the // call backs registered we set a custom property setHeaders(context, response, outMsgCtx, responseMsgCtx); outMsgCtx.setProperty(NhttpConstants.HTTP_202_RECEIVED, "true"); mr.receive(outMsgCtx); return; } if (responseMsgCtx == null) { return; } setHeaders(context, response, outMsgCtx, responseMsgCtx); responseMsgCtx.setServerSide(true); responseMsgCtx.setDoingREST(outMsgCtx.isDoingREST()); responseMsgCtx.setProperty(MessageContext.TRANSPORT_IN, outMsgCtx.getProperty(MessageContext.TRANSPORT_IN)); responseMsgCtx.setTransportIn(outMsgCtx.getTransportIn()); responseMsgCtx.setTransportOut(outMsgCtx.getTransportOut()); responseMsgCtx.setAxisMessage( outMsgCtx.getAxisOperation().getMessage(WSDLConstants.MESSAGE_LABEL_IN_VALUE)); responseMsgCtx.setOperationContext(outMsgCtx.getOperationContext()); responseMsgCtx.setConfigurationContext(outMsgCtx.getConfigurationContext()); responseMsgCtx.setTo(null); if (!outMsgCtx.isDoingREST() && !outMsgCtx.isSOAP11()) { responseMsgCtx.setEnvelope(new SOAP12Factory().getDefaultEnvelope()); } else { responseMsgCtx.setEnvelope(new SOAP11Factory().getDefaultEnvelope()); } responseMsgCtx.setProperty(AddressingConstants.DISABLE_ADDRESSING_FOR_OUT_MESSAGES, Boolean.TRUE); responseMsgCtx.setProperty(NhttpConstants.SC_ACCEPTED, Boolean.TRUE); int statusCode = response.getStatusLine().getStatusCode(); responseMsgCtx.setProperty(NhttpConstants.HTTP_SC, statusCode); mr.receive(responseMsgCtx); } catch (org.apache.axis2.AxisFault af) { log.debug(conn + ": Unable to report back " + "202 Accepted state to the message receiver"); } } return; } case HttpStatus.SC_OK: { processResponse(conn, context, response); return; } case HttpStatus.SC_INTERNAL_SERVER_ERROR: { if (warnOnHttp500(response)) { log.warn(getErrorMessage( "Received an internal server error : " + response.getStatusLine().getReasonPhrase(), conn)); } processResponse(conn, context, response); return; } default: { if (log.isDebugEnabled()) { log.debug(conn + ": " + getErrorMessage("HTTP status code received : " + response.getStatusLine().getStatusCode() + " :: " + response.getStatusLine().getReasonPhrase(), conn)); } Header contentType = response.getFirstHeader(HTTP.CONTENT_TYPE); if (contentType != null) { if ((contentType.getValue().indexOf(SOAP11Constants.SOAP_11_CONTENT_TYPE) >= 0) || contentType.getValue().indexOf(SOAP12Constants.SOAP_12_CONTENT_TYPE) >= 0) { if (log.isDebugEnabled()) { log.debug(conn + ": Received an unexpected response with a SOAP payload"); } } else if (contentType.getValue().indexOf("html") == -1) { if (log.isDebugEnabled()) { log.debug(conn + ": Received an unexpected response with a POX/REST payload"); } } else { log.warn(getErrorMessage( "Received an unexpected response - " + "of content type : " + contentType.getValue() + " and status code : " + response.getStatusLine().getStatusCode() + " with reason : " + response.getStatusLine().getReasonPhrase(), conn)); } } else { if (log.isDebugEnabled()) { log.debug(conn + ": " + getErrorMessage( "Received a response - " + "without a content type with status code : " + response.getStatusLine().getStatusCode() + " and reason : " + response.getStatusLine().getReasonPhrase(), conn)); } } processResponse(conn, context, response); } } }
From source file:org.apache.synapse.transport.nhttp.ClientHandler.java
/** * Shutdown the connection ignoring any IO errors during the process * * @param conn the connection to be shutdown * @param isError whether shutdown is due to an error * @param errorMsg error message if shutdown happens on error *///from w w w . ja v a 2s .c o m private void shutdownConnection(final NHttpClientConnection conn, boolean isError, String errorMsg) { if (conn instanceof HttpInetConnection) { HttpInetConnection inetConnection = (HttpInetConnection) conn; if (log.isWarnEnabled() && (isError || log.isDebugEnabled())) { String msg = "Connection from local address : " + inetConnection.getLocalAddress() + ":" + inetConnection.getLocalPort() + " to remote address : " + inetConnection.getRemoteAddress() + ":" + inetConnection.getRemotePort() + " is closed!" + (errorMsg != null ? " - On error : " + errorMsg : ""); if (isError) { log.warn(msg); } else { log.debug(msg); } } if (countConnections) { removeConnectionRecord(inetConnection); } } HttpContext context = conn.getContext(); SharedOutputBuffer outputBuffer = (SharedOutputBuffer) context.getAttribute(REQUEST_SOURCE_BUFFER); if (outputBuffer != null) { outputBuffer.close(); } SharedInputBuffer inputBuffer = (SharedInputBuffer) context.getAttribute(RESPONSE_SINK_BUFFER); if (inputBuffer != null) { inputBuffer.close(); } try { conn.shutdown(); } catch (IOException ignore) { } context.removeAttribute(RESPONSE_SINK_BUFFER); context.removeAttribute(REQUEST_SOURCE_BUFFER); context.removeAttribute(CLIENT_CONNECTION_DEBUG); context.removeAttribute(CONNECTION_CREATION_TIME); }
From source file:org.apache.synapse.transport.nhttp.ConnectionPool.java
private static void cleanConnectionReferences(NHttpClientConnection conn) { HttpContext ctx = conn.getContext(); Axis2HttpRequest axis2Req = (Axis2HttpRequest) ctx.getAttribute(ClientHandler.AXIS2_HTTP_REQUEST); axis2Req.clear(); // this is linked via the selection key attachment and will free itself // on timeout of the keep alive connection. Till then minimize the // memory usage to a few bytes ctx.removeAttribute(ClientHandler.ATTACHMENT_KEY); ctx.removeAttribute(ClientHandler.TUNNEL_HANDLER); ctx.removeAttribute(ClientHandler.AXIS2_HTTP_REQUEST); ctx.removeAttribute(ClientHandler.OUTGOING_MESSAGE_CONTEXT); ctx.removeAttribute(ClientHandler.REQUEST_SOURCE_BUFFER); ctx.removeAttribute(ClientHandler.RESPONSE_SINK_BUFFER); ctx.removeAttribute(ExecutionContext.HTTP_REQUEST); ctx.removeAttribute(ExecutionContext.HTTP_RESPONSE); conn.resetOutput();/* w w w . j a va2 s . co m*/ }
From source file:org.apache.synapse.transport.nhttp.ServerHandler.java
/** * Process ready input by writing it into the Pipe * @param conn the connection being processed * @param decoder the content decoder in use *//*from w w w . ja v a 2 s . c o m*/ public void inputReady(final NHttpServerConnection conn, final ContentDecoder decoder) { HttpContext context = conn.getContext(); ContentInputBuffer inBuf = (ContentInputBuffer) context.getAttribute(REQUEST_SINK_BUFFER); try { int bytesRead = inBuf.consumeContent(decoder); if (metrics != null && bytesRead > 0) { metrics.incrementBytesReceived(bytesRead); } if (decoder.isCompleted()) { ((ServerConnectionDebug) conn.getContext().getAttribute(SERVER_CONNECTION_DEBUG)) .recordRequestCompletionTime(); // remove the request we have fully read, to detect harmless keepalive timeouts from // real timeouts while reading requests context.setAttribute(NhttpConstants.REQUEST_READ, Boolean.TRUE); context.setAttribute(NhttpConstants.REQ_FROM_CLIENT_READ_END_TIME, System.currentTimeMillis()); } } catch (IOException e) { if (metrics != null) { metrics.incrementFaultsReceiving(); } handleException("I/O Error at inputReady : " + e.getMessage(), e, conn); } }