List of usage examples for org.apache.http.protocol HttpContext setAttribute
void setAttribute(String str, Object obj);
From source file:com.xtremelabs.robolectric.tester.org.apache.http.impl.client.DefaultRequestDirector.java
public HttpResponse execute(HttpHost target, HttpRequest request, HttpContext context) throws HttpException, IOException { HttpRequest orig = request;/*from w ww . j ava 2 s . c om*/ RequestWrapper origWrapper = wrapRequest(orig); origWrapper.setParams(params); HttpRoute origRoute = determineRoute(target, origWrapper, context); virtualHost = (HttpHost) orig.getParams().getParameter(ClientPNames.VIRTUAL_HOST); RoutedRequest roureq = new RoutedRequest(origWrapper, origRoute); long timeout = ConnManagerParams.getTimeout(params); int execCount = 0; boolean reuse = false; boolean done = false; try { HttpResponse response = null; while (!done) { // In this loop, the RoutedRequest may be replaced by a // followup request and route. The request and route passed // in the method arguments will be replaced. The original // request is still available in 'orig'. RequestWrapper wrapper = roureq.getRequest(); HttpRoute route = roureq.getRoute(); response = null; // See if we have a user token bound to the execution context Object userToken = context.getAttribute(ClientContext.USER_TOKEN); // Allocate connection if needed if (managedConn == null) { ClientConnectionRequest connRequest = connManager.requestConnection(route, userToken); if (orig instanceof AbortableHttpRequest) { ((AbortableHttpRequest) orig).setConnectionRequest(connRequest); } try { managedConn = connRequest.getConnection(timeout, TimeUnit.MILLISECONDS); } catch (InterruptedException interrupted) { InterruptedIOException iox = new InterruptedIOException(); iox.initCause(interrupted); throw iox; } if (HttpConnectionParams.isStaleCheckingEnabled(params)) { // validate connection if (managedConn.isOpen()) { this.log.debug("Stale connection check"); if (managedConn.isStale()) { this.log.debug("Stale connection detected"); managedConn.close(); } } } } if (orig instanceof AbortableHttpRequest) { ((AbortableHttpRequest) orig).setReleaseTrigger(managedConn); } // Reopen connection if needed if (!managedConn.isOpen()) { managedConn.open(route, context, params); } else { managedConn.setSocketTimeout(HttpConnectionParams.getSoTimeout(params)); } try { establishRoute(route, context); } catch (TunnelRefusedException ex) { if (this.log.isDebugEnabled()) { this.log.debug(ex.getMessage()); } response = ex.getResponse(); break; } // Reset headers on the request wrapper wrapper.resetHeaders(); // Re-write request URI if needed rewriteRequestURI(wrapper, route); // Use virtual host if set target = virtualHost; if (target == null) { target = route.getTargetHost(); } HttpHost proxy = route.getProxyHost(); // Populate the execution context context.setAttribute(ExecutionContext.HTTP_TARGET_HOST, target); context.setAttribute(ExecutionContext.HTTP_PROXY_HOST, proxy); context.setAttribute(ExecutionContext.HTTP_CONNECTION, managedConn); context.setAttribute(ClientContext.TARGET_AUTH_STATE, targetAuthState); context.setAttribute(ClientContext.PROXY_AUTH_STATE, proxyAuthState); // Run request protocol interceptors requestExec.preProcess(wrapper, httpProcessor, context); boolean retrying = true; Exception retryReason = null; while (retrying) { // 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 (this.log.isDebugEnabled()) { this.log.debug("Attempt " + execCount + " to execute request"); } response = requestExec.execute(wrapper, managedConn, context); retrying = false; } catch (IOException ex) { this.log.debug("Closing the connection."); managedConn.close(); 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; } // 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."); retrying = false; } } } if (response == null) { // Need to start over continue; } // Run response protocol interceptors response.setParams(params); requestExec.postProcess(response, httpProcessor, context); // The connection is in or can be brought to a re-usable state. reuse = reuseStrategy.keepAlive(response, context); if (reuse) { // Set the idle duration of this connection long duration = keepAliveStrategy.getKeepAliveDuration(response, context); managedConn.setIdleDuration(duration, TimeUnit.MILLISECONDS); if (this.log.isDebugEnabled()) { if (duration >= 0) { this.log.debug("Connection can be kept alive for " + duration + " ms"); } else { this.log.debug("Connection can be kept alive indefinitely"); } } } RoutedRequest followup = handleResponse(roureq, response, context); if (followup == null) { done = true; } else { if (reuse) { // Make sure the response body is fully consumed, if present HttpEntity entity = response.getEntity(); if (entity != null) { entity.consumeContent(); } // entity consumed above is not an auto-release entity, // need to mark the connection re-usable explicitly managedConn.markReusable(); } else { managedConn.close(); } // check if we can use the same connection for the followup if (!followup.getRoute().equals(roureq.getRoute())) { releaseConnection(); } roureq = followup; } if (managedConn != null && userToken == null) { userToken = userTokenHandler.getUserToken(context); context.setAttribute(ClientContext.USER_TOKEN, userToken); if (userToken != null) { managedConn.setState(userToken); } } } // while not done // check for entity, release connection if possible if ((response == null) || (response.getEntity() == null) || !response.getEntity().isStreaming()) { // connection not needed and (assumed to be) in re-usable state if (reuse) managedConn.markReusable(); releaseConnection(); } else { // install an auto-release entity HttpEntity entity = response.getEntity(); entity = new BasicManagedEntity(entity, managedConn, reuse); response.setEntity(entity); } return response; } catch (HttpException ex) { abortConnection(); throw ex; } catch (IOException ex) { abortConnection(); throw ex; } catch (RuntimeException ex) { abortConnection(); throw ex; } }
From source file:org.robolectric.shadows.httpclient.DefaultRequestDirector.java
public HttpResponse execute(HttpHost target, HttpRequest request, HttpContext context) throws HttpException, IOException { HttpRequest orig = request;//w ww . j a v a 2 s . c o m RequestWrapper origWrapper = wrapRequest(orig); origWrapper.setParams(params); HttpRoute origRoute = determineRoute(target, origWrapper, context); virtualHost = (HttpHost) orig.getParams().getParameter(ClientPNames.VIRTUAL_HOST); RoutedRequest roureq = new RoutedRequest(origWrapper, origRoute); long timeout = ConnManagerParams.getTimeout(params); int execCount = 0; boolean reuse = false; boolean done = false; try { HttpResponse response = null; while (!done) { // In this loop, the RoutedRequest may be replaced by a // followup request and route. The request and route passed // in the method arguments will be replaced. The original // request is still available in 'orig'. RequestWrapper wrapper = roureq.getRequest(); HttpRoute route = roureq.getRoute(); response = null; // See if we have a user token bound to the execution context Object userToken = context.getAttribute(ClientContext.USER_TOKEN); // Allocate connection if needed if (managedConn == null) { ClientConnectionRequest connRequest = connManager.requestConnection(route, userToken); if (orig instanceof AbortableHttpRequest) { ((AbortableHttpRequest) orig).setConnectionRequest(connRequest); } try { managedConn = connRequest.getConnection(timeout, TimeUnit.MILLISECONDS); } catch (InterruptedException interrupted) { InterruptedIOException iox = new InterruptedIOException(); iox.initCause(interrupted); throw iox; } if (HttpConnectionParams.isStaleCheckingEnabled(params)) { // validate connection if (managedConn.isOpen()) { this.log.debug("Stale connection check"); if (managedConn.isStale()) { this.log.debug("Stale connection detected"); managedConn.close(); } } } } if (orig instanceof AbortableHttpRequest) { ((AbortableHttpRequest) orig).setReleaseTrigger(managedConn); } // Reopen connection if needed if (!managedConn.isOpen()) { managedConn.open(route, context, params); } else { managedConn.setSocketTimeout(HttpConnectionParams.getSoTimeout(params)); } try { establishRoute(route, context); } catch (TunnelRefusedException ex) { if (this.log.isDebugEnabled()) { this.log.debug(ex.getMessage()); } response = ex.getResponse(); break; } // Reset headers on the request wrapper wrapper.resetHeaders(); // Re-write request URI if needed rewriteRequestURI(wrapper, route); // Use virtual host if set target = virtualHost; if (target == null) { target = route.getTargetHost(); } HttpHost proxy = route.getProxyHost(); // Populate the execution context context.setAttribute(ExecutionContext.HTTP_TARGET_HOST, target); context.setAttribute(ExecutionContext.HTTP_PROXY_HOST, proxy); context.setAttribute(ExecutionContext.HTTP_CONNECTION, managedConn); context.setAttribute(ClientContext.TARGET_AUTH_STATE, targetAuthState); context.setAttribute(ClientContext.PROXY_AUTH_STATE, proxyAuthState); // Run request protocol interceptors requestExec.preProcess(wrapper, httpProcessor, context); boolean retrying = true; Exception retryReason = null; while (retrying) { // 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 (this.log.isDebugEnabled()) { this.log.debug("Attempt " + execCount + " to execute request"); } response = requestExec.execute(wrapper, managedConn, context); retrying = false; } catch (IOException ex) { this.log.debug("Closing the connection."); managedConn.close(); 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; } // 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."); retrying = false; } } } if (response == null) { // Need to start over continue; } // Run response protocol interceptors response.setParams(params); requestExec.postProcess(response, httpProcessor, context); // The connection is in or can be brought to a re-usable state. reuse = reuseStrategy.keepAlive(response, context); if (reuse) { // Set the idle duration of this connection long duration = keepAliveStrategy.getKeepAliveDuration(response, context); managedConn.setIdleDuration(duration, TimeUnit.MILLISECONDS); if (this.log.isDebugEnabled()) { if (duration >= 0) { this.log.debug("Connection can be kept alive for " + duration + " ms"); } else { this.log.debug("Connection can be kept alive indefinitely"); } } } RoutedRequest followup = handleResponse(roureq, response, context); if (followup == null) { done = true; } else { if (reuse) { // Make sure the response body is fully consumed, if present HttpEntity entity = response.getEntity(); if (entity != null) { entity.consumeContent(); } // entity consumed above is not an auto-release entity, // need to mark the connection re-usable explicitly managedConn.markReusable(); } else { managedConn.close(); } // check if we can use the same connection for the followup if (!followup.getRoute().equals(roureq.getRoute())) { releaseConnection(); } roureq = followup; } if (managedConn != null && userToken == null) { userToken = userTokenHandler.getUserToken(context); context.setAttribute(ClientContext.USER_TOKEN, userToken); if (userToken != null) { managedConn.setState(userToken); } } } // while not done // check for entity, release connection if possible if ((response == null) || (response.getEntity() == null) || !response.getEntity().isStreaming()) { // connection not needed and (assumed to be) in re-usable state if (reuse) managedConn.markReusable(); releaseConnection(); } else { // install an auto-release entity HttpEntity entity = response.getEntity(); entity = new BasicManagedEntity(entity, managedConn, reuse); response.setEntity(entity); } return response; } catch (HttpException | RuntimeException | IOException ex) { abortConnection(); throw ex; } }
From source file:org.vietspider.net.apache.DefaultRequestDirector.java
public HttpResponse execute(HttpHost target, HttpRequest request, HttpContext context) throws HttpException, IOException { HttpRequest orig = request;//w w w.j ava 2 s .c o m RequestWrapper origWrapper = wrapRequest(orig); origWrapper.setParams(params); HttpRoute origRoute = determineRoute(target, origWrapper, context); virtualHost = (HttpHost) orig.getParams().getParameter(ClientPNames.VIRTUAL_HOST); RoutedRequest roureq = new RoutedRequest(origWrapper, origRoute); long timeout = HttpConnectionParams.getConnectionTimeout(params); boolean reuse = false; boolean done = false; try { HttpResponse response = null; while (!done) { // In this loop, the RoutedRequest may be replaced by a // followup request and route. The request and route passed // in the method arguments will be replaced. The original // request is still available in 'orig'. RequestWrapper wrapper = roureq.getRequest(); HttpRoute route = roureq.getRoute(); response = null; // See if we have a user token bound to the execution context Object userToken = context.getAttribute(ClientContext.USER_TOKEN); // Allocate connection if needed if (managedConn == null) { ClientConnectionRequest connRequest = connManager.requestConnection(route, userToken); if (orig instanceof AbortableHttpRequest) { ((AbortableHttpRequest) orig).setConnectionRequest(connRequest); } try { // if(timeout < 1) timeout = 30000; // System.out.println(" =========== chay vao day roi nhe " + timeout ); // System.out.println(connRequest); managedConn = connRequest.getConnection(timeout, TimeUnit.MILLISECONDS); // System.out.println("get thuc chuyen nay"); } catch (InterruptedException interrupted) { InterruptedIOException iox = new InterruptedIOException(); iox.initCause(interrupted); throw iox; } if (HttpConnectionParams.isStaleCheckingEnabled(params)) { // validate connection if (managedConn.isOpen()) { this.log.debug("Stale connection check"); if (managedConn.isStale()) { this.log.debug("Stale connection detected"); managedConn.close(); } } } } if (orig instanceof AbortableHttpRequest) { ((AbortableHttpRequest) orig).setReleaseTrigger(managedConn); } try { tryConnect(roureq, context); } catch (TunnelRefusedException ex) { if (this.log.isDebugEnabled()) { this.log.debug(ex.getMessage()); } response = ex.getResponse(); break; } // Reset headers on the request wrapper wrapper.resetHeaders(); // Re-write request URI if needed rewriteRequestURI(wrapper, route); // Use virtual host if set target = virtualHost; if (target == null) { target = route.getTargetHost(); } HttpHost proxy = route.getProxyHost(); // Populate the execution context context.setAttribute(ExecutionContext.HTTP_TARGET_HOST, target); context.setAttribute(ExecutionContext.HTTP_PROXY_HOST, proxy); context.setAttribute(ExecutionContext.HTTP_CONNECTION, managedConn); context.setAttribute(ClientContext.TARGET_AUTH_STATE, targetAuthState); context.setAttribute(ClientContext.PROXY_AUTH_STATE, proxyAuthState); // Run request protocol interceptors requestExec.preProcess(wrapper, httpProcessor, context); response = tryExecute(roureq, context); if (response == null) { // Need to start over continue; } // Run response protocol interceptors response.setParams(params); requestExec.postProcess(response, httpProcessor, context); // The connection is in or can be brought to a re-usable state. reuse = reuseStrategy.keepAlive(response, context); if (reuse) { // Set the idle duration of this connection long duration = keepAliveStrategy.getKeepAliveDuration(response, context); if (this.log.isDebugEnabled()) { String s; if (duration > 0) { s = "for " + duration + " " + TimeUnit.MILLISECONDS; } else { s = "indefinitely"; } this.log.debug("Connection can be kept alive " + s); } managedConn.setIdleDuration(duration, TimeUnit.MILLISECONDS); } RoutedRequest followup = handleResponse(roureq, response, context); if (followup == null) { done = true; } else { if (reuse) { // Make sure the response body is fully consumed, if present HttpEntity entity = response.getEntity(); EntityUtils.consume(entity); // entity consumed above is not an auto-release entity, // need to mark the connection re-usable explicitly managedConn.markReusable(); } else { managedConn.close(); } // check if we can use the same connection for the followup if (!followup.getRoute().equals(roureq.getRoute())) { releaseConnection(); } roureq = followup; } if (managedConn != null && userToken == null) { userToken = userTokenHandler.getUserToken(context); context.setAttribute(ClientContext.USER_TOKEN, userToken); if (userToken != null) { managedConn.setState(userToken); } } } // while not done // check for entity, release connection if possible if ((response == null) || (response.getEntity() == null) || !response.getEntity().isStreaming()) { // connection not needed and (assumed to be) in re-usable state if (reuse) managedConn.markReusable(); releaseConnection(); } else { // install an auto-release entity HttpEntity entity = response.getEntity(); entity = new BasicManagedEntity(entity, managedConn, reuse); response.setEntity(entity); } return response; } catch (ConnectionShutdownException ex) { InterruptedIOException ioex = new InterruptedIOException("Connection has been shut down"); ioex.initCause(ex); throw ioex; } catch (HttpException ex) { abortConnection(); throw ex; } catch (IOException ex) { abortConnection(); throw ex; } catch (RuntimeException ex) { abortConnection(); throw ex; } }
From source file:org.apache.axis2.transport.nhttp.ClientHandler.java
/** * Submit a new request over an already established connection, which has been * 'kept alive'//from w ww. j a va2 s . c om * @param conn the connection to use to send the request, which has been kept open * @param axis2Req the new request */ public void submitRequest(final NHttpClientConnection conn, Axis2HttpRequest axis2Req) { try { HttpContext context = conn.getContext(); context.setAttribute(HttpExecutionContext.HTTP_CONNECTION, conn); context.setAttribute(HttpExecutionContext.HTTP_TARGET_HOST, axis2Req.getHttpHost()); context.setAttribute(OUTGOING_MESSAGE_CONTEXT, axis2Req.getMsgContext()); context.setAttribute(REQUEST_SOURCE_CHANNEL, axis2Req.getSourceChannel()); HttpRequest request = axis2Req.getRequest(); request.getParams().setDefaults(this.params); this.httpProcessor.process(request, context); conn.submitRequest(request); context.setAttribute(HttpExecutionContext.HTTP_REQUEST, request); } catch (IOException e) { handleException("I/O Error : " + e.getMessage(), e, conn); } catch (HttpException e) { handleException("Unexpected HTTP protocol error: " + e.getMessage(), e, conn); } }
From source file:org.apache.axis2.transport.nhttp.ClientHandler.java
/** * Invoked when the destination is connected * @param conn the connection being processed * @param attachment the attachment set previously */// w w w . j a v a2s . c o m public void connected(final NHttpClientConnection conn, final Object attachment) { try { HttpContext context = conn.getContext(); Axis2HttpRequest axis2Req = (Axis2HttpRequest) attachment; context.setAttribute(HttpExecutionContext.HTTP_CONNECTION, conn); context.setAttribute(HttpExecutionContext.HTTP_TARGET_HOST, axis2Req.getHttpHost()); // allocate temporary buffers to process this request context.setAttribute(REQUEST_BUFFER, ByteBuffer.allocate(2048)); context.setAttribute(RESPONSE_BUFFER, ByteBuffer.allocate(2048)); context.setAttribute(OUTGOING_MESSAGE_CONTEXT, axis2Req.getMsgContext()); context.setAttribute(REQUEST_SOURCE_CHANNEL, axis2Req.getSourceChannel()); HttpRequest request = axis2Req.getRequest(); request.getParams().setDefaults(this.params); this.httpProcessor.process(request, context); conn.submitRequest(request); context.setAttribute(HttpExecutionContext.HTTP_REQUEST, request); } catch (IOException e) { handleException("I/O Error : " + e.getMessage(), e, conn); } catch (HttpException e) { handleException("Unexpected HTTP protocol error: " + e.getMessage(), e, conn); } }
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 *//*from ww w. j a 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/* w ww . j a va2 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.hive.jdbc.HiveConnection.java
private CloseableHttpClient getHttpClient(Boolean useSsl) throws SQLException { boolean isCookieEnabled = sessConfMap.get(JdbcConnectionParams.COOKIE_AUTH) == null || (!JdbcConnectionParams.COOKIE_AUTH_FALSE .equalsIgnoreCase(sessConfMap.get(JdbcConnectionParams.COOKIE_AUTH))); String cookieName = sessConfMap.get(JdbcConnectionParams.COOKIE_NAME) == null ? JdbcConnectionParams.DEFAULT_COOKIE_NAMES_HS2 : sessConfMap.get(JdbcConnectionParams.COOKIE_NAME); CookieStore cookieStore = isCookieEnabled ? new BasicCookieStore() : null; HttpClientBuilder httpClientBuilder; // Request interceptor for any request pre-processing logic HttpRequestInterceptor requestInterceptor; Map<String, String> additionalHttpHeaders = new HashMap<String, String>(); // Retrieve the additional HttpHeaders for (Map.Entry<String, String> entry : sessConfMap.entrySet()) { String key = entry.getKey(); if (key.startsWith(JdbcConnectionParams.HTTP_HEADER_PREFIX)) { additionalHttpHeaders.put(key.substring(JdbcConnectionParams.HTTP_HEADER_PREFIX.length()), entry.getValue());//from ww w.ja va 2 s. c om } } // Configure http client for kerberos/password based authentication if (isKerberosAuthMode()) { /** * Add an interceptor which sets the appropriate header in the request. * It does the kerberos authentication and get the final service ticket, * for sending to the server before every request. * In https mode, the entire information is encrypted */ requestInterceptor = new HttpKerberosRequestInterceptor( sessConfMap.get(JdbcConnectionParams.AUTH_PRINCIPAL), host, getServerHttpUrl(useSsl), assumeSubject, cookieStore, cookieName, useSsl, additionalHttpHeaders); } else { // Check for delegation token, if present add it in the header String tokenStr = getClientDelegationToken(sessConfMap); if (tokenStr != null) { requestInterceptor = new HttpTokenAuthInterceptor(tokenStr, cookieStore, cookieName, useSsl, additionalHttpHeaders); } else { /** * Add an interceptor to pass username/password in the header. * In https mode, the entire information is encrypted */ requestInterceptor = new HttpBasicAuthInterceptor(getUserName(), getPassword(), cookieStore, cookieName, useSsl, additionalHttpHeaders); } } // Configure http client for cookie based authentication if (isCookieEnabled) { // Create a http client with a retry mechanism when the server returns a status code of 401. httpClientBuilder = HttpClients.custom() .setServiceUnavailableRetryStrategy(new ServiceUnavailableRetryStrategy() { @Override public boolean retryRequest(final HttpResponse response, final int executionCount, final HttpContext context) { int statusCode = response.getStatusLine().getStatusCode(); boolean ret = statusCode == 401 && executionCount <= 1; // Set the context attribute to true which will be interpreted by the request // interceptor if (ret) { context.setAttribute(Utils.HIVE_SERVER2_RETRY_KEY, Utils.HIVE_SERVER2_RETRY_TRUE); } return ret; } @Override public long getRetryInterval() { // Immediate retry return 0; } }); } else { httpClientBuilder = HttpClientBuilder.create(); } // In case the server's idletimeout is set to a lower value, it might close it's side of // connection. However we retry one more time on NoHttpResponseException httpClientBuilder.setRetryHandler(new HttpRequestRetryHandler() { @Override public boolean retryRequest(IOException exception, int executionCount, HttpContext context) { if (executionCount > 1) { LOG.info("Retry attempts to connect to server exceeded."); return false; } if (exception instanceof org.apache.http.NoHttpResponseException) { LOG.info("Could not connect to the server. Retrying one more time."); return true; } return false; } }); // Add the request interceptor to the client builder httpClientBuilder.addInterceptorFirst(requestInterceptor); // Add an interceptor to add in an XSRF header httpClientBuilder.addInterceptorLast(new XsrfHttpRequestInterceptor()); // Configure http client for SSL if (useSsl) { String useTwoWaySSL = sessConfMap.get(JdbcConnectionParams.USE_TWO_WAY_SSL); String sslTrustStorePath = sessConfMap.get(JdbcConnectionParams.SSL_TRUST_STORE); String sslTrustStorePassword = sessConfMap.get(JdbcConnectionParams.SSL_TRUST_STORE_PASSWORD); KeyStore sslTrustStore; SSLConnectionSocketFactory socketFactory; SSLContext sslContext; /** * The code within the try block throws: SSLInitializationException, KeyStoreException, * IOException, NoSuchAlgorithmException, CertificateException, KeyManagementException & * UnrecoverableKeyException. We don't want the client to retry on any of these, * hence we catch all and throw a SQLException. */ try { if (useTwoWaySSL != null && useTwoWaySSL.equalsIgnoreCase(JdbcConnectionParams.TRUE)) { socketFactory = getTwoWaySSLSocketFactory(); } else if (sslTrustStorePath == null || sslTrustStorePath.isEmpty()) { // Create a default socket factory based on standard JSSE trust material socketFactory = SSLConnectionSocketFactory.getSocketFactory(); } else { // Pick trust store config from the given path sslTrustStore = KeyStore.getInstance(JdbcConnectionParams.SSL_TRUST_STORE_TYPE); try (FileInputStream fis = new FileInputStream(sslTrustStorePath)) { sslTrustStore.load(fis, sslTrustStorePassword.toCharArray()); } sslContext = SSLContexts.custom().loadTrustMaterial(sslTrustStore, null).build(); socketFactory = new SSLConnectionSocketFactory(sslContext, new DefaultHostnameVerifier(null)); } final Registry<ConnectionSocketFactory> registry = RegistryBuilder.<ConnectionSocketFactory>create() .register("https", socketFactory).build(); httpClientBuilder.setConnectionManager(new BasicHttpClientConnectionManager(registry)); } catch (Exception e) { String msg = "Could not create an https connection to " + jdbcUriString + ". " + e.getMessage(); throw new SQLException(msg, " 08S01", e); } } return httpClientBuilder.build(); }
From source file:org.apache.http.client.protocol.RequestAddCookies.java
public void process(final HttpRequest request, final HttpContext context) throws HttpException, IOException { Args.notNull(request, "HTTP request"); Args.notNull(context, "HTTP context"); final String method = request.getRequestLine().getMethod(); if (method.equalsIgnoreCase("CONNECT")) { return;//from w ww .j av a 2 s . co m } final HttpClientContext clientContext = HttpClientContext.adapt(context); // Obtain cookie store final CookieStore cookieStore = clientContext.getCookieStore(); if (cookieStore == null) { this.log.debug("Cookie store not specified in HTTP context"); return; } // Obtain the registry of cookie specs final Lookup<CookieSpecProvider> registry = clientContext.getCookieSpecRegistry(); if (registry == null) { this.log.debug("CookieSpec registry not specified in HTTP context"); return; } // Obtain the target host, possibly virtual (required) final HttpHost targetHost = clientContext.getTargetHost(); if (targetHost == null) { this.log.debug("Target host not set in the context"); return; } // Obtain the route (required) final RouteInfo route = clientContext.getHttpRoute(); if (route == null) { this.log.debug("Connection route not set in the context"); return; } final RequestConfig config = clientContext.getRequestConfig(); String policy = config.getCookieSpec(); if (policy == null) { policy = CookieSpecs.BEST_MATCH; } if (this.log.isDebugEnabled()) { this.log.debug("CookieSpec selected: " + policy); } URI requestURI = null; if (request instanceof HttpUriRequest) { requestURI = ((HttpUriRequest) request).getURI(); } else { try { requestURI = new URI(request.getRequestLine().getUri()); } catch (final URISyntaxException ignore) { } } final String path = requestURI != null ? requestURI.getPath() : null; final String hostName = targetHost.getHostName(); int port = targetHost.getPort(); if (port < 0) { port = route.getTargetHost().getPort(); } final CookieOrigin cookieOrigin = new CookieOrigin(hostName, port >= 0 ? port : 0, !TextUtils.isEmpty(path) ? path : "/", route.isSecure()); // Get an instance of the selected cookie policy final CookieSpecProvider provider = registry.lookup(policy); if (provider == null) { throw new HttpException("Unsupported cookie policy: " + policy); } final CookieSpec cookieSpec = provider.create(clientContext); // Get all cookies available in the HTTP state final List<Cookie> cookies = new ArrayList<Cookie>(cookieStore.getCookies()); // Find cookies matching the given origin final List<Cookie> matchedCookies = new ArrayList<Cookie>(); final Date now = new Date(); for (final Cookie cookie : cookies) { if (!cookie.isExpired(now)) { if (cookieSpec.match(cookie, cookieOrigin)) { if (this.log.isDebugEnabled()) { this.log.debug("Cookie " + cookie + " match " + cookieOrigin); } matchedCookies.add(cookie); } } else { if (this.log.isDebugEnabled()) { this.log.debug("Cookie " + cookie + " expired"); } } } // Generate Cookie request headers if (!matchedCookies.isEmpty()) { final List<Header> headers = cookieSpec.formatCookies(matchedCookies); for (final Header header : headers) { request.addHeader(header); } } final int ver = cookieSpec.getVersion(); if (ver > 0) { boolean needVersionHeader = false; for (final Cookie cookie : matchedCookies) { if (ver != cookie.getVersion() || !(cookie instanceof SetCookie2)) { needVersionHeader = true; } } if (needVersionHeader) { final Header header = cookieSpec.getVersionHeader(); if (header != null) { // Advertise cookie version support request.addHeader(header); } } } // Stick the CookieSpec and CookieOrigin instances to the HTTP context // so they could be obtained by the response interceptor context.setAttribute(HttpClientContext.COOKIE_SPEC, cookieSpec); context.setAttribute(HttpClientContext.COOKIE_ORIGIN, cookieOrigin); }
From source file:org.apache.http.client.protocol.ResponseAuthCache.java
public void process(final HttpResponse response, final HttpContext context) throws HttpException, IOException { Args.notNull(response, "HTTP request"); Args.notNull(context, "HTTP context"); AuthCache authCache = (AuthCache) context.getAttribute(ClientContext.AUTH_CACHE); HttpHost target = (HttpHost) context.getAttribute(ExecutionContext.HTTP_TARGET_HOST); final AuthState targetState = (AuthState) context.getAttribute(ClientContext.TARGET_AUTH_STATE); if (target != null && targetState != null) { if (this.log.isDebugEnabled()) { this.log.debug("Target auth state: " + targetState.getState()); }// ww w .ja v a2s. c o m if (isCachable(targetState)) { final SchemeRegistry schemeRegistry = (SchemeRegistry) context .getAttribute(ClientContext.SCHEME_REGISTRY); if (target.getPort() < 0) { final Scheme scheme = schemeRegistry.getScheme(target); target = new HttpHost(target.getHostName(), scheme.resolvePort(target.getPort()), target.getSchemeName()); } if (authCache == null) { authCache = new BasicAuthCache(); context.setAttribute(ClientContext.AUTH_CACHE, authCache); } switch (targetState.getState()) { case CHALLENGED: cache(authCache, target, targetState.getAuthScheme()); break; case FAILURE: uncache(authCache, target, targetState.getAuthScheme()); } } } final HttpHost proxy = (HttpHost) context.getAttribute(ExecutionContext.HTTP_PROXY_HOST); final AuthState proxyState = (AuthState) context.getAttribute(ClientContext.PROXY_AUTH_STATE); if (proxy != null && proxyState != null) { if (this.log.isDebugEnabled()) { this.log.debug("Proxy auth state: " + proxyState.getState()); } if (isCachable(proxyState)) { if (authCache == null) { authCache = new BasicAuthCache(); context.setAttribute(ClientContext.AUTH_CACHE, authCache); } switch (proxyState.getState()) { case CHALLENGED: cache(authCache, proxy, proxyState.getAuthScheme()); break; case FAILURE: uncache(authCache, proxy, proxyState.getAuthScheme()); } } } }