use of org.apache.http.impl.client.BasicAuthCache in project iaf by ibissource.
the class HttpSenderBase method sendMessageWithTimeoutGuarded.
@Override
public String sendMessageWithTimeoutGuarded(String correlationID, String message, ParameterResolutionContext prc) throws SenderException, TimeOutException {
ParameterValueList pvl = null;
try {
if (prc != null && paramList != null) {
pvl = prc.getValues(paramList);
}
} catch (ParameterException e) {
throw new SenderException(getLogPrefix() + "Sender [" + getName() + "] caught exception evaluating parameters", e);
}
URIBuilder uri;
HttpRequestBase httpRequestBase;
try {
if (urlParameter != null) {
String url = (String) pvl.getParameterValue(getUrlParam()).getValue();
uri = getURI(url);
} else {
uri = staticUri;
}
httpTarget = new HttpHost(uri.getHost(), getPort(uri), uri.getScheme());
Map<String, String> headersParamsMap = new HashMap<String, String>();
if (headersParams != null) {
StringTokenizer st = new StringTokenizer(headersParams, ",");
while (st.hasMoreElements()) {
headersParamsMap.put(st.nextToken(), null);
}
}
if (isEncodeMessages()) {
message = URLEncoder.encode(message, getCharSet());
}
httpRequestBase = getMethod(uri, message, pvl, headersParamsMap, prc.getSession());
if (httpRequestBase == null)
throw new MethodNotSupportedException("could not find implementation for method [" + getMethodType() + "]");
if (!"POST".equals(getMethodType()) && !"PUT".equals(getMethodType()) && !"REPORT".equals(getMethodType())) {
httpClientBuilder.setRedirectStrategy(new DefaultRedirectStrategy() {
@Override
protected boolean isRedirectable(String method) {
return true;
}
});
}
if (StringUtils.isNotEmpty(getContentType())) {
httpRequestBase.setHeader("Content-Type", getContentType());
}
if (credentials != null && !StringUtils.isEmpty(credentials.getUsername())) {
AuthCache authCache = httpClientContext.getAuthCache();
if (authCache == null)
authCache = new BasicAuthCache();
authCache.put(httpTarget, new BasicScheme());
httpClientContext.setAuthCache(authCache);
}
log.info(getLogPrefix() + "configured httpclient for host [" + uri.getHost() + "]");
} catch (Exception e) {
throw new SenderException(e);
}
CloseableHttpClient httpClient = httpClientBuilder.build();
String result = null;
int statusCode = -1;
int count = getMaxExecuteRetries();
String msg = null;
while (count-- >= 0 && statusCode == -1) {
try {
log.debug(getLogPrefix() + "executing method [" + httpRequestBase.getRequestLine() + "]");
HttpResponse httpResponse = httpClient.execute(httpTarget, httpRequestBase, httpClientContext);
log.debug(getLogPrefix() + "executed method");
HttpResponseHandler responseHandler = new HttpResponseHandler(httpResponse);
StatusLine statusline = httpResponse.getStatusLine();
statusCode = statusline.getStatusCode();
if (StringUtils.isNotEmpty(getResultStatusCodeSessionKey()) && prc != null) {
prc.getSession().put(getResultStatusCodeSessionKey(), Integer.toString(statusCode));
}
if (statusCode != HttpServletResponse.SC_OK) {
log.warn(getLogPrefix() + "status [" + statusline.toString() + "]");
} else {
log.debug(getLogPrefix() + "status [" + statusCode + "]");
}
result = extractResult(responseHandler, prc);
log.debug(getLogPrefix() + "retrieved result [" + result + "]");
} catch (ClientProtocolException e) {
httpRequestBase.abort();
Throwable throwable = e.getCause();
String cause = null;
if (throwable != null) {
cause = throwable.toString();
}
msg = e.getMessage();
log.warn(getLogPrefix() + "httpException with message [" + msg + "] and cause [" + cause + "], executeRetries left [" + count + "]");
} catch (IOException e) {
httpRequestBase.abort();
if (e instanceof SocketTimeoutException) {
throw new TimeOutException(e);
}
throw new SenderException(e);
} finally {
// By forcing the use of the HttpResponseHandler the resultStream
// will automatically be closed when it has been read.
// See HttpResponseHandler and ReleaseConnectionAfterReadInputStream.
// We cannot close the connection as the response might be kept
// in a sessionKey for later use in the pipeline.
//
// IMPORTANT: It is possible that poorly written implementations
// wont read or close the response.
// This will cause the connection to become stale..
}
}
if (statusCode == -1) {
if (StringUtils.contains(msg.toUpperCase(), "TIMEOUTEXCEPTION")) {
// java.net.SocketTimeoutException: Read timed out
throw new TimeOutException("Failed to recover from timeout exception");
}
throw new SenderException("Failed to recover from exception");
}
if (isXhtml() && StringUtils.isNotEmpty(result)) {
result = XmlUtils.skipDocTypeDeclaration(result.trim());
if (result.startsWith("<html>") || result.startsWith("<html ")) {
CleanerProperties props = new CleanerProperties();
HtmlCleaner cleaner = new HtmlCleaner(props);
TagNode tagNode = cleaner.clean(result);
result = new SimpleXmlSerializer(props).getXmlAsString(tagNode);
if (transformerPool != null) {
log.debug(getLogPrefix() + " transforming result [" + result + "]");
ParameterResolutionContext prc_xslt = new ParameterResolutionContext(result, null, true, true);
try {
result = transformerPool.transform(prc_xslt.getInputSource(), null);
} catch (Exception e) {
throw new SenderException("Exception on transforming input", e);
}
}
}
}
return result;
}
use of org.apache.http.impl.client.BasicAuthCache in project knox by apache.
the class Hadoop method createClient.
private CloseableHttpClient createClient(ClientContext clientContext) throws GeneralSecurityException {
// SSL
HostnameVerifier hostnameVerifier = NoopHostnameVerifier.INSTANCE;
TrustStrategy trustStrategy = null;
if (clientContext.connection().secure()) {
hostnameVerifier = SSLConnectionSocketFactory.getDefaultHostnameVerifier();
} else {
trustStrategy = TrustSelfSignedStrategy.INSTANCE;
System.out.println("**************** WARNING ******************\n" + "This is an insecure client instance and may\n" + "leave the interactions subject to a man in\n" + "the middle attack. Please use the login()\n" + "method instead of loginInsecure() for any\n" + "sensitive or production usecases.\n" + "*******************************************");
}
KeyStore trustStore = getTrustStore();
SSLContext sslContext = SSLContexts.custom().loadTrustMaterial(trustStore, trustStrategy).build();
Registry<ConnectionSocketFactory> registry = RegistryBuilder.<ConnectionSocketFactory>create().register("http", PlainConnectionSocketFactory.getSocketFactory()).register("https", new SSLConnectionSocketFactory(sslContext, hostnameVerifier)).build();
// Pool
PoolingHttpClientConnectionManager connectionManager = new PoolingHttpClientConnectionManager(registry);
connectionManager.setMaxTotal(clientContext.pool().maxTotal());
connectionManager.setDefaultMaxPerRoute(clientContext.pool().defaultMaxPerRoute());
ConnectionConfig connectionConfig = ConnectionConfig.custom().setBufferSize(clientContext.connection().bufferSize()).build();
connectionManager.setDefaultConnectionConfig(connectionConfig);
SocketConfig socketConfig = SocketConfig.custom().setSoKeepAlive(clientContext.socket().keepalive()).setSoLinger(clientContext.socket().linger()).setSoReuseAddress(clientContext.socket().reuseAddress()).setSoTimeout(clientContext.socket().timeout()).setTcpNoDelay(clientContext.socket().tcpNoDelay()).build();
connectionManager.setDefaultSocketConfig(socketConfig);
// Auth
URI uri = URI.create(clientContext.url());
host = new HttpHost(uri.getHost(), uri.getPort(), uri.getScheme());
CredentialsProvider credentialsProvider = null;
if (clientContext.username() != null && clientContext.password() != null) {
credentialsProvider = new BasicCredentialsProvider();
credentialsProvider.setCredentials(new AuthScope(host.getHostName(), host.getPort()), new UsernamePasswordCredentials(clientContext.username(), clientContext.password()));
AuthCache authCache = new BasicAuthCache();
BasicScheme authScheme = new BasicScheme();
authCache.put(host, authScheme);
context = new BasicHttpContext();
context.setAttribute(org.apache.http.client.protocol.HttpClientContext.AUTH_CACHE, authCache);
}
return HttpClients.custom().setConnectionManager(connectionManager).setDefaultCredentialsProvider(credentialsProvider).build();
}
use of org.apache.http.impl.client.BasicAuthCache in project syncope by apache.
the class HttpUtils method setAuth.
private HttpClientContext setAuth(final HttpHost targetHost, final AuthScheme authScheme) {
final CredentialsProvider credsProvider = new BasicCredentialsProvider();
credsProvider.setCredentials(new AuthScope(targetHost.getHostName(), targetHost.getPort()), new UsernamePasswordCredentials(username, password));
final HttpClientContext context = HttpClientContext.create();
final AuthCache authCache = new BasicAuthCache();
authCache.put(targetHost, authScheme);
context.setAuthCache(authCache);
context.setCredentialsProvider(credsProvider);
return context;
}
use of org.apache.http.impl.client.BasicAuthCache in project jackrabbit by apache.
the class WebDAVTestBase method setUp.
protected void setUp() throws Exception {
super.setUp();
File home = new File("target/jackrabbit-repository");
if (!home.exists()) {
home.mkdirs();
}
File config = new File(home, "repository.xml");
if (!config.exists()) {
createDefaultConfiguration(config);
}
File keystore = new File(home, KEYSTORE);
if (!keystore.exists()) {
createKeystore(keystore);
}
if (repoContext == null) {
repoContext = RepositoryContext.create(RepositoryConfig.create(config.toURI(), home.getPath()));
}
if (server == null) {
server = new Server();
ServletHolder simple = new ServletHolder(new SimpleWebdavServlet() {
private static final long serialVersionUID = 8638589328461138178L;
public Repository getRepository() {
return repoContext.getRepository();
}
});
simple.setInitParameter(SimpleWebdavServlet.INIT_PARAM_RESOURCE_CONFIG, "/config.xml");
ServletHolder remoting = new ServletHolder(new JcrRemotingServlet() {
private static final long serialVersionUID = -2969534124090379387L;
public Repository getRepository() {
return repoContext.getRepository();
}
});
remoting.setInitParameter(JcrRemotingServlet.INIT_PARAM_RESOURCE_PATH_PREFIX, "/remoting");
ServletContextHandler schandler = new ServletContextHandler(server, "/");
schandler.addServlet(simple, SIMPLE_WEBDAV_SERVLET_PATH_MAPPING);
schandler.addServlet(remoting, REMOTING_WEBDAV_SERVLET_PATH_MAPPING);
schandler.setBaseResource(Resource.newClassPathResource("/"));
server.setHandler(schandler);
}
if (httpConnector == null) {
httpConnector = new ServerConnector(server);
httpConnector.setHost("localhost");
httpConnector.setPort(0);
server.addConnector(httpConnector);
}
if (httpsConnector == null) {
SslContextFactory sslContextFactory = new SslContextFactory();
sslContextFactory.setKeyStorePath(keystore.getPath());
sslContextFactory.setKeyStorePassword(KEYSTOREPW);
sslContextFactory.setKeyManagerPassword(KEYSTOREPW);
sslContextFactory.setTrustStorePath(keystore.getPath());
sslContextFactory.setTrustStorePassword(KEYSTOREPW);
SslConnectionFactory cfac = new SslConnectionFactory(sslContextFactory, HttpVersion.HTTP_1_1.asString());
httpsConnector = new ServerConnector(server, cfac, new HttpConnectionFactory(new HttpConfiguration()));
httpsConnector.setHost("localhost");
httpsConnector.setPort(0);
server.addConnector(httpsConnector);
}
if (!server.isStarted()) {
try {
server.start();
} catch (Exception e) {
throw new RepositoryStubException(e);
}
}
this.uri = new URI("http", null, "localhost", httpConnector.getLocalPort(), "/default/", null, null);
this.remotingUri = new URI("http", null, "localhost", httpConnector.getLocalPort(), REMOTING_PREFIX + "/", null, null);
this.httpsUri = new URI("https", null, "localhost", httpsConnector.getLocalPort(), "/default/", null, null);
this.root = this.uri.toASCIIString();
PoolingHttpClientConnectionManager cm = new PoolingHttpClientConnectionManager();
// cm.setMaxTotal(100);
HttpHost targetHost = new HttpHost(uri.getHost(), uri.getPort());
CredentialsProvider credsProvider = new BasicCredentialsProvider();
credsProvider.setCredentials(new AuthScope(targetHost.getHostName(), targetHost.getPort()), new UsernamePasswordCredentials("admin", "admin"));
AuthCache authCache = new BasicAuthCache();
// Generate BASIC scheme object and add it to the local auth cache
BasicScheme basicAuth = new BasicScheme();
authCache.put(targetHost, basicAuth);
// Add AuthCache to the execution context
this.context = HttpClientContext.create();
this.context.setCredentialsProvider(credsProvider);
this.context.setAuthCache(authCache);
this.client = HttpClients.custom().setConnectionManager(cm).build();
super.setUp();
}
use of org.apache.http.impl.client.BasicAuthCache in project vcell by virtualcell.
the class VCellApiClient method authenticate.
public AccessTokenRepresentation authenticate(String userid, String password, boolean alreadyDigested) throws ClientProtocolException, IOException {
// hash the password
String digestedPassword = (alreadyDigested) ? (password) : createdDigestPassword(password);
HttpGet httpget = new HttpGet("https://" + httpHost.getHostName() + ":" + httpHost.getPort() + "/access_token?user_id=" + userid + "&user_password=" + digestedPassword + "&client_id=" + clientID);
if (lg.isInfoEnabled()) {
lg.info("Executing request to retrieve access_token " + httpget.getRequestLine());
}
String responseBody = httpclient.execute(httpget, new VCellStringResponseHandler("authenticate()", httpget));
String accessTokenJson = responseBody;
if (lg.isInfoEnabled()) {
lg.info("returned: " + accessTokenJson);
}
Gson gson = new Gson();
AccessTokenRepresentation accessTokenRep = gson.fromJson(accessTokenJson, AccessTokenRepresentation.class);
CredentialsProvider credsProvider = new BasicCredentialsProvider();
credsProvider.setCredentials(new AuthScope(httpHost.getHostName(), httpHost.getPort()), new UsernamePasswordCredentials("access_token", accessTokenRep.getToken()));
// Create AuthCache instance
AuthCache authCache = new BasicAuthCache();
// Generate BASIC scheme object and add it to the local auth cache
BasicScheme basicAuth = new BasicScheme();
authCache.put(httpHost, basicAuth);
// Add AuthCache to the execution context
httpClientContext = HttpClientContext.create();
httpClientContext.setCredentialsProvider(credsProvider);
httpClientContext.setAuthCache(authCache);
return accessTokenRep;
}
Aggregations