List of usage examples for org.apache.http.client.protocol HttpClientContext setAuthSchemeRegistry
public void setAuthSchemeRegistry(final Lookup<AuthSchemeProvider> lookup)
From source file:org.apache.calcite.avatica.remote.AvaticaCommonsHttpClientSpnegoImpl.java
@Override public byte[] send(byte[] request) { HttpClientContext context = HttpClientContext.create(); context.setTargetHost(host);// www.j av a2 s. co m context.setCredentialsProvider(credentialsProvider); context.setAuthSchemeRegistry(authRegistry); context.setAuthCache(authCache); ByteArrayEntity entity = new ByteArrayEntity(request, ContentType.APPLICATION_OCTET_STREAM); // Create the client with the AuthSchemeRegistry and manager HttpPost post = new HttpPost(toURI(url)); post.setEntity(entity); try (CloseableHttpResponse response = client.execute(post, context)) { final int statusCode = response.getStatusLine().getStatusCode(); if (HttpURLConnection.HTTP_OK == statusCode || HttpURLConnection.HTTP_INTERNAL_ERROR == statusCode) { return EntityUtils.toByteArray(response.getEntity()); } throw new RuntimeException("Failed to execute HTTP Request, got HTTP/" + statusCode); } catch (RuntimeException e) { throw e; } catch (Exception e) { LOG.debug("Failed to execute HTTP request", e); throw new RuntimeException(e); } }
From source file:com.teradata.tempto.internal.hadoop.hdfs.SpnegoHttpRequestsExecutor.java
private HttpContext createSpnegoAwareHttpContext() { HttpClientContext httpContext = HttpClientContext.create(); Lookup<AuthSchemeProvider> authSchemeRegistry = RegistryBuilder.<AuthSchemeProvider>create() .register(AuthSchemes.SPNEGO, new SPNegoSchemeFactory(true)).build(); httpContext.setAuthSchemeRegistry(authSchemeRegistry); BasicCredentialsProvider credentialsProvider = new BasicCredentialsProvider(); credentialsProvider.setCredentials(new AuthScope(null, -1, null), new NullCredentials()); httpContext.setCredentialsProvider(credentialsProvider); return httpContext; }
From source file:org.apache.solr.client.solrj.impl.SolrHttpClientContextBuilder.java
public HttpClientContext createContext(Object userToken) { HttpClientContext context = new HttpClientContext(); if (getCredentialsProviderProvider() != null) { context.setCredentialsProvider(getCredentialsProviderProvider().getCredentialsProvider()); }// w w w . j a va 2s . c om if (getAuthSchemeRegistryProvider() != null) { context.setAuthSchemeRegistry(getAuthSchemeRegistryProvider().getAuthSchemeRegistry()); } if (getCookieSpecRegistryProvider() != null) { context.setCookieSpecRegistry(getCookieSpecRegistryProvider().getCookieSpecRegistry()); } context.setUserToken(userToken); return context; }
From source file:org.apache.calcite.avatica.remote.AvaticaCommonsHttpClientImpl.java
public byte[] send(byte[] request) { while (true) { HttpClientContext context = HttpClientContext.create(); context.setTargetHost(host);/*from w ww. jav a2s. c o m*/ // Set the credentials if they were provided. if (null != this.credentials) { context.setCredentialsProvider(credentialsProvider); context.setAuthSchemeRegistry(authRegistry); context.setAuthCache(authCache); } ByteArrayEntity entity = new ByteArrayEntity(request, ContentType.APPLICATION_OCTET_STREAM); // Create the client with the AuthSchemeRegistry and manager HttpPost post = new HttpPost(uri); post.setEntity(entity); try (CloseableHttpResponse response = execute(post, context)) { final int statusCode = response.getStatusLine().getStatusCode(); if (HttpURLConnection.HTTP_OK == statusCode || HttpURLConnection.HTTP_INTERNAL_ERROR == statusCode) { return EntityUtils.toByteArray(response.getEntity()); } else if (HttpURLConnection.HTTP_UNAVAILABLE == statusCode) { LOG.debug("Failed to connect to server (HTTP/503), retrying"); continue; } throw new RuntimeException("Failed to execute HTTP Request, got HTTP/" + statusCode); } catch (NoHttpResponseException e) { // This can happen when sitting behind a load balancer and a backend server dies LOG.debug("The server failed to issue an HTTP response, retrying"); continue; } catch (RuntimeException e) { throw e; } catch (Exception e) { LOG.debug("Failed to execute HTTP request", e); throw new RuntimeException(e); } } }
From source file:org.apache.hadoop.hbase.http.TestSpnegoHttpServer.java
@Test public void testAllowedClient() throws Exception { // Create the subject for the client final Subject clientSubject = JaasKrbUtil.loginUsingKeytab(CLIENT_PRINCIPAL, clientKeytab); final Set<Principal> clientPrincipals = clientSubject.getPrincipals(); // Make sure the subject has a principal assertFalse(clientPrincipals.isEmpty()); // Get a TGT for the subject (might have many, different encryption types). The first should // be the default encryption type. Set<KerberosTicket> privateCredentials = clientSubject.getPrivateCredentials(KerberosTicket.class); assertFalse(privateCredentials.isEmpty()); KerberosTicket tgt = privateCredentials.iterator().next(); assertNotNull(tgt);/* w w w . j av a2 s .c o m*/ // The name of the principal final String principalName = clientPrincipals.iterator().next().getName(); // Run this code, logged in as the subject (the client) HttpResponse resp = Subject.doAs(clientSubject, new PrivilegedExceptionAction<HttpResponse>() { @Override public HttpResponse run() throws Exception { // Logs in with Kerberos via GSS GSSManager gssManager = GSSManager.getInstance(); // jGSS Kerberos login constant Oid oid = new Oid("1.2.840.113554.1.2.2"); GSSName gssClient = gssManager.createName(principalName, GSSName.NT_USER_NAME); GSSCredential credential = gssManager.createCredential(gssClient, GSSCredential.DEFAULT_LIFETIME, oid, GSSCredential.INITIATE_ONLY); HttpClientContext context = HttpClientContext.create(); Lookup<AuthSchemeProvider> authRegistry = RegistryBuilder.<AuthSchemeProvider>create() .register(AuthSchemes.SPNEGO, new SPNegoSchemeFactory(true, true)).build(); HttpClient client = HttpClients.custom().setDefaultAuthSchemeRegistry(authRegistry).build(); BasicCredentialsProvider credentialsProvider = new BasicCredentialsProvider(); credentialsProvider.setCredentials(AuthScope.ANY, new KerberosCredentials(credential)); URL url = new URL(getServerURL(server), "/echo?a=b"); context.setTargetHost(new HttpHost(url.getHost(), url.getPort())); context.setCredentialsProvider(credentialsProvider); context.setAuthSchemeRegistry(authRegistry); HttpGet get = new HttpGet(url.toURI()); return client.execute(get, context); } }); assertNotNull(resp); assertEquals(HttpURLConnection.HTTP_OK, resp.getStatusLine().getStatusCode()); assertEquals("a:b", EntityUtils.toString(resp.getEntity()).trim()); }
From source file:com.mirth.connect.connectors.ws.WebServiceDispatcher.java
/** * Returns the URL for the passed in String. If the URL requires authentication, then the WSDL * is saved as a temp file and the URL for that file is returned. * /*from w ww. j a v a 2 s . c o m*/ * @param wsdlUrl * @param username * @param password * @return * @throws Exception */ private URL getWsdlUrl(DispatchContainer dispatchContainer) throws Exception { URI uri = new URI(dispatchContainer.getCurrentWsdlUrl()); // If the URL points to file, just return it if (!uri.getScheme().equalsIgnoreCase("file")) { BasicHttpClientConnectionManager httpClientConnectionManager = new BasicHttpClientConnectionManager( socketFactoryRegistry.build()); httpClientConnectionManager.setSocketConfig(SocketConfig.custom().setSoTimeout(timeout).build()); HttpClientBuilder clientBuilder = HttpClients.custom() .setConnectionManager(httpClientConnectionManager); HttpUtil.configureClientBuilder(clientBuilder); CloseableHttpClient client = clientBuilder.build(); try { clients.add(client); HttpClientContext context = HttpClientContext.create(); if (dispatchContainer.getCurrentUsername() != null && dispatchContainer.getCurrentPassword() != null) { CredentialsProvider credsProvider = new BasicCredentialsProvider(); AuthScope authScope = new AuthScope(AuthScope.ANY_HOST, AuthScope.ANY_PORT, AuthScope.ANY_REALM); Credentials credentials = new UsernamePasswordCredentials( dispatchContainer.getCurrentUsername(), dispatchContainer.getCurrentPassword()); credsProvider.setCredentials(authScope, credentials); AuthCache authCache = new BasicAuthCache(); RegistryBuilder<AuthSchemeProvider> registryBuilder = RegistryBuilder .<AuthSchemeProvider>create(); registryBuilder.register(AuthSchemes.BASIC, new BasicSchemeFactory()); context.setCredentialsProvider(credsProvider); context.setAuthSchemeRegistry(registryBuilder.build()); context.setAuthCache(authCache); } RequestConfig requestConfig = RequestConfig.custom().setConnectTimeout(timeout) .setSocketTimeout(timeout).setStaleConnectionCheckEnabled(true).build(); context.setRequestConfig(requestConfig); return getWsdl(client, context, dispatchContainer, new HashMap<String, File>(), dispatchContainer.getCurrentWsdlUrl()).toURI().toURL(); } finally { HttpClientUtils.closeQuietly(client); clients.remove(client); } } return uri.toURL(); }
From source file:com.mirth.connect.connectors.http.HttpDispatcher.java
@Override public Response send(ConnectorProperties connectorProperties, ConnectorMessage connectorMessage) { HttpDispatcherProperties httpDispatcherProperties = (HttpDispatcherProperties) connectorProperties; eventController.dispatchEvent(new ConnectionStatusEvent(getChannelId(), getMetaDataId(), getDestinationName(), ConnectionStatusEventType.WRITING)); String responseData = null;/* w w w . java 2s. c om*/ String responseError = null; String responseStatusMessage = null; Status responseStatus = Status.QUEUED; boolean validateResponse = false; CloseableHttpClient client = null; HttpRequestBase httpMethod = null; CloseableHttpResponse httpResponse = null; File tempFile = null; int socketTimeout = NumberUtils.toInt(httpDispatcherProperties.getSocketTimeout(), 30000); try { configuration.configureDispatcher(this, httpDispatcherProperties); long dispatcherId = getDispatcherId(); client = clients.get(dispatcherId); if (client == null) { BasicHttpClientConnectionManager httpClientConnectionManager = new BasicHttpClientConnectionManager( socketFactoryRegistry.build()); httpClientConnectionManager .setSocketConfig(SocketConfig.custom().setSoTimeout(socketTimeout).build()); HttpClientBuilder clientBuilder = HttpClients.custom() .setConnectionManager(httpClientConnectionManager); HttpUtil.configureClientBuilder(clientBuilder); if (httpDispatcherProperties.isUseProxyServer()) { clientBuilder.setRoutePlanner(new DynamicProxyRoutePlanner()); } client = clientBuilder.build(); clients.put(dispatcherId, client); } URI hostURI = new URI(httpDispatcherProperties.getHost()); String host = hostURI.getHost(); String scheme = hostURI.getScheme(); int port = hostURI.getPort(); if (port == -1) { if (scheme.equalsIgnoreCase("https")) { port = 443; } else { port = 80; } } // Parse the content type field first, and then add the charset if needed ContentType contentType = ContentType.parse(httpDispatcherProperties.getContentType()); Charset charset = null; if (contentType.getCharset() == null) { charset = Charset.forName(CharsetUtils.getEncoding(httpDispatcherProperties.getCharset())); } else { charset = contentType.getCharset(); } if (httpDispatcherProperties.isMultipart()) { tempFile = File.createTempFile(UUID.randomUUID().toString(), ".tmp"); } HttpHost target = new HttpHost(host, port, scheme); httpMethod = buildHttpRequest(hostURI, httpDispatcherProperties, connectorMessage, tempFile, contentType, charset); HttpClientContext context = HttpClientContext.create(); // authentication if (httpDispatcherProperties.isUseAuthentication()) { CredentialsProvider credsProvider = new BasicCredentialsProvider(); AuthScope authScope = new AuthScope(AuthScope.ANY_HOST, AuthScope.ANY_PORT, AuthScope.ANY_REALM); Credentials credentials = new UsernamePasswordCredentials(httpDispatcherProperties.getUsername(), httpDispatcherProperties.getPassword()); credsProvider.setCredentials(authScope, credentials); AuthCache authCache = new BasicAuthCache(); RegistryBuilder<AuthSchemeProvider> registryBuilder = RegistryBuilder.<AuthSchemeProvider>create(); if (AuthSchemes.DIGEST.equalsIgnoreCase(httpDispatcherProperties.getAuthenticationType())) { logger.debug("using Digest authentication"); registryBuilder.register(AuthSchemes.DIGEST, new DigestSchemeFactory(charset)); if (httpDispatcherProperties.isUsePreemptiveAuthentication()) { processDigestChallenge(authCache, target, credentials, httpMethod, context); } } else { logger.debug("using Basic authentication"); registryBuilder.register(AuthSchemes.BASIC, new BasicSchemeFactory(charset)); if (httpDispatcherProperties.isUsePreemptiveAuthentication()) { authCache.put(target, new BasicScheme()); } } context.setCredentialsProvider(credsProvider); context.setAuthSchemeRegistry(registryBuilder.build()); context.setAuthCache(authCache); logger.debug("using authentication with credentials: " + credentials); } RequestConfig requestConfig = RequestConfig.custom().setConnectTimeout(socketTimeout) .setSocketTimeout(socketTimeout).setStaleConnectionCheckEnabled(true).build(); context.setRequestConfig(requestConfig); // Set proxy information if (httpDispatcherProperties.isUseProxyServer()) { context.setAttribute(PROXY_CONTEXT_KEY, new HttpHost(httpDispatcherProperties.getProxyAddress(), Integer.parseInt(httpDispatcherProperties.getProxyPort()))); } // execute the method logger.debug( "executing method: type=" + httpMethod.getMethod() + ", uri=" + httpMethod.getURI().toString()); httpResponse = client.execute(target, httpMethod, context); StatusLine statusLine = httpResponse.getStatusLine(); int statusCode = statusLine.getStatusCode(); logger.debug("received status code: " + statusCode); Map<String, List<String>> headers = new HashMap<String, List<String>>(); for (Header header : httpResponse.getAllHeaders()) { List<String> list = headers.get(header.getName()); if (list == null) { list = new ArrayList<String>(); headers.put(header.getName(), list); } list.add(header.getValue()); } connectorMessage.getConnectorMap().put("responseStatusLine", statusLine.toString()); connectorMessage.getConnectorMap().put("responseHeaders", new MessageHeaders(new CaseInsensitiveMap(headers))); ContentType responseContentType = ContentType.get(httpResponse.getEntity()); if (responseContentType == null) { responseContentType = ContentType.TEXT_PLAIN; } Charset responseCharset = charset; if (responseContentType.getCharset() != null) { responseCharset = responseContentType.getCharset(); } final String responseBinaryMimeTypes = httpDispatcherProperties.getResponseBinaryMimeTypes(); BinaryContentTypeResolver binaryContentTypeResolver = new BinaryContentTypeResolver() { @Override public boolean isBinaryContentType(ContentType contentType) { return HttpDispatcher.this.isBinaryContentType(responseBinaryMimeTypes, contentType); } }; /* * First parse out the body of the HTTP response. Depending on the connector settings, * this could end up being a string encoded with the response charset, a byte array * representing the raw response payload, or a MimeMultipart object. */ Object responseBody = ""; // The entity could be null in certain cases such as 204 responses if (httpResponse.getEntity() != null) { // Only parse multipart if XML Body is selected and Parse Multipart is enabled if (httpDispatcherProperties.isResponseXmlBody() && httpDispatcherProperties.isResponseParseMultipart() && responseContentType.getMimeType().startsWith(FileUploadBase.MULTIPART)) { responseBody = new MimeMultipart(new ByteArrayDataSource(httpResponse.getEntity().getContent(), responseContentType.toString())); } else if (binaryContentTypeResolver.isBinaryContentType(responseContentType)) { responseBody = IOUtils.toByteArray(httpResponse.getEntity().getContent()); } else { responseBody = IOUtils.toString(httpResponse.getEntity().getContent(), responseCharset); } } /* * Now that we have the response body, we need to create the actual Response message * data. Depending on the connector settings this could be our custom serialized XML, a * Base64 string encoded from the raw response payload, or a string encoded from the * payload with the request charset. */ if (httpDispatcherProperties.isResponseXmlBody()) { responseData = HttpMessageConverter.httpResponseToXml(statusLine.toString(), headers, responseBody, responseContentType, httpDispatcherProperties.isResponseParseMultipart(), httpDispatcherProperties.isResponseIncludeMetadata(), binaryContentTypeResolver); } else if (responseBody instanceof byte[]) { responseData = new String(Base64Util.encodeBase64((byte[]) responseBody), "US-ASCII"); } else { responseData = (String) responseBody; } validateResponse = httpDispatcherProperties.getDestinationConnectorProperties().isValidateResponse(); if (statusCode < HttpStatus.SC_BAD_REQUEST) { responseStatus = Status.SENT; } else { eventController.dispatchEvent(new ErrorEvent(getChannelId(), getMetaDataId(), connectorMessage.getMessageId(), ErrorEventType.DESTINATION_CONNECTOR, getDestinationName(), connectorProperties.getName(), "Received error response from HTTP server.", null)); responseStatusMessage = ErrorMessageBuilder .buildErrorResponse("Received error response from HTTP server.", null); responseError = ErrorMessageBuilder.buildErrorMessage(connectorProperties.getName(), responseData, null); } } catch (Exception e) { eventController.dispatchEvent(new ErrorEvent(getChannelId(), getMetaDataId(), connectorMessage.getMessageId(), ErrorEventType.DESTINATION_CONNECTOR, getDestinationName(), connectorProperties.getName(), "Error connecting to HTTP server.", e)); responseStatusMessage = ErrorMessageBuilder.buildErrorResponse("Error connecting to HTTP server", e); responseError = ErrorMessageBuilder.buildErrorMessage(connectorProperties.getName(), "Error connecting to HTTP server", e); } finally { try { HttpClientUtils.closeQuietly(httpResponse); // Delete temp files if we created them if (tempFile != null) { tempFile.delete(); tempFile = null; } } finally { eventController.dispatchEvent(new ConnectionStatusEvent(getChannelId(), getMetaDataId(), getDestinationName(), ConnectionStatusEventType.IDLE)); } } return new Response(responseStatus, responseData, responseStatusMessage, responseError, validateResponse); }
From source file:org.apache.hadoop.hbase.rest.TestSecureRESTServer.java
private Pair<CloseableHttpClient, HttpClientContext> getClient() { HttpClientConnectionManager pool = new PoolingHttpClientConnectionManager(); HttpHost host = new HttpHost("localhost", REST_TEST.getServletPort()); Registry<AuthSchemeProvider> authRegistry = RegistryBuilder.<AuthSchemeProvider>create() .register(AuthSchemes.SPNEGO, new SPNegoSchemeFactory(true, true)).build(); CredentialsProvider credentialsProvider = new BasicCredentialsProvider(); credentialsProvider.setCredentials(AuthScope.ANY, EmptyCredentials.INSTANCE); AuthCache authCache = new BasicAuthCache(); CloseableHttpClient client = HttpClients.custom().setDefaultAuthSchemeRegistry(authRegistry) .setConnectionManager(pool).build(); HttpClientContext context = HttpClientContext.create(); context.setTargetHost(host);/* ww w .j a va 2 s .c o m*/ context.setCredentialsProvider(credentialsProvider); context.setAuthSchemeRegistry(authRegistry); context.setAuthCache(authCache); return new Pair<>(client, context); }