List of usage examples for org.apache.http.protocol HttpContext getAttribute
Object getAttribute(String str);
From source file:fr.ippon.wip.http.hc.HttpClientExecutor.java
private void manageAuthentification(PortletRequest portletRequest, HttpContext context, HttpResponse httpResponse) {/*from w ww . j a v a2s . co m*/ // Check if authentication is requested by remote host PortletWindow portletWindow = PortletWindow.getInstance(portletRequest); int statusCode = httpResponse.getStatusLine().getStatusCode(); // TODO: process proxy auth requests HttpStatus.SC_PROXY_AUTHENTICATION_REQUIRED (407) ? // TODO: also needs a custom implementation of RoutePlanner to select proxy per-application ? List<String> schemes = null; if (statusCode == HttpStatus.SC_UNAUTHORIZED) { // Check what authentication scheme are required schemes = new ArrayList<String>(); for (Header authHeader : httpResponse.getHeaders(HttpHeaders.WWW_AUTHENTICATE)) { String headerValue = authHeader.getValue(); schemes.add(headerValue.split(" ")[0]); } } portletWindow.setRequestedAuthSchemes(schemes); // Updates authentication state AuthState authState = (AuthState) context.getAttribute(ClientContext.TARGET_AUTH_STATE); portletWindow.setAuthenticated(authState != null && authState.getCredentials() != null); }
From source file:com.mxhero.plugin.cloudstorage.onedrive.api.command.HttpRequestRetryHandler.java
@Override public boolean retryRequest(IOException exception, int executionCount, HttpContext context) { if (executionCount >= retries) { logger.debug("no more retries, cancel"); return false; }// ww w . ja v a 2 s . c o m if (exception instanceof NoHttpResponseException) { logger.debug("is NoHttpResponseException, retrying..."); return true; } if (exception instanceof ConnectTimeoutException || exception instanceof ConnectionPoolTimeoutException) { logger.debug("is ConnectTimeoutException or ConnectionPoolTimeoutException, retrying..."); return true; } if (exception instanceof InterruptedIOException) { logger.debug("is InterruptedIOException, retrying..."); return true; } if (exception instanceof UnknownHostException) { logger.debug("is UnknownHostException, cancel"); return false; } if (exception instanceof ConnectException) { logger.debug("is ConnectException, cancel"); return false; } if (exception instanceof SSLException) { logger.debug("is SSLException, cancel"); return false; } HttpRequest request = (HttpRequest) context.getAttribute(HttpCoreContext.HTTP_REQUEST); boolean idempotent = !(request instanceof HttpEntityEnclosingRequest); if (idempotent) { logger.debug("is idempotent, retrying..."); return true; } Boolean b = (Boolean) context.getAttribute(HttpCoreContext.HTTP_REQ_SENT); boolean sent = (b != null && b.booleanValue()); if (!sent) { logger.debug("is not sent, retrying..."); return true; } return false; }
From source file:com.grendelscan.commons.http.apache_overrides.client.CustomClientRequestDirector.java
@Override public HttpResponse execute(HttpHost originalTarget, final HttpRequest request, HttpContext context) throws HttpException, IOException { HttpHost target = originalTarget;/*w ww . j a v a 2 s . co m*/ final HttpRoute route = determineRoute(target, request, context); virtualHost = (HttpHost) request.getParams().getParameter(ClientPNames.VIRTUAL_HOST); long timeout = ConnManagerParams.getTimeout(params); try { HttpResponse 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 (request instanceof AbortableHttpRequest) { ((AbortableHttpRequest) request).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()) { LOGGER.debug("Stale connection check"); if (managedConn.isStale()) { LOGGER.debug("Stale connection detected"); managedConn.close(); } } } } if (request instanceof AbortableHttpRequest) { ((AbortableHttpRequest) request).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) { LOGGER.debug(ex.getMessage()); response = ex.getResponse(); } // 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(request, httpProcessor, context); try { response = requestExec.execute(request, managedConn, context); } catch (IOException ex) { LOGGER.debug("Closing connection after request failure."); managedConn.close(); throw ex; } if (response == null) { return null; } // 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. boolean 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 (duration >= 0) { LOGGER.trace("Connection can be kept alive for " + duration + " ms"); } else { LOGGER.trace("Connection can be kept alive indefinitely"); } } if ((managedConn != null) && (userToken == null)) { userToken = userTokenHandler.getUserToken(context); context.setAttribute(ClientContext.USER_TOKEN, userToken); if (userToken != null) { managedConn.setState(userToken); } } // check for entity, release connection if possible if ((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.ellis.yun.search.test.httpclient.HttpClientTest.java
@Test public void testKeepAliveTime() throws Exception { DefaultHttpClient httpclient = new DefaultHttpClient(); // httpContext ?httpClienthttp? HttpContext httpContext = new BasicHttpContext(); HttpGet httpGet = new HttpGet("http://www.baidu.com"); httpclient.setKeepAliveStrategy(new ConnectionKeepAliveStrategy() { public long getKeepAliveDuration(HttpResponse response, HttpContext context) { // ?Keep-Alive? HeaderIterator hit = response.headerIterator(HTTP.CONN_KEEP_ALIVE); HeaderElementIterator it = new BasicHeaderElementIterator(hit); while (it.hasNext()) { HeaderElement element = it.nextElement(); String name = element.getName(); String value = element.getValue(); if ("timeout".equalsIgnoreCase(name) && !StringUtils.isBlank(value)) { return Long.parseLong(value) * 1000; }// ww w. j av a 2 s . com } HttpHost target = (HttpHost) context.getAttribute(ExecutionContext.HTTP_TARGET_HOST); if ("www.baidu.com".equalsIgnoreCase(target.getHostName())) { // ???5 return 5 * 1000; } else { // ???30 return 30 * 1000; } } }); HttpResponse response = httpclient.execute(httpGet, httpContext); String content = parseEntity(response.getEntity()); System.out.println(content); System.out.println("=============================================\n"); // ?Keep-Alive? HeaderIterator hit = response.headerIterator(); HeaderElementIterator it = new BasicHeaderElementIterator(hit); while (it.hasNext()) { HeaderElement element = it.nextElement(); String name = element.getName(); String value = element.getValue(); System.out.println(" ==> " + name + " >> " + value); } }
From source file:com.cloud.api.ApiServer.java
@SuppressWarnings({ "unchecked", "rawtypes" }) @Override/*from w ww. j a v a 2s . co m*/ public void handle(HttpRequest request, HttpResponse response, HttpContext context) throws HttpException, IOException { // get some information for the access log... StringBuffer sb = new StringBuffer(); HttpServerConnection connObj = (HttpServerConnection) context.getAttribute("http.connection"); if (connObj instanceof SocketHttpServerConnection) { InetAddress remoteAddr = ((SocketHttpServerConnection) connObj).getRemoteAddress(); sb.append(remoteAddr.toString() + " -- "); } sb.append(request.getRequestLine()); try { String uri = request.getRequestLine().getUri(); int requestParamsStartIndex = uri.indexOf('?'); if (requestParamsStartIndex >= 0) { uri = uri.substring(requestParamsStartIndex + 1); } String[] paramArray = uri.split("&"); if (paramArray.length < 1) { s_logger.info("no parameters received for request: " + uri + ", aborting..."); return; } Map parameterMap = new HashMap<String, String[]>(); String responseType = BaseCmd.RESPONSE_TYPE_XML; for (String paramEntry : paramArray) { String[] paramValue = paramEntry.split("="); if (paramValue.length != 2) { s_logger.info("malformed parameter: " + paramEntry + ", skipping"); continue; } if ("response".equalsIgnoreCase(paramValue[0])) { responseType = paramValue[1]; } else { // according to the servlet spec, the parameter map should be in the form (name=String, // value=String[]), so // parameter values will be stored in an array parameterMap.put(/* name */paramValue[0], /* value */new String[] { paramValue[1] }); } } try { // always trust commands from API port, user context will always be UID_SYSTEM/ACCOUNT_ID_SYSTEM UserContext.registerContext(_systemUser.getId(), _systemAccount, null, true); sb.insert(0, "(userId=" + User.UID_SYSTEM + " accountId=" + Account.ACCOUNT_ID_SYSTEM + " sessionId=" + null + ") "); String responseText = handleRequest(parameterMap, true, responseType, sb); sb.append(" 200 " + ((responseText == null) ? 0 : responseText.length())); writeResponse(response, responseText, HttpStatus.SC_OK, responseType, null); } catch (ServerApiException se) { String responseText = getSerializedApiError(se.getErrorCode(), se.getDescription(), parameterMap, responseType, se); writeResponse(response, responseText, se.getErrorCode(), responseType, se.getDescription()); sb.append(" " + se.getErrorCode() + " " + se.getDescription()); } catch (RuntimeException e) { // log runtime exception like NullPointerException to help identify the source easier s_logger.error("Unhandled exception, ", e); throw e; } } finally { s_accessLogger.info(sb.toString()); UserContext.unregisterContext(); } }
From source file:org.apache.synapse.transport.nhttp.ClientHandler.java
private MessageContext getMessageContext(final NHttpClientConnection conn) { HttpContext context = conn.getContext(); Axis2HttpRequest axis2Req = (Axis2HttpRequest) context.getAttribute(AXIS2_HTTP_REQUEST); if (axis2Req != null) { return axis2Req.getMsgContext(); }/*from w w w.ja v a 2 s .c o m*/ return null; }
From source file:org.openiot.gsn.http.rest.PushRemoteWrapper.java
public DataField[] registerAndGetStructure() throws IOException, ClassNotFoundException { // Create the POST request HttpPost httpPost = new HttpPost(initParams.getRemoteContactPointEncoded(lastReceivedTimestamp)); // Add the POST parameters httpPost.setEntity(new UrlEncodedFormEntity(postParameters, HTTP.UTF_8)); ///*from w w w . java2 s. c o m*/ httpPost.getParams().setParameter(CoreProtocolPNames.USE_EXPECT_CONTINUE, Boolean.FALSE); // Create local execution context HttpContext localContext = new BasicHttpContext(); // NotificationRegistry.getInstance().addNotification(uid, this); int tries = 0; AuthState authState = null; // while (tries < 2) { tries++; HttpResponse response = null; try { // Execute the POST request response = httpclient.execute(httpPost, localContext); // int sc = response.getStatusLine().getStatusCode(); // if (sc == HttpStatus.SC_OK) { logger.debug(new StringBuilder().append("Wants to consume the structure packet from ") .append(initParams.getRemoteContactPoint())); structure = (DataField[]) XSTREAM.fromXML(response.getEntity().getContent()); logger.debug("Connection established for: " + initParams.getRemoteContactPoint()); break; } else { if (sc == HttpStatus.SC_UNAUTHORIZED) authState = (AuthState) localContext.getAttribute(ClientContext.TARGET_AUTH_STATE); // Target host authentication required else if (sc == HttpStatus.SC_PROXY_AUTHENTICATION_REQUIRED) authState = (AuthState) localContext.getAttribute(ClientContext.PROXY_AUTH_STATE); // Proxy authentication required else { logger.error(new StringBuilder().append("Unexpected POST status code returned: ").append(sc) .append("\nreason: ").append(response.getStatusLine().getReasonPhrase())); } if (authState != null) { if (initParams.getUsername() == null || (tries > 1 && initParams.getUsername() != null)) { logger.error("A valid username/password required to connect to the remote host: " + initParams.getRemoteContactPoint()); } else { AuthScope authScope = authState.getAuthScope(); logger.warn(new StringBuilder().append("Setting Credentials for host: ") .append(authScope.getHost()).append(":").append(authScope.getPort())); Credentials creds = new UsernamePasswordCredentials(initParams.getUsername(), initParams.getPassword()); httpclient.getCredentialsProvider().setCredentials(authScope, creds); } } } } catch (RuntimeException ex) { // In case of an unexpected exception you may want to abort // the HTTP request in order to shut down the underlying // connection and release it back to the connection manager. logger.warn("Aborting the HTTP POST request."); httpPost.abort(); throw ex; } finally { if (response != null && response.getEntity() != null) { response.getEntity().consumeContent(); } } } if (structure == null) throw new RuntimeException("Cannot connect to the remote host."); return structure; }
From source file:github.daneren2005.dsub.service.RESTMusicService.java
private void detectRedirect(String originalUrl, Context context, HttpContext httpContext) { HttpUriRequest request = (HttpUriRequest) httpContext.getAttribute(ExecutionContext.HTTP_REQUEST); HttpHost host = (HttpHost) httpContext.getAttribute(ExecutionContext.HTTP_TARGET_HOST); // Sometimes the request doesn't contain the "http://host" part String redirectedUrl;/*from www . j a v a 2 s . c om*/ if (request.getURI().getScheme() == null) { redirectedUrl = host.toURI() + request.getURI(); } else { redirectedUrl = request.getURI().toString(); } redirectFrom = originalUrl.substring(0, originalUrl.indexOf("/rest/")); redirectTo = redirectedUrl.substring(0, redirectedUrl.indexOf("/rest/")); if (redirectFrom.compareTo(redirectTo) != 0) { Log.i(TAG, redirectFrom + " redirects to " + redirectTo); } redirectionLastChecked = System.currentTimeMillis(); redirectionNetworkType = getCurrentNetworkType(context); }
From source file:org.apache.synapse.transport.nhttp.ClientHandler.java
/** * Handle IO errors while reading or writing to underlying channels * //from www . ja va 2 s. co m * @param conn the connection being processed * @param ex the exception encountered */ public void exception(final NHttpClientConnection conn, final Exception ex) { HttpContext context = conn.getContext(); Axis2HttpRequest axis2Req = (Axis2HttpRequest) context.getAttribute(ATTACHMENT_KEY); context.setAttribute(AXIS2_HTTP_REQUEST, axis2Req); if (ex instanceof HttpException) { String message = getErrorMessage("HTTP protocol violation : " + ex.getMessage(), conn); log.error(message, ex); checkAxisRequestComplete(conn, NhttpConstants.PROTOCOL_VIOLATION, message, ex); shutdownConnection(conn, true, "HTTP protocol violation : " + ex.getMessage()); } if (ex instanceof IOException) { String message = getErrorMessage("I/O error : " + ex.getMessage(), conn); if (message.toLowerCase().indexOf("reset") != -1) { log.warn(message); } else { log.error(message, ex); } checkAxisRequestComplete(conn, NhttpConstants.SND_IO_ERROR_SENDING, message, ex); shutdownConnection(conn, true, "I/O error : " + ex.getMessage()); } else { log.error(ex.getMessage(), ex); shutdownConnection(conn, true, "Error occurred : " + ex.getMessage()); } }