List of usage examples for org.apache.http.protocol HttpContext setAttribute
void setAttribute(String str, Object obj);
From source file:org.orbeon.oxf.resources.handler.HTTPURLConnection.java
public void connect() throws IOException { if (!connected) { final String userInfo = url.getUserInfo(); final boolean isAuthenticationRequestedWithUsername = username != null && !username.equals(""); // Create the HTTP client and HTTP context for the client (we expect this to be fairly lightweight) final DefaultHttpClient httpClient = new DefaultHttpClient(connectionManager, httpParams); final HttpContext httpContext = new BasicHttpContext(); // Set cookie store, creating a new one if none was provided to us if (cookieStore == null) cookieStore = new BasicCookieStore(); httpClient.setCookieStore(cookieStore); // Set proxy and host authentication if (proxyAuthState != null) httpContext.setAttribute(ClientContext.PROXY_AUTH_STATE, proxyAuthState); if (userInfo != null || isAuthenticationRequestedWithUsername) { // Make authentication preemptive; interceptor is added first, as the Authentication header is added // by HttpClient's RequestTargetAuthentication which is itself an interceptor, so our interceptor // needs to run before RequestTargetAuthentication, otherwise RequestTargetAuthentication won't find // the appropriate AuthState/AuthScheme/Credentials in the HttpContext // Don't add the interceptor if we don't want preemptive authentication! if (!"false".equals(preemptiveAuthentication)) { httpClient.addRequestInterceptor(preemptiveAuthHttpRequestInterceptor, 0); }//ww w.j av a2 s .c o m CredentialsProvider credentialsProvider = new BasicCredentialsProvider(); httpContext.setAttribute(ClientContext.CREDS_PROVIDER, credentialsProvider); final AuthScope authScope = new AuthScope(url.getHost(), url.getPort()); final Credentials credentials; if (userInfo != null) { // Set username and optional password specified on URL final int separatorPosition = userInfo.indexOf(":"); String username = separatorPosition == -1 ? userInfo : userInfo.substring(0, separatorPosition); String password = separatorPosition == -1 ? "" : userInfo.substring(separatorPosition + 1); // If the username/password contain special character, those character will be encoded, since we // are getting this from a URL. Now do the decoding. username = URLDecoder.decode(username, "utf-8"); password = URLDecoder.decode(password, "utf-8"); credentials = new UsernamePasswordCredentials(username, password); } else { // Set username and password specified externally credentials = domain == null ? new UsernamePasswordCredentials(username, password == null ? "" : password) : new NTCredentials(username, password, url.getHost(), domain); } credentialsProvider.setCredentials(authScope, credentials); } // If method has not been set, use GET // This can happen e.g. when this connection handler is used from URLFactory if (method == null) setRequestMethod("GET"); // Set all headers, final boolean skipAuthorizationHeader = userInfo != null || username != null; for (final Map.Entry<String, String[]> currentEntry : requestProperties.entrySet()) { final String currentHeaderName = currentEntry.getKey(); final String[] currentHeaderValues = currentEntry.getValue(); for (final String currentHeaderValue : currentHeaderValues) { // Skip over Authorization header if user authentication specified if (skipAuthorizationHeader && currentHeaderName.toLowerCase() .equals(Connection.AUTHORIZATION_HEADER.toLowerCase())) continue; method.addHeader(currentHeaderName, currentHeaderValue); } } // Create request entity with body if (method instanceof HttpEntityEnclosingRequest) { // Use the body that was set directly, or the result of writing to the OutputStream final byte[] body = (requestBody != null) ? requestBody : (os != null) ? os.toByteArray() : null; if (body != null) { final Header contentTypeHeader = method.getFirstHeader("Content-Type"); // Header names are case-insensitive for comparison if (contentTypeHeader == null) throw new ProtocolException("Can't set request entity: Content-Type header is missing"); final ByteArrayEntity byteArrayEntity = new ByteArrayEntity(body); byteArrayEntity.setContentType(contentTypeHeader); ((HttpEntityEnclosingRequest) method).setEntity(byteArrayEntity); } } // Make request httpResponse = httpClient.execute(method, httpContext); connected = true; } }
From source file:org.lightcouch.CouchDbClientBase.java
/** * @return {@link DefaultHttpClient} instance. *//*from w w w.java2 s. com*/ private HttpClient createHttpClient(CouchDbProperties props) { DefaultHttpClient httpclient = null; try { SchemeSocketFactory ssf = null; if (props.getProtocol().equals("https")) { TrustManager trustManager = new X509TrustManager() { public void checkClientTrusted(X509Certificate[] chain, String authType) throws CertificateException { } public void checkServerTrusted(X509Certificate[] chain, String authType) throws CertificateException { } public X509Certificate[] getAcceptedIssuers() { return null; } }; SSLContext sslcontext = SSLContext.getInstance("TLS"); sslcontext.init(null, new TrustManager[] { trustManager }, null); ssf = new SSLSocketFactory(sslcontext, SSLSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER); SSLSocket socket = (SSLSocket) ssf.createSocket(null); socket.setEnabledCipherSuites(new String[] { "SSL_RSA_WITH_RC4_128_MD5" }); } else { ssf = PlainSocketFactory.getSocketFactory(); } SchemeRegistry schemeRegistry = new SchemeRegistry(); schemeRegistry.register(new Scheme(props.getProtocol(), props.getPort(), ssf)); PoolingClientConnectionManager ccm = new PoolingClientConnectionManager(schemeRegistry); httpclient = new DefaultHttpClient(ccm); host = new HttpHost(props.getHost(), props.getPort(), props.getProtocol()); context = new BasicHttpContext(); // Http params httpclient.getParams().setParameter(CoreProtocolPNames.HTTP_CONTENT_CHARSET, "UTF-8"); httpclient.getParams().setParameter(CoreConnectionPNames.SO_TIMEOUT, props.getSocketTimeout()); httpclient.getParams().setParameter(CoreConnectionPNames.CONNECTION_TIMEOUT, props.getConnectionTimeout()); int maxConnections = props.getMaxConnections(); if (maxConnections != 0) { ccm.setMaxTotal(maxConnections); ccm.setDefaultMaxPerRoute(maxConnections); } if (props.getProxyHost() != null) { HttpHost proxy = new HttpHost(props.getProxyHost(), props.getProxyPort()); httpclient.getParams().setParameter(ConnRoutePNames.DEFAULT_PROXY, proxy); } // basic authentication if (props.getUsername() != null && props.getPassword() != null) { httpclient.getCredentialsProvider().setCredentials(new AuthScope(props.getHost(), props.getPort()), new UsernamePasswordCredentials(props.getUsername(), props.getPassword())); props.clearPassword(); AuthCache authCache = new BasicAuthCache(); BasicScheme basicAuth = new BasicScheme(); authCache.put(host, basicAuth); context.setAttribute(ClientContext.AUTH_CACHE, authCache); } // request interceptor httpclient.addRequestInterceptor(new HttpRequestInterceptor() { public void process(final HttpRequest request, final HttpContext context) throws IOException { if (log.isInfoEnabled()) log.info(">> " + request.getRequestLine()); } }); // response interceptor httpclient.addResponseInterceptor(new HttpResponseInterceptor() { public void process(final HttpResponse response, final HttpContext context) throws IOException { validate(response); if (log.isInfoEnabled()) log.info("<< Status: " + response.getStatusLine().getStatusCode()); } }); } catch (Exception e) { log.error("Error Creating HTTP client. " + e.getMessage()); throw new IllegalStateException(e); } return httpclient; }
From source file:com.soundcloud.playerapi.ApiWrapper.java
/** @return The HttpClient instance used to make the calls */ public HttpClient getHttpClient() { if (httpClient == null) { final HttpParams params = getParams(); HttpClientParams.setRedirecting(params, false); HttpProtocolParams.setUserAgent(params, getUserAgent()); final SchemeRegistry registry = new SchemeRegistry(); registry.register(new Scheme("http", getSocketFactory(), 80)); final SSLSocketFactory sslFactory = getSSLSocketFactory(); registry.register(new Scheme("https", sslFactory, 443)); httpClient = new DefaultHttpClient(new ThreadSafeClientConnManager(params, registry), params) { {//from w w w . j a v a 2s. co m setKeepAliveStrategy(new ConnectionKeepAliveStrategy() { @Override public long getKeepAliveDuration(HttpResponse httpResponse, HttpContext httpContext) { return KEEPALIVE_TIMEOUT; } }); getCredentialsProvider().setCredentials( new AuthScope(AuthScope.ANY_HOST, AuthScope.ANY_PORT, CloudAPI.REALM, OAUTH_SCHEME), OAuth2Scheme.EmptyCredentials.INSTANCE); getAuthSchemes().register(CloudAPI.OAUTH_SCHEME, new OAuth2Scheme.Factory(ApiWrapper.this)); addResponseInterceptor(new HttpResponseInterceptor() { @Override public void process(HttpResponse response, HttpContext context) throws HttpException, IOException { if (response == null || response.getEntity() == null) return; HttpEntity entity = response.getEntity(); Header header = entity.getContentEncoding(); if (header != null) { for (HeaderElement codec : header.getElements()) { if (codec.getName().equalsIgnoreCase("gzip")) { response.setEntity(new GzipDecompressingEntity(entity)); break; } } } } }); } @Override protected HttpContext createHttpContext() { HttpContext ctxt = super.createHttpContext(); ctxt.setAttribute(ClientContext.AUTH_SCHEME_PREF, Arrays.asList(CloudAPI.OAUTH_SCHEME, "digest", "basic")); return ctxt; } @Override protected BasicHttpProcessor createHttpProcessor() { BasicHttpProcessor processor = super.createHttpProcessor(); processor.addInterceptor(new OAuth2HttpRequestInterceptor()); return processor; } // for testability only @Override protected RequestDirector createClientRequestDirector(HttpRequestExecutor requestExec, ClientConnectionManager conman, ConnectionReuseStrategy reustrat, ConnectionKeepAliveStrategy kastrat, HttpRoutePlanner rouplan, HttpProcessor httpProcessor, HttpRequestRetryHandler retryHandler, RedirectHandler redirectHandler, AuthenticationHandler targetAuthHandler, AuthenticationHandler proxyAuthHandler, UserTokenHandler stateHandler, HttpParams params) { return getRequestDirector(requestExec, conman, reustrat, kastrat, rouplan, httpProcessor, retryHandler, redirectHandler, targetAuthHandler, proxyAuthHandler, stateHandler, params); } }; } return httpClient; }
From source file:org.apache.synapse.transport.nhttp.ServerWorker.java
/** * Create an Axis2 message context for the given http request. The request may be in the * process of being streamed//ww w . j a va 2 s . co m * @param request the http request to be used to create the corresponding Axis2 message context * @return the Axis2 message context created */ private MessageContext createMessageContext(HttpRequest request) { MessageContext msgContext = new MessageContext(); msgContext.setMessageID(UIDGenerator.generateURNString()); // There is a discrepency in what I thought, Axis2 spawns a new threads to // send a message if this is TRUE - and I want it to be the other way msgContext.setProperty(MessageContext.CLIENT_API_NON_BLOCKING, Boolean.FALSE); msgContext.setConfigurationContext(cfgCtx); if ("https".equalsIgnoreCase(schemeName)) { msgContext.setTransportOut(cfgCtx.getAxisConfiguration().getTransportOut(Constants.TRANSPORT_HTTPS)); msgContext.setTransportIn(cfgCtx.getAxisConfiguration().getTransportIn(Constants.TRANSPORT_HTTPS)); msgContext.setIncomingTransportName(Constants.TRANSPORT_HTTPS); SSLIOSession session = (SSLIOSession) (conn.getContext()).getAttribute(SSLIOSession.SESSION_KEY); //set SSL certificates to message context if SSLVerifyClient parameter is set if (session != null && msgContext.getTransportIn() != null && msgContext.getTransportIn().getParameter(NhttpConstants.SSL_VERIFY_CLIENT) != null) { try { msgContext.setProperty(NhttpConstants.SSL_CLIENT_AUTH_CERT_X509, session.getSSLSession().getPeerCertificateChain()); } catch (SSLPeerUnverifiedException e) { //Peer Certificate Chain may not be available always.(in case of verify client is optional) if (log.isTraceEnabled()) { log.trace("Peer certificate chain is not available for MsgContext " + msgContext.getMessageID()); } } } } else { msgContext.setTransportOut(cfgCtx.getAxisConfiguration().getTransportOut(Constants.TRANSPORT_HTTP)); msgContext.setTransportIn(cfgCtx.getAxisConfiguration().getTransportIn(Constants.TRANSPORT_HTTP)); msgContext.setIncomingTransportName(Constants.TRANSPORT_HTTP); } msgContext.setProperty(Constants.OUT_TRANSPORT_INFO, this); // the following statement causes the soap session services to be failing - ruwan // msgContext.setServiceGroupContextId(UUIDGenerator.getUUID()); msgContext.setServerSide(true); msgContext.setProperty(Constants.Configuration.TRANSPORT_IN_URL, request.getRequestLine().getUri()); // http transport header names are case insensitive Map<String, String> headers = new TreeMap<String, String>(new Comparator<String>() { public int compare(String o1, String o2) { return o1.compareToIgnoreCase(o2); } }); for (Header header : request.getAllHeaders()) { String headerName = header.getName(); // if this header is already added if (headers.containsKey(headerName)) { /* this is a multi-value header */ // generate the key String key = NhttpConstants.EXCESS_TRANSPORT_HEADERS; // get the old value String oldValue = headers.get(headerName); // adds additional values to a list in a property of message context Map map; if (msgContext.getProperty(key) != null) { map = (Map) msgContext.getProperty(key); map.put(headerName, oldValue); } else { map = new MultiValueMap(); map.put(headerName, oldValue); // set as a property in message context msgContext.setProperty(key, map); } } headers.put(header.getName(), header.getValue()); } msgContext.setProperty(MessageContext.TRANSPORT_HEADERS, headers); // find the remote party IP address and set it to the message context if (conn instanceof HttpInetConnection) { HttpContext httpContext = conn.getContext(); HttpInetConnection inetConn = (HttpInetConnection) conn; InetAddress remoteAddr = inetConn.getRemoteAddress(); if (remoteAddr != null) { httpContext.setAttribute(NhttpConstants.CLIENT_REMOTE_ADDR, remoteAddr); httpContext.setAttribute(NhttpConstants.CLIENT_REMOTE_PORT, inetConn.getRemotePort()); msgContext.setProperty(MessageContext.REMOTE_ADDR, remoteAddr.getHostAddress()); msgContext.setProperty(NhttpConstants.REMOTE_HOST, NhttpUtil.getHostName(remoteAddr)); remoteAddress = remoteAddr.getHostAddress(); } } msgContext.setProperty(RequestResponseTransport.TRANSPORT_CONTROL, new HttpCoreRequestResponseTransport(msgContext)); msgContext.setProperty(ServerHandler.SERVER_CONNECTION_DEBUG, conn.getContext().getAttribute(ServerHandler.SERVER_CONNECTION_DEBUG)); msgContext.setProperty(NhttpConstants.NHTTP_INPUT_STREAM, is); msgContext.setProperty(NhttpConstants.NHTTP_OUTPUT_STREAM, os); return msgContext; }
From source file:com.googlecode.jdeltasync.DeltaSyncClient.java
private <T> T post(final IDeltaSyncSession session, String uri, final String userAgent, final String contentType, final byte[] data, final UriCapturingResponseHandler<T> handler) throws DeltaSyncException, IOException { final HttpPost post = createHttpPost(uri, userAgent, contentType, data); final HttpContext context = new BasicHttpContext(); context.setAttribute(HttpClientContext.COOKIE_STORE, session.getCookieStore()); try {/*from ww w . j av a 2s .c o m*/ return httpClient.execute(post, new ResponseHandler<T>() { public T handleResponse(HttpResponse response) throws ClientProtocolException, IOException { try { if (isRedirect(response)) { URI redirectUri = getRedirectLocationURI(session, post, response, context); return post(session, redirectUri.toString(), userAgent, contentType, data, handler); } if (response.getStatusLine().getStatusCode() != HttpStatus.SC_OK) { throw new HttpException(response.getStatusLine().getStatusCode(), response.getStatusLine().getReasonPhrase()); } HttpRequest request = (HttpRequest) context.getAttribute(HttpCoreContext.HTTP_REQUEST); HttpHost host = (HttpHost) context.getAttribute(HttpCoreContext.HTTP_TARGET_HOST); URI uri; try { if (request instanceof HttpUriRequest) { uri = ((HttpUriRequest) request).getURI(); } else { uri = new URI(request.getRequestLine().getUri()); } if (!uri.isAbsolute()) { uri = URIUtils.rewriteURI(uri, host); } } catch (URISyntaxException e) { throw new DeltaSyncException(e); } return handler.handle(uri, response); } catch (DeltaSyncException e) { throw new RuntimeException(e); } } }, context); } catch (RuntimeException e) { Throwable t = e.getCause(); while (t != null) { if (t instanceof DeltaSyncException) { throw (DeltaSyncException) t; } t = t.getCause(); } throw e; } }
From source file:com.farmafene.commons.cas.URLAuthenticationHandler.java
/** * {@inheritDoc}/*from w ww . j a va 2 s . c o m*/ * * @see org.jasig.cas.authentication.handler.support.AbstractUsernamePasswordAuthenticationHandler#authenticateUsernamePasswordInternal(org.jasig.cas.authentication.principal.UsernamePasswordCredentials) */ @Override protected boolean authenticateUsernamePasswordInternal(UsernamePasswordCredentials credentials) throws AuthenticationException { long initTime = System.currentTimeMillis(); boolean authenticateUsernamePasswordInternal = false; HttpContext context = new BasicHttpContext(); HttpClientFactory f = new HttpClientFactory(); f.setLoginURL(loginURL); f.setProxyHost(proxyHost); f.setProxyPort(proxyPort); DefaultHttpClient httpClient = f.getClient(); CredentialsProvider credsProvider = new BasicCredentialsProvider(); org.apache.http.auth.UsernamePasswordCredentials cred = new org.apache.http.auth.UsernamePasswordCredentials( credentials.getUsername(), credentials.getPassword()); credsProvider.setCredentials(AuthScope.ANY, cred); List<String> n = new ArrayList<String>(); n.add(AuthPolicy.BASIC); n.add(AuthPolicy.DIGEST); httpClient.getParams().setParameter(AuthPNames.TARGET_AUTH_PREF, n); context.setAttribute(ClientContext.CREDS_PROVIDER, credsProvider); HttpGet httpGet = new HttpGet(loginURL); HttpResponse httpResponse = null; try { httpResponse = httpClient.execute(httpGet, context); if (httpResponse.getStatusLine().getStatusCode() == 200) { authenticateUsernamePasswordInternal = true; } } catch (ClientProtocolException e) { logger.error("Error: ", e); } catch (IOException e) { logger.error("Error: ", e); } if (logger.isDebugEnabled()) { logger.debug("Total time: " + (System.currentTimeMillis() - initTime) + " ms, " + this); } return authenticateUsernamePasswordInternal; }
From source file:com.unboundid.scim.sdk.PreemptiveAuthInterceptor.java
/** * {@inheritDoc}//from ww w . j av a 2 s. c o m */ @Override public void process(final HttpRequest request, final HttpContext context) throws HttpException, IOException { HttpHost target = (HttpHost) context.getAttribute(ExecutionContext.HTTP_TARGET_HOST); if (target.getPort() < 0) { SchemeRegistry schemeRegistry = (SchemeRegistry) context.getAttribute(ClientContext.SCHEME_REGISTRY); Scheme scheme = schemeRegistry.getScheme(target); target = new HttpHost(target.getHostName(), scheme.resolvePort(target.getPort()), target.getSchemeName()); } AuthCache authCache = (AuthCache) context.getAttribute(ClientContext.AUTH_CACHE); if (authCache == null) { authCache = new BasicAuthCache(); BasicScheme basicAuth = new BasicScheme(); authCache.put(target, basicAuth); context.setAttribute(ClientContext.AUTH_CACHE, authCache); return; } CredentialsProvider credsProvider = (CredentialsProvider) context .getAttribute(ClientContext.CREDS_PROVIDER); if (credsProvider == null) { return; } final AuthState targetState = (AuthState) context.getAttribute(ClientContext.TARGET_AUTH_STATE); if (targetState != null && targetState.getState() == AuthProtocolState.UNCHALLENGED) { final AuthScheme authScheme = authCache.get(target); if (authScheme != null) { doPreemptiveAuth(target, authScheme, targetState, credsProvider); } } 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 && proxyState.getState() == AuthProtocolState.UNCHALLENGED) { final AuthScheme authScheme = authCache.get(proxy); if (authScheme != null) { doPreemptiveAuth(proxy, authScheme, proxyState, credsProvider); } } }
From source file:org.apache.axis2.transport.http.server.RequestSessionCookie.java
public void process(final HttpRequest request, final HttpContext context) throws HttpException, IOException { if (request == null) { throw new IllegalArgumentException("HTTP request may not be null"); }/* ww w .j a va 2s .c o m*/ if (context == null) { throw new IllegalArgumentException("HTTP context may not be null"); } String sessionCookie = null; Header[] headers = request.getHeaders(HTTPConstants.HEADER_COOKIE); for (int i = 0; i < headers.length; i++) { HeaderElement[] elements = headers[i].getElements(); for (int e = 0; e < elements.length; e++) { HeaderElement element = elements[e]; if (Constants.SESSION_COOKIE.equalsIgnoreCase(element.getName()) || Constants.SESSION_COOKIE_JSESSIONID.equalsIgnoreCase(element.getName())) { sessionCookie = element.getValue(); } } } context.setAttribute(HTTPConstants.COOKIE_STRING, sessionCookie); }
From source file:org.wso2.carbon.apimgt.impl.publishers.WSO2APIPublisher.java
public boolean isAPIAvailable(API api, APIStore store) throws APIManagementException { boolean available = false; if (store.getEndpoint() == null || store.getUsername() == null || store.getPassword() == null) { String msg = "External APIStore endpoint URL or credentials are not defined. " + "Cannot proceed with checking API availability from the APIStore - " + store.getDisplayName(); throw new APIManagementException(msg); } else {/*from w w w.j a v a2 s.c o m*/ CookieStore cookieStore = new BasicCookieStore(); HttpContext httpContext = new BasicHttpContext(); httpContext.setAttribute(ClientContext.COOKIE_STORE, cookieStore); boolean authenticated = authenticateAPIM(store, httpContext); if (authenticated) { available = isAPIAvailableInWSO2Store(api, store.getUsername(), store.getEndpoint(), httpContext); logoutFromExternalStore(store, httpContext); } return available; } }