List of usage examples for org.apache.http.conn.routing HttpRoute isTunnelled
public final boolean isTunnelled()
From source file:org.apache.http.impl.client.DefaultRequestDirector.java
/** * Execute request and retry in case of a recoverable I/O failure *//* w ww .ja v a 2 s. co m*/ private HttpResponse tryExecute(final RoutedRequest req, final HttpContext context) throws HttpException, IOException { final RequestWrapper wrapper = req.getRequest(); final HttpRoute route = req.getRoute(); HttpResponse response = null; Exception retryReason = null; for (;;) { // Increment total exec count (with redirects) execCount++; // Increment exec count for this particular request wrapper.incrementExecCount(); if (!wrapper.isRepeatable()) { this.log.debug("Cannot retry non-repeatable request"); if (retryReason != null) { throw new NonRepeatableRequestException( "Cannot retry request " + "with a non-repeatable request entity. The cause lists the " + "reason the original request failed.", retryReason); } else { throw new NonRepeatableRequestException( "Cannot retry request " + "with a non-repeatable request entity."); } } try { if (!managedConn.isOpen()) { // If we have a direct route to the target host // just re-open connection and re-try the request if (!route.isTunnelled()) { this.log.debug("Reopening the direct connection."); managedConn.open(route, context, params); } else { // otherwise give up this.log.debug("Proxied connection. Need to start over."); break; } } if (this.log.isDebugEnabled()) { this.log.debug("Attempt " + execCount + " to execute request"); } response = requestExec.execute(wrapper, managedConn, context); break; } catch (final IOException ex) { this.log.debug("Closing the connection."); try { managedConn.close(); } catch (final IOException ignore) { } if (retryHandler.retryRequest(ex, wrapper.getExecCount(), context)) { if (this.log.isInfoEnabled()) { this.log.info("I/O exception (" + ex.getClass().getName() + ") caught when processing request to " + route + ": " + ex.getMessage()); } if (this.log.isDebugEnabled()) { this.log.debug(ex.getMessage(), ex); } if (this.log.isInfoEnabled()) { this.log.info("Retrying request to " + route); } retryReason = ex; } else { if (ex instanceof NoHttpResponseException) { final NoHttpResponseException updatedex = new NoHttpResponseException( route.getTargetHost().toHostString() + " failed to respond"); updatedex.setStackTrace(ex.getStackTrace()); throw updatedex; } else { throw ex; } } } } return response; }
From source file:org.apache.http.impl.client.StatiscicsLoggingRequestDirector.java
/** * Execute request and retry in case of a recoverable I/O failure *///ww w .jav a2 s . c o m private HttpResponse tryExecute(final RoutedRequest req, final HttpContext context) throws HttpException, IOException { RequestWrapper wrapper = req.getRequest(); HttpRoute route = req.getRoute(); HttpResponse response = null; Exception retryReason = null; for (;;) { // Increment total exec count (with redirects) execCount++; // Increment exec count for this particular request wrapper.incrementExecCount(); if (!wrapper.isRepeatable()) { this.log.debug("Cannot retry non-repeatable request"); if (retryReason != null) { throw new NonRepeatableRequestException( "Cannot retry request " + "with a non-repeatable request entity. The cause lists the " + "reason the original request failed.", retryReason); } else { throw new NonRepeatableRequestException( "Cannot retry request " + "with a non-repeatable request entity."); } } try { if (!managedConn.isOpen()) { // If we have a direct route to the target host // just re-open connection and re-try the request if (!route.isTunnelled()) { this.log.debug("Reopening the direct connection."); managedConn.open(route, context, params); } else { // otherwise give up this.log.debug("Proxied connection. Need to start over."); break; } } if (this.log.isDebugEnabled()) { this.log.debug("Attempt " + execCount + " to execute request"); } response = requestExec.execute(wrapper, managedConn, context); break; } catch (IOException ex) { this.log.debug("Closing the connection."); try { managedConn.close(); } catch (IOException ignore) { } if (retryHandler.retryRequest(ex, wrapper.getExecCount(), context)) { if (this.log.isInfoEnabled()) { this.log.info("I/O exception (" + ex.getClass().getName() + ") caught when processing request: " + ex.getMessage()); } if (this.log.isDebugEnabled()) { this.log.debug(ex.getMessage(), ex); } this.log.info("Retrying request"); retryReason = ex; } else { throw ex; } } } return response; }
From source file:org.apache.http.impl.execchain.MainClientExec.java
public CloseableHttpResponse execute(final HttpRoute route, final HttpRequestWrapper request, final HttpClientContext context, final HttpExecutionAware execAware) throws IOException, HttpException { Args.notNull(route, "HTTP route"); Args.notNull(request, "HTTP request"); Args.notNull(context, "HTTP context"); AuthState targetAuthState = context.getTargetAuthState(); if (targetAuthState == null) { targetAuthState = new AuthState(); context.setAttribute(HttpClientContext.TARGET_AUTH_STATE, targetAuthState); }/* ww w .j a va 2 s . c om*/ AuthState proxyAuthState = context.getProxyAuthState(); if (proxyAuthState == null) { proxyAuthState = new AuthState(); context.setAttribute(HttpClientContext.PROXY_AUTH_STATE, proxyAuthState); } if (request instanceof HttpEntityEnclosingRequest) { Proxies.enhanceEntity((HttpEntityEnclosingRequest) request); } Object userToken = context.getUserToken(); final ConnectionRequest connRequest = connManager.requestConnection(route, userToken); if (execAware != null) { if (execAware.isAborted()) { connRequest.cancel(); throw new RequestAbortedException("Request aborted"); } else { execAware.setCancellable(connRequest); } } final RequestConfig config = context.getRequestConfig(); final HttpClientConnection managedConn; try { final int timeout = config.getConnectionRequestTimeout(); managedConn = connRequest.get(timeout > 0 ? timeout : 0, TimeUnit.MILLISECONDS); } catch (final InterruptedException interrupted) { Thread.currentThread().interrupt(); throw new RequestAbortedException("Request aborted", interrupted); } catch (final ExecutionException ex) { Throwable cause = ex.getCause(); if (cause == null) { cause = ex; } throw new RequestAbortedException("Request execution failed", cause); } context.setAttribute(HttpCoreContext.HTTP_CONNECTION, managedConn); if (config.isStaleConnectionCheckEnabled()) { // validate connection if (managedConn.isOpen()) { this.log.debug("Stale connection check"); if (managedConn.isStale()) { this.log.debug("Stale connection detected"); managedConn.close(); } } } final ConnectionHolder connHolder = new ConnectionHolder(this.log, this.connManager, managedConn); try { if (execAware != null) { execAware.setCancellable(connHolder); } HttpResponse response; for (int execCount = 1;; execCount++) { if (execCount > 1 && !Proxies.isRepeatable(request)) { throw new NonRepeatableRequestException( "Cannot retry request " + "with a non-repeatable request entity."); } if (execAware != null && execAware.isAborted()) { throw new RequestAbortedException("Request aborted"); } if (!managedConn.isOpen()) { this.log.debug("Opening connection " + route); try { establishRoute(proxyAuthState, managedConn, route, request, context); } catch (final TunnelRefusedException ex) { if (this.log.isDebugEnabled()) { this.log.debug(ex.getMessage()); } response = ex.getResponse(); break; } } final int timeout = config.getSocketTimeout(); if (timeout >= 0) { managedConn.setSocketTimeout(timeout); } if (execAware != null && execAware.isAborted()) { throw new RequestAbortedException("Request aborted"); } if (this.log.isDebugEnabled()) { this.log.debug("Executing request " + request.getRequestLine()); } if (!request.containsHeader(AUTH.WWW_AUTH_RESP)) { if (this.log.isDebugEnabled()) { this.log.debug("Target auth state: " + targetAuthState.getState()); } this.authenticator.generateAuthResponse(request, targetAuthState, context); } if (!request.containsHeader(AUTH.PROXY_AUTH_RESP) && !route.isTunnelled()) { if (this.log.isDebugEnabled()) { this.log.debug("Proxy auth state: " + proxyAuthState.getState()); } this.authenticator.generateAuthResponse(request, proxyAuthState, context); } response = requestExecutor.execute(request, managedConn, context); // The connection is in or can be brought to a re-usable state. if (reuseStrategy.keepAlive(response, context)) { // Set the idle duration of this connection final long duration = keepAliveStrategy.getKeepAliveDuration(response, context); if (this.log.isDebugEnabled()) { final String s; if (duration > 0) { s = "for " + duration + " " + TimeUnit.MILLISECONDS; } else { s = "indefinitely"; } this.log.debug("Connection can be kept alive " + s); } connHolder.setValidFor(duration, TimeUnit.MILLISECONDS); connHolder.markReusable(); } else { connHolder.markNonReusable(); } if (needAuthentication(targetAuthState, proxyAuthState, route, response, context)) { // Make sure the response body is fully consumed, if present final HttpEntity entity = response.getEntity(); if (connHolder.isReusable()) { EntityUtils.consume(entity); } else { managedConn.close(); if (proxyAuthState.getState() == AuthProtocolState.SUCCESS && proxyAuthState.getAuthScheme() != null && proxyAuthState.getAuthScheme().isConnectionBased()) { this.log.debug("Resetting proxy auth state"); proxyAuthState.reset(); } if (targetAuthState.getState() == AuthProtocolState.SUCCESS && targetAuthState.getAuthScheme() != null && targetAuthState.getAuthScheme().isConnectionBased()) { this.log.debug("Resetting target auth state"); targetAuthState.reset(); } } // discard previous auth headers final HttpRequest original = request.getOriginal(); if (!original.containsHeader(AUTH.WWW_AUTH_RESP)) { request.removeHeaders(AUTH.WWW_AUTH_RESP); } if (!original.containsHeader(AUTH.PROXY_AUTH_RESP)) { request.removeHeaders(AUTH.PROXY_AUTH_RESP); } } else { break; } } if (userToken == null) { userToken = userTokenHandler.getUserToken(context); context.setAttribute(HttpClientContext.USER_TOKEN, userToken); } if (userToken != null) { connHolder.setState(userToken); } // check for entity, release connection if possible final HttpEntity entity = response.getEntity(); if (entity == null || !entity.isStreaming()) { // connection not needed and (assumed to be) in re-usable state connHolder.releaseConnection(); return Proxies.enhanceResponse(response, null); } else { return Proxies.enhanceResponse(response, connHolder); } } catch (final ConnectionShutdownException ex) { final InterruptedIOException ioex = new InterruptedIOException("Connection has been shut down"); ioex.initCause(ex); throw ioex; } catch (final HttpException ex) { connHolder.abortConnection(); throw ex; } catch (final IOException ex) { connHolder.abortConnection(); throw ex; } catch (final RuntimeException ex) { connHolder.abortConnection(); throw ex; } }
From source file:org.apache.http.impl.execchain.ProtocolExec.java
void rewriteRequestURI(final HttpRequestWrapper request, final HttpRoute route) throws ProtocolException { try {/*from www . jav a2 s.co m*/ URI uri = request.getURI(); if (uri != null) { if (route.getProxyHost() != null && !route.isTunnelled()) { // Make sure the request URI is absolute if (!uri.isAbsolute()) { final HttpHost target = route.getTargetHost(); uri = URIUtils.rewriteURI(uri, target, true); } else { uri = URIUtils.rewriteURI(uri); } } else { // Make sure the request URI is relative if (uri.isAbsolute()) { uri = URIUtils.rewriteURI(uri, null, true); } else { uri = URIUtils.rewriteURI(uri); } } request.setURI(uri); } } catch (final URISyntaxException ex) { throw new ProtocolException("Invalid URI: " + request.getRequestLine().getUri(), ex); } }
From source file:org.apache.http.impl.nio.client.DefaultAsyncRequestDirector.java
protected void rewriteRequestURI(final RequestWrapper request, final HttpRoute route) throws ProtocolException { try {/*from ww w .j av a 2s. c o m*/ URI uri = request.getURI(); if (route.getProxyHost() != null && !route.isTunnelled()) { // Make sure the request URI is absolute if (!uri.isAbsolute()) { final HttpHost target = route.getTargetHost(); uri = URIUtils.rewriteURI(uri, target); request.setURI(uri); } } else { // Make sure the request URI is relative if (uri.isAbsolute()) { uri = URIUtils.rewriteURI(uri, null); request.setURI(uri); } } } catch (final URISyntaxException ex) { throw new ProtocolException("Invalid URI: " + request.getRequestLine().getUri(), ex); } }
From source file:org.apache.http.impl.nio.client.MainClientExec.java
@Override public HttpRequest generateRequest(final InternalState state, final AbstractClientExchangeHandler<?> handler) throws IOException, HttpException { final HttpRoute route = handler.getRoute(); handler.verifytRoute();/*from www . jav a 2 s. c o m*/ if (!handler.isRouteEstablished()) { int step; loop: do { final HttpRoute fact = handler.getActualRoute(); step = this.routeDirector.nextStep(route, fact); switch (step) { case HttpRouteDirector.CONNECT_TARGET: handler.onRouteToTarget(); break; case HttpRouteDirector.CONNECT_PROXY: handler.onRouteToProxy(); break; case HttpRouteDirector.TUNNEL_TARGET: if (this.log.isDebugEnabled()) { this.log.debug("[exchange: " + state.getId() + "] Tunnel required"); } final HttpRequest connect = createConnectRequest(route, state); handler.setCurrentRequest(HttpRequestWrapper.wrap(connect)); break loop; case HttpRouteDirector.TUNNEL_PROXY: throw new HttpException("Proxy chains are not supported"); case HttpRouteDirector.LAYER_PROTOCOL: handler.onRouteUpgrade(); break; case HttpRouteDirector.UNREACHABLE: throw new HttpException( "Unable to establish route: " + "planned = " + route + "; current = " + fact); case HttpRouteDirector.COMPLETE: handler.onRouteComplete(); this.log.debug("Connection route established"); break; default: throw new IllegalStateException("Unknown step indicator " + step + " from RouteDirector."); } } while (step > HttpRouteDirector.COMPLETE); } final HttpClientContext localContext = state.getLocalContext(); HttpRequestWrapper currentRequest = handler.getCurrentRequest(); if (currentRequest == null) { currentRequest = state.getMainRequest(); handler.setCurrentRequest(currentRequest); } if (handler.isRouteEstablished()) { state.incrementExecCount(); if (state.getExecCount() > 1) { final HttpAsyncRequestProducer requestProducer = state.getRequestProducer(); if (!requestProducer.isRepeatable() && state.isRequestContentProduced()) { throw new NonRepeatableRequestException( "Cannot retry request " + "with a non-repeatable request entity."); } requestProducer.resetRequest(); } if (this.log.isDebugEnabled()) { this.log.debug("[exchange: " + state.getId() + "] Attempt " + state.getExecCount() + " to execute request"); } if (!currentRequest.containsHeader(AUTH.WWW_AUTH_RESP)) { final AuthState targetAuthState = localContext.getTargetAuthState(); if (this.log.isDebugEnabled()) { this.log.debug("Target auth state: " + targetAuthState.getState()); } this.authenticator.generateAuthResponse(currentRequest, targetAuthState, localContext); } if (!currentRequest.containsHeader(AUTH.PROXY_AUTH_RESP) && !route.isTunnelled()) { final AuthState proxyAuthState = localContext.getProxyAuthState(); if (this.log.isDebugEnabled()) { this.log.debug("Proxy auth state: " + proxyAuthState.getState()); } this.authenticator.generateAuthResponse(currentRequest, proxyAuthState, localContext); } } else { if (!currentRequest.containsHeader(AUTH.PROXY_AUTH_RESP)) { final AuthState proxyAuthState = localContext.getProxyAuthState(); if (this.log.isDebugEnabled()) { this.log.debug("Proxy auth state: " + proxyAuthState.getState()); } this.authenticator.generateAuthResponse(currentRequest, proxyAuthState, localContext); } } final NHttpClientConnection managedConn = handler.getConnection(); localContext.setAttribute(HttpCoreContext.HTTP_CONNECTION, managedConn); final RequestConfig config = localContext.getRequestConfig(); if (config.getSocketTimeout() > 0) { managedConn.setSocketTimeout(config.getSocketTimeout()); } return currentRequest; }
From source file:org.apache.http.impl.nio.client.MainClientExec.java
private void rewriteRequestURI(final HttpRequestWrapper request, final HttpRoute route) throws ProtocolException { try {// w w w .j a va2 s . c o m URI uri = request.getURI(); if (uri != null) { if (route.getProxyHost() != null && !route.isTunnelled()) { // Make sure the request URI is absolute if (!uri.isAbsolute()) { final HttpHost target = route.getTargetHost(); uri = URIUtils.rewriteURI(uri, target, true); } else { uri = URIUtils.rewriteURI(uri); } } else { // Make sure the request URI is relative if (uri.isAbsolute()) { uri = URIUtils.rewriteURI(uri, null, true); } else { uri = URIUtils.rewriteURI(uri); } } request.setURI(uri); } } catch (final URISyntaxException ex) { throw new ProtocolException("Invalid URI: " + request.getRequestLine().getUri(), ex); } }
From source file:org.apache.synapse.transport.http.conn.ClientConnFactory.java
public DefaultNHttpClientConnection createConnection(final IOSession iosession, final HttpRoute route) { IOSession customSession;//from w w w . ja v a 2 s .c o m if (ssl != null && route.isSecure() && !route.isTunnelled()) { SSLContext customContext = getSSLContext(iosession); SSLIOSession ssliosession = new SSLIOSession(iosession, SSLMode.CLIENT, customContext, ssl.getHandler()); iosession.setAttribute(SSLIOSession.SESSION_KEY, ssliosession); customSession = ssliosession; } else { if (route != null && route.isTunnelled()) { org.apache.http.HttpHost httpHost = route.getTargetHost(); String beAddress = null; String proxyAdd = null; if (httpHost != null) { String hostname = httpHost.getHostName(); int port = httpHost.getPort(); beAddress = hostname + ":" + port; } org.apache.http.HttpHost proxyHost = route.getProxyHost(); if (proxyHost != null) { String proxyHostName = proxyHost.getHostName(); int proxyPort = proxyHost.getPort(); proxyAdd = proxyHostName + ":" + proxyPort; } if (sslByHostMap != null && sslByHostMap.containsKey(beAddress)) { SSLContext beCtx = sslByHostMap.get(beAddress); sslByHostMap.put(proxyAdd, beCtx); } } customSession = iosession; } DefaultNHttpClientConnection conn = LoggingUtils.createClientConnection(customSession, responseFactory, allocator, params); int timeout = HttpConnectionParams.getSoTimeout(params); conn.setSocketTimeout(timeout); return conn; }
From source file:org.apache.synapse.transport.nhttp.ClientHandler.java
/** * Process a new connection over an existing TCP connection or new * //from ww w . j av a 2s . co m * @param conn HTTP connection to be processed * @param axis2Req axis2 representation of the message in the connection * @throws ConnectionClosedException if the connection is closed */ private void processConnection(final NHttpClientConnection conn, final Axis2HttpRequest axis2Req) throws ConnectionClosedException { // record start time of request ClientConnectionDebug cd = (ClientConnectionDebug) axis2Req.getMsgContext() .getProperty(CLIENT_CONNECTION_DEBUG); if (cd != null) { cd.recordRequestStartTime(conn, axis2Req); conn.getContext().setAttribute(CLIENT_CONNECTION_DEBUG, cd); } try { // Reset connection metrics conn.getMetrics().reset(); HttpContext context = conn.getContext(); ContentOutputBuffer outputBuffer = new SharedOutputBuffer(cfg.getBufferSize(), conn, allocator); axis2Req.setOutputBuffer(outputBuffer); context.setAttribute(REQUEST_SOURCE_BUFFER, outputBuffer); HttpRoute route = axis2Req.getRoute(); context.setAttribute(AXIS2_HTTP_REQUEST, axis2Req); context.setAttribute(ExecutionContext.HTTP_CONNECTION, conn); context.setAttribute(ExecutionContext.HTTP_TARGET_HOST, route.getTargetHost()); context.setAttribute(OUTGOING_MESSAGE_CONTEXT, axis2Req.getMsgContext()); HttpRequest request = axis2Req.getRequest(); request.setParams(new DefaultedHttpParams(request.getParams(), this.params)); /* * Remove Content-Length and Transfer-Encoding headers, if already present. * */ request.removeHeaders(HTTP.TRANSFER_ENCODING); request.removeHeaders(HTTP.CONTENT_LEN); this.httpProcessor.process(request, context); if (proxyauthenticator != null && route.getProxyHost() != null && !route.isTunnelled()) { proxyauthenticator.authenticatePreemptively(request, context); } if (axis2Req.getTimeout() > 0) { conn.setSocketTimeout(axis2Req.getTimeout()); } context.setAttribute(NhttpConstants.ENDPOINT_PREFIX, axis2Req.getEndpointURLPrefix()); context.setAttribute(NhttpConstants.HTTP_REQ_METHOD, request.getRequestLine().getMethod()); context.setAttribute(ExecutionContext.HTTP_REQUEST, request); setServerContextAttribute(NhttpConstants.REQ_DEPARTURE_TIME, System.currentTimeMillis(), conn); setServerContextAttribute(NhttpConstants.REQ_TO_BACKEND_WRITE_START_TIME, System.currentTimeMillis(), conn); conn.submitRequest(request); } catch (ConnectionClosedException e) { throw e; } catch (IOException e) { if (metrics != null) { metrics.incrementFaultsSending(); } handleException("I/O Error submitting request : " + e.getMessage(), e, conn); } catch (HttpException e) { if (metrics != null) { metrics.incrementFaultsSending(); } handleException("HTTP protocol error submitting request : " + e.getMessage(), e, conn); } finally { synchronized (axis2Req) { axis2Req.setReadyToStream(true); axis2Req.notifyAll(); } } }
From source file:org.apache.synapse.transport.passthru.TargetHandler.java
public void connected(NHttpClientConnection conn, Object o) { assert o instanceof HostConnections : "Attachment should be a HostConnections"; HostConnections pool = (HostConnections) o; conn.getContext().setAttribute(PassThroughConstants.CONNECTION_POOL, pool); HttpRoute route = pool.getRoute(); // create the connection information and set it to request ready TargetContext.create(conn, ProtocolState.REQUEST_READY, targetConfiguration); // notify the pool about the new connection targetConfiguration.getConnections().addConnection(conn); // notify about the new connection deliveryAgent.connected(pool.getRoute(), conn); HttpContext context = conn.getContext(); context.setAttribute(PassThroughConstants.REQ_DEPARTURE_TIME, System.currentTimeMillis()); metrics.connected();/*from w ww .ja v a 2s .co m*/ if (route.isTunnelled()) { // Requires a proxy tunnel ProxyTunnelHandler tunnelHandler = new ProxyTunnelHandler(route, connFactory); context.setAttribute(PassThroughConstants.TUNNEL_HANDLER, tunnelHandler); } }