List of usage examples for org.apache.http.protocol HttpCoreContext HTTP_CONNECTION
String HTTP_CONNECTION
To view the source code for org.apache.http.protocol HttpCoreContext HTTP_CONNECTION.
Click Source Link
From source file:ste.web.http.beanshell.BugFreeBeanShellUtils.java
@Test public void bodyAsJSONObjectWithCharset() throws Exception { final String TEST_LABEL1 = "label1"; final String TEST_VALUE1 = "a first label"; BasicHttpEntityEnclosingRequest request = new BasicHttpEntityEnclosingRequest("get", TEST_URI_PARAMETERS); HttpSessionContext context = new HttpSessionContext(); context.setAttribute(HttpCoreContext.HTTP_CONNECTION, getConnection()); request.addHeader(HTTP.CONTENT_TYPE, CONTENT_TYPE_JSON + ";charset=utf-8"); request.setEntity(new StringEntity(String.format("{%s:'%s'}", TEST_LABEL1, TEST_VALUE1))); Interpreter i = new Interpreter(); BeanShellUtils.setup(i, request, RESPONSE_OK, context); checkJSONObject(i, TEST_LABEL1, TEST_VALUE1); }
From source file:ste.web.http.beanshell.BugFreeBeanShellHandler.java
@Test public void runningMultipleThreadInDifferentContexts() throws Exception { final HttpSessionContext CTX1 = new HttpSessionContext(); final HttpSessionContext CTX2 = new HttpSessionContext(); CTX1.setAttribute(HttpCoreContext.HTTP_CONNECTION, getConnection()); CTX2.setAttribute(HttpCoreContext.HTTP_CONNECTION, getConnection()); Thread t1 = new Thread(new Runnable() { @Override/*w w w . j av a2 s . c o m*/ public void run() { try { handler.handle(get("/multithreading.bsh"), response, CTX1); } catch (Exception x) { x.printStackTrace(); } } }); Thread t2 = new Thread(new Runnable() { @Override public void run() { try { handler.handle(get("/multithreading.bsh"), response, CTX2); } catch (Exception x) { x.printStackTrace(); } } }); t1.start(); t2.start(); t1.join(); t2.join(); then(CTX1.get("view")).isEqualTo(t1.getName()); then(CTX2.get("view")).isEqualTo(t2.getName()); }
From source file:ste.web.http.beanshell.BugFreeBeanShellUtils.java
@Test public void bodyAsCorruptedJSONObject() throws Exception { BasicHttpEntityEnclosingRequest request = new BasicHttpEntityEnclosingRequest("get", TEST_URI_PARAMETERS); HttpSessionContext context = new HttpSessionContext(); context.setAttribute(HttpCoreContext.HTTP_CONNECTION, getConnection()); request.addHeader(HTTP.CONTENT_TYPE, CONTENT_TYPE_JSON); Interpreter i = new Interpreter(); for (String s : TEST_JSON_ERRORS) { request.setEntity(new StringEntity(s)); try {/* w ww . j av a 2 s. com*/ BeanShellUtils.setup(i, request, RESPONSE_OK, context); fail("JSONException not thrown for <" + s + ">"); } catch (IOException x) { then(x.getCause()).isNotNull().isInstanceOf(JSONException.class); } } }
From source file:ste.web.http.beanshell.BugFreeBeanShellUtils.java
@Test public void formUrlEncodedParameters() throws Exception { BasicHttpEntityEnclosingRequest request = new BasicHttpEntityEnclosingRequest("get", TEST_URI09); StringEntity e = new StringEntity(TEST_QUERY_STRING); e.setContentType(ContentType.APPLICATION_FORM_URLENCODED.getMimeType()); request.setEntity(e);//from ww w.ja v a 2 s. c o m HttpSessionContext context = new HttpSessionContext(); context.setAttribute(HttpCoreContext.HTTP_CONNECTION, getConnection()); request.addHeader(HTTP.CONTENT_TYPE, e.getContentType().getValue()); Interpreter i = new Interpreter(); BeanShellUtils.setup(i, request, RESPONSE_OK, context); then(i.get(TEST_URL_PARAM1)).isEqualTo(TEST_VALUE1); then(i.get(TEST_URL_PARAM2)).isEqualTo(TEST_VALUE2); e.setContentType(ContentType.APPLICATION_FORM_URLENCODED.getMimeType() + " ; charset=UTF-8"); request.setHeader(HTTP.CONTENT_TYPE, e.getContentType().getValue()); i = new Interpreter(); BeanShellUtils.setup(i, request, RESPONSE_OK, context); then(i.get(TEST_URL_PARAM1)).isEqualTo(TEST_VALUE1); then(i.get(TEST_URL_PARAM2)).isEqualTo(TEST_VALUE2); }
From source file:com.bytelightning.opensource.pokerface.ScriptHelperImpl.java
/** * Return the underlying connection for this request / response transaction *//*w w w . j a va 2s . c om*/ private NHttpServerConnection getConnection() { return (NHttpServerConnection) context.getAttribute(HttpCoreContext.HTTP_CONNECTION); }
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); }/*w ww . j a v a 2s. 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.MinimalClientExec.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"); rewriteRequestURI(request, route);//from w ww.j av a 2 s . com final ConnectionRequest connRequest = connManager.requestConnection(route, null); 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); } final ConnectionHolder releaseTrigger = new ConnectionHolder(log, connManager, managedConn); try { if (execAware != null) { if (execAware.isAborted()) { releaseTrigger.close(); throw new RequestAbortedException("Request aborted"); } else { execAware.setCancellable(releaseTrigger); } } if (!managedConn.isOpen()) { final int timeout = config.getConnectTimeout(); this.connManager.connect(managedConn, route, timeout > 0 ? timeout : 0, context); this.connManager.routeComplete(managedConn, route, context); } final int timeout = config.getSocketTimeout(); if (timeout >= 0) { managedConn.setSocketTimeout(timeout); } HttpHost target = null; final HttpRequest original = request.getOriginal(); if (original instanceof HttpUriRequest) { final URI uri = ((HttpUriRequest) original).getURI(); if (uri.isAbsolute()) { target = new HttpHost(uri.getHost(), uri.getPort(), uri.getScheme()); } } if (target == null) { target = route.getTargetHost(); } context.setAttribute(HttpCoreContext.HTTP_TARGET_HOST, target); context.setAttribute(HttpCoreContext.HTTP_REQUEST, request); context.setAttribute(HttpCoreContext.HTTP_CONNECTION, managedConn); context.setAttribute(HttpClientContext.HTTP_ROUTE, route); httpProcessor.process(request, context); final HttpResponse response = requestExecutor.execute(request, managedConn, context); httpProcessor.process(response, 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); releaseTrigger.setValidFor(duration, TimeUnit.MILLISECONDS); releaseTrigger.markReusable(); } else { releaseTrigger.markNonReusable(); } // 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 releaseTrigger.releaseConnection(); return Proxies.enhanceResponse(response, null); } else { return Proxies.enhanceResponse(response, releaseTrigger); } } catch (final ConnectionShutdownException ex) { final InterruptedIOException ioex = new InterruptedIOException("Connection has been shut down"); ioex.initCause(ex); throw ioex; } catch (final HttpException ex) { releaseTrigger.abortConnection(); throw ex; } catch (final IOException ex) { releaseTrigger.abortConnection(); throw ex; } catch (final RuntimeException ex) { releaseTrigger.abortConnection(); throw 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();//ww w . jav a 2s . c om 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.MinimalClientExchangeHandlerImpl.java
@Override public HttpRequest generateRequest() throws IOException, HttpException { verifytRoute();/*from w w w. j av a2s .co m*/ if (!isRouteEstablished()) { onRouteToTarget(); onRouteComplete(); } final NHttpClientConnection localConn = getConnection(); this.localContext.setAttribute(HttpCoreContext.HTTP_CONNECTION, localConn); final RequestConfig config = this.localContext.getRequestConfig(); if (config.getSocketTimeout() > 0) { localConn.setSocketTimeout(config.getSocketTimeout()); } return getCurrentRequest(); }
From source file:org.apache.http.impl.nio.client.PipeliningClientExchangeHandlerImpl.java
@Override public HttpRequest generateRequest() throws IOException, HttpException { verifytRoute();/*ww w . j av a2s. co m*/ if (!isRouteEstablished()) { onRouteToTarget(); onRouteComplete(); } final NHttpClientConnection localConn = getConnection(); this.localContext.setAttribute(HttpCoreContext.HTTP_CONNECTION, localConn); Asserts.check(this.requestProducerRef.get() == null, "Inconsistent state: currentRequest producer is not null"); final HttpAsyncRequestProducer requestProducer = this.requestProducerQueue.poll(); if (requestProducer == null) { return null; } this.requestProducerRef.set(requestProducer); final HttpRequest original = requestProducer.generateRequest(); final HttpRequestWrapper currentRequest = HttpRequestWrapper.wrap(original); final RequestConfig config = this.localContext.getRequestConfig(); if (config.getSocketTimeout() > 0) { localConn.setSocketTimeout(config.getSocketTimeout()); } this.httpProcessor.process(currentRequest, this.localContext); this.requestQueue.add(currentRequest); setCurrentRequest(currentRequest); return currentRequest; }