use of org.apache.http.impl.conn.BasicHttpClientConnectionManager in project hive by apache.
the class HiveConnection method getHttpClient.
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());
}
}
// 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;
// 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();
}
// 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();
}
use of org.apache.http.impl.conn.BasicHttpClientConnectionManager in project Signal-Android by WhisperSystems.
the class LegacyMmsConnection method constructHttpClient.
protected CloseableHttpClient constructHttpClient() throws IOException {
RequestConfig config = RequestConfig.custom().setConnectTimeout(20 * 1000).setConnectionRequestTimeout(20 * 1000).setSocketTimeout(20 * 1000).setMaxRedirects(20).build();
URL mmsc = new URL(apn.getMmsc());
CredentialsProvider credsProvider = new BasicCredentialsProvider();
if (apn.hasAuthentication()) {
credsProvider.setCredentials(new AuthScope(mmsc.getHost(), mmsc.getPort() > -1 ? mmsc.getPort() : mmsc.getDefaultPort()), new UsernamePasswordCredentials(apn.getUsername(), apn.getPassword()));
}
return HttpClients.custom().setConnectionReuseStrategy(new NoConnectionReuseStrategyHC4()).setRedirectStrategy(new LaxRedirectStrategy()).setUserAgent(TextSecurePreferences.getMmsUserAgent(context, USER_AGENT)).setConnectionManager(new BasicHttpClientConnectionManager()).setDefaultRequestConfig(config).setDefaultCredentialsProvider(credsProvider).build();
}
use of org.apache.http.impl.conn.BasicHttpClientConnectionManager in project opennms by OpenNMS.
the class HttpClientWrapper method configureSSLContext.
protected void configureSSLContext(final HttpClientBuilder builder) {
final RegistryBuilder<ConnectionSocketFactory> registryBuilder = RegistryBuilder.<ConnectionSocketFactory>create();
for (final Map.Entry<String, SSLContext> entry : m_sslContext.entrySet()) {
final SSLConnectionSocketFactory sslConnectionFactory = new SSLConnectionSocketFactory(entry.getValue(), SSLConnectionSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER);
registryBuilder.register(entry.getKey(), sslConnectionFactory);
}
if (!m_sslContext.containsKey("http")) {
registryBuilder.register("http", PlainConnectionSocketFactory.INSTANCE);
}
if (!m_sslContext.containsKey("https")) {
registryBuilder.register("https", SSLConnectionSocketFactory.getSystemSocketFactory());
}
final HttpClientConnectionManager ccm = new BasicHttpClientConnectionManager(registryBuilder.build());
builder.setConnectionManager(ccm);
}
use of org.apache.http.impl.conn.BasicHttpClientConnectionManager in project lucene-solr by apache.
the class HttpReplicatorTest method testServerErrors.
@Test
public void testServerErrors() throws Exception {
// tests the behaviour of the client when the server sends an error
// must use BasicClientConnectionManager to test whether the client is closed correctly
BasicHttpClientConnectionManager conMgr = new BasicHttpClientConnectionManager();
Replicator replicator = new HttpReplicator(host, port, ReplicationService.REPLICATION_CONTEXT + "/s1", conMgr);
ReplicationClient client = new ReplicationClient(replicator, new IndexReplicationHandler(handlerIndexDir, null), new PerSessionDirectoryFactory(clientWorkDir));
try {
publishRevision(5);
try {
replicationServlet.setRespondWithError(true);
client.updateNow();
fail("expected exception");
} catch (Throwable t) {
// expected
}
replicationServlet.setRespondWithError(false);
// now it should work
client.updateNow();
reopenReader();
assertEquals(5, Integer.parseInt(reader.getIndexCommit().getUserData().get("ID"), 16));
client.close();
} finally {
replicationServlet.setRespondWithError(false);
}
}
use of org.apache.http.impl.conn.BasicHttpClientConnectionManager in project wildfly by wildfly.
the class Utils method makeHttpCallWithFallback.
/**
* Creates request against SPNEGO protected web-app with FORM fallback. It tries to login using SPNEGO first - if it fails,
* FORM is used.
*
* @param contextUrl
* @param page
* @param user
* @param pass
* @param expectedStatusCode
* @return
* @throws IOException
* @throws URISyntaxException
* @throws PrivilegedActionException
* @throws LoginException
*/
public static String makeHttpCallWithFallback(final String contextUrl, final String page, final String user, final String pass, final int expectedStatusCode) throws IOException, URISyntaxException, PrivilegedActionException, LoginException {
final String strippedContextUrl = StringUtils.stripEnd(contextUrl, "/");
final String url = strippedContextUrl + page;
LOGGER.trace("Requesting URL: " + url);
String unauthorizedPageBody = null;
final Krb5LoginConfiguration krb5Configuration = new Krb5LoginConfiguration(getLoginConfiguration());
Registry<AuthSchemeProvider> authSchemeRegistry = RegistryBuilder.<AuthSchemeProvider>create().register(AuthSchemes.SPNEGO, new JBossNegotiateSchemeFactory(true)).build();
CredentialsProvider credentialsProvider = new BasicCredentialsProvider();
credentialsProvider.setCredentials(new AuthScope(null, -1, null), new NullHCCredentials());
final CloseableHttpClient httpClient = HttpClientBuilder.create().setDefaultAuthSchemeRegistry(authSchemeRegistry).setDefaultCredentialsProvider(credentialsProvider).setRedirectStrategy(REDIRECT_STRATEGY).setConnectionManager(new BasicHttpClientConnectionManager()).build();
try {
final HttpGet httpGet = new HttpGet(url);
final HttpResponse response = httpClient.execute(httpGet);
int statusCode = response.getStatusLine().getStatusCode();
if (HttpServletResponse.SC_UNAUTHORIZED != statusCode || StringUtils.isEmpty(user)) {
assertEquals("Unexpected HTTP response status code.", expectedStatusCode, statusCode);
return EntityUtils.toString(response.getEntity());
}
final Header[] authnHeaders = response.getHeaders("WWW-Authenticate");
assertTrue("WWW-Authenticate header is present", authnHeaders != null && authnHeaders.length > 0);
final Set<String> authnHeaderValues = new HashSet<String>();
for (final Header header : authnHeaders) {
authnHeaderValues.add(header.getValue());
}
assertTrue("WWW-Authenticate: Negotiate header is missing", authnHeaderValues.contains("Negotiate"));
LOGGER.debug("HTTP response was SC_UNAUTHORIZED, let's authenticate the user " + user);
unauthorizedPageBody = EntityUtils.toString(response.getEntity());
// Use our custom configuration to avoid reliance on external config
Configuration.setConfiguration(krb5Configuration);
// 1. Authenticate to Kerberos.
final LoginContext lc = loginWithKerberos(krb5Configuration, user, pass);
// 2. Perform the work as authenticated Subject.
final String responseBody = Subject.doAs(lc.getSubject(), new PrivilegedExceptionAction<String>() {
public String run() throws Exception {
final HttpResponse response = httpClient.execute(httpGet);
int statusCode = response.getStatusLine().getStatusCode();
assertEquals("Unexpected status code returned after the authentication.", expectedStatusCode, statusCode);
return EntityUtils.toString(response.getEntity());
}
});
lc.logout();
return responseBody;
} catch (LoginException e) {
assertNotNull(unauthorizedPageBody);
assertTrue(unauthorizedPageBody.contains("j_security_check"));
HttpPost httpPost = new HttpPost(strippedContextUrl + "/j_security_check");
List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>();
nameValuePairs.add(new BasicNameValuePair("j_username", user));
nameValuePairs.add(new BasicNameValuePair("j_password", pass));
httpPost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
final HttpResponse response = httpClient.execute(httpPost);
int statusCode = response.getStatusLine().getStatusCode();
assertEquals("Unexpected status code returned after the authentication.", expectedStatusCode, statusCode);
return EntityUtils.toString(response.getEntity());
} finally {
// When HttpClient instance is no longer needed,
// shut down the connection manager to ensure
// immediate deallocation of all system resources
httpClient.close();
// reset login configuration
krb5Configuration.resetConfiguration();
}
}
Aggregations