use of org.graylog.shaded.elasticsearch7.org.apache.http.client.CredentialsProvider in project orientdb by orientechnologies.
the class BaseHttpTest method exec.
protected BaseHttpTest exec() throws IOException {
final HttpHost targetHost = new HttpHost(getHost(), getPort(), getProtocol());
CredentialsProvider credsProvider = new BasicCredentialsProvider();
credsProvider.setCredentials(new AuthScope(targetHost), new UsernamePasswordCredentials(getUserName(), getUserPassword()));
// 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(targetHost, basicAuth);
// Add AuthCache to the execution context
HttpClientContext context = HttpClientContext.create();
context.setCredentialsProvider(credsProvider);
context.setAuthCache(authCache);
if (keepAlive != null)
request.addHeader("Connection", keepAlive ? "Keep-Alive" : "Close");
if (payload != null && request instanceof HttpEntityEnclosingRequestBase)
((HttpEntityEnclosingRequestBase) request).setEntity(payload);
final CloseableHttpClient httpClient = HttpClients.createDefault();
// DefaultHttpMethodRetryHandler retryhandler = new DefaultHttpMethodRetryHandler(retry, false);
// context.setAttribute(HttpMethodParams.RETRY_HANDLER, retryhandler);
response = httpClient.execute(targetHost, request, context);
return this;
}
use of org.graylog.shaded.elasticsearch7.org.apache.http.client.CredentialsProvider in project robolectric by robolectric.
the class DefaultRequestDirector method createTunnelToTarget.
// establishConnection
/**
* Creates a tunnel to the target server.
* The connection must be established to the (last) proxy.
* A CONNECT request for tunnelling through the proxy will
* be created and sent, the response received and checked.
* This method does <i>not</i> update the connection with
* information about the tunnel, that is left to the caller.
*
* @param route the route to establish
* @param context the context for request execution
*
* @return {@code true} if the tunnelled route is secure,
* {@code false} otherwise.
* The implementation here always returns {@code false},
* but derived classes may override.
*
* @throws HttpException in case of a problem
* @throws IOException in case of an IO problem
*/
protected boolean createTunnelToTarget(HttpRoute route, HttpContext context) throws HttpException, IOException {
HttpHost proxy = route.getProxyHost();
HttpHost target = route.getTargetHost();
HttpResponse response = null;
boolean done = false;
while (!done) {
done = true;
if (!this.managedConn.isOpen()) {
this.managedConn.open(route, context, this.params);
}
HttpRequest connect = createConnectRequest(route, context);
connect.setParams(this.params);
// 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);
context.setAttribute(ExecutionContext.HTTP_REQUEST, connect);
this.requestExec.preProcess(connect, this.httpProcessor, context);
response = this.requestExec.execute(connect, this.managedConn, context);
response.setParams(this.params);
this.requestExec.postProcess(response, this.httpProcessor, context);
int status = response.getStatusLine().getStatusCode();
if (status < 200) {
throw new HttpException("Unexpected response to CONNECT request: " + response.getStatusLine());
}
CredentialsProvider credsProvider = (CredentialsProvider) context.getAttribute(ClientContext.CREDS_PROVIDER);
if (credsProvider != null && HttpClientParams.isAuthenticating(params)) {
if (this.proxyAuthHandler.isAuthenticationRequested(response, context)) {
this.log.debug("Proxy requested authentication");
Map<String, Header> challenges = this.proxyAuthHandler.getChallenges(response, context);
try {
processChallenges(challenges, this.proxyAuthState, this.proxyAuthHandler, response, context);
} catch (AuthenticationException ex) {
if (this.log.isWarnEnabled()) {
this.log.warn("Authentication error: " + ex.getMessage());
break;
}
}
updateAuthState(this.proxyAuthState, proxy, credsProvider);
if (this.proxyAuthState.getCredentials() != null) {
done = false;
// Retry request
if (this.reuseStrategy.keepAlive(response, context)) {
this.log.debug("Connection kept alive");
// Consume response content
HttpEntity entity = response.getEntity();
if (entity != null) {
entity.consumeContent();
}
} else {
this.managedConn.close();
}
}
} else {
// Reset proxy auth scope
this.proxyAuthState.setAuthScope(null);
}
}
}
// can't be null
int status = response.getStatusLine().getStatusCode();
if (status > 299) {
// Buffer response content
HttpEntity entity = response.getEntity();
if (entity != null) {
response.setEntity(new BufferedHttpEntity(entity));
}
this.managedConn.close();
throw new TunnelRefusedException("CONNECT refused by proxy: " + response.getStatusLine(), response);
}
this.managedConn.markReusable();
// Leave it to derived classes, consider insecure by default here.
return false;
}
use of org.graylog.shaded.elasticsearch7.org.apache.http.client.CredentialsProvider in project jackrabbit by apache.
the class RepositoryServiceImpl method getContext.
protected HttpContext getContext(SessionInfo sessionInfo) throws RepositoryException {
HttpClientContext result = HttpClientContext.create();
CredentialsProvider credsProvider = new BasicCredentialsProvider();
result.setCredentialsProvider(credsProvider);
// take over default credentials (e.g. for proxy)
for (Map.Entry<AuthScope, org.apache.http.auth.Credentials> entry : commonCredentials.entrySet()) {
credsProvider.setCredentials(entry.getKey(), entry.getValue());
}
if (sessionInfo != null) {
checkSessionInfo(sessionInfo);
org.apache.http.auth.Credentials creds = ((SessionInfoImpl) sessionInfo).getCredentials().getHttpCredentials();
if (creds != null) {
credsProvider.setCredentials(new org.apache.http.auth.AuthScope(httpHost.getHostName(), httpHost.getPort()), creds);
BasicScheme basicAuth = new BasicScheme();
AuthCache authCache = new BasicAuthCache();
authCache.put(httpHost, basicAuth);
result.setAuthCache(authCache);
}
}
return result;
}
use of org.graylog.shaded.elasticsearch7.org.apache.http.client.CredentialsProvider in project hazelcast by hazelcast.
the class ElasticClients method client.
/**
* Convenience method to create {@link RestClientBuilder} with basic authentication
* and given hostname, port and scheme. Valid schemes are "http" and "https".
* <p>
* Usage:
* <pre>{@code
* BatchSource<SearchHit> source = elastic(() -> client("user", "password", "host", 9200, "https"));
* }</pre>
*/
@Nonnull
public static RestClientBuilder client(@Nonnull String username, @Nonnull String password, @Nonnull String hostname, int port, @Nonnull String scheme) {
CredentialsProvider credentialsProvider = new BasicCredentialsProvider();
credentialsProvider.setCredentials(ANY, new UsernamePasswordCredentials(username, password));
return RestClient.builder(new HttpHost(hostname, port, scheme)).setHttpClientConfigCallback(httpClientBuilder -> httpClientBuilder.setDefaultCredentialsProvider(credentialsProvider));
}
use of org.graylog.shaded.elasticsearch7.org.apache.http.client.CredentialsProvider in project stanbol by apache.
the class StanbolTestBase method waitForServerReady.
@Before
public void waitForServerReady() throws Exception {
log.debug("> before {}#waitForServerReady()", getClass().getSimpleName());
// initialize instance request builder and HTTP client
builder = new RequestBuilder(serverBaseUrl);
// TODO:user name and pwd
String credentials = getCredentials();
if (credentials != null && !credentials.isEmpty()) {
CredentialsProvider credsProvider = new BasicCredentialsProvider();
credsProvider.setCredentials(new AuthScope(HttpHost.create(serverBaseUrl)), new UsernamePasswordCredentials(credentials));
httpClient = HttpClients.custom().setDefaultCredentialsProvider(credsProvider).build();
} else {
httpClient = HttpClients.createDefault();
}
executor = new RequestExecutor(httpClient);
if (serverReady) {
log.debug(" ... server already marked as ready!");
return;
}
// Timeout for readiness test
final String sec = System.getProperty(SERVER_READY_TIMEOUT_PROP);
final int timeoutSec = sec == null ? 60 : Integer.valueOf(sec);
log.info("Will wait up to " + timeoutSec + " seconds for server to become ready");
final long endTime = System.currentTimeMillis() + timeoutSec * 1000L;
// Get the list of paths to test and expected content regexps
final List<String> testPaths = new ArrayList<String>();
final TreeSet<Object> propertyNames = new TreeSet<Object>();
propertyNames.addAll(System.getProperties().keySet());
for (Object o : propertyNames) {
final String key = (String) o;
if (key.startsWith(SERVER_READY_PROP_PREFIX)) {
testPaths.add(System.getProperty(key));
}
}
// Consider the server ready if it responds to a GET on each of
// our configured request paths with a 200 result and content
// that matches the regexp supplied with the path
long sleepTime = 100;
readyLoop: while (!serverReady && System.currentTimeMillis() < endTime) {
// Wait a bit between checks, to let the server come up
Thread.sleep(sleepTime);
sleepTime = Math.min(5000L, sleepTime * 2);
// A test path is in the form path:substring or just path, in which case
// we don't check that the content contains the substring
log.debug(" - check serverReady Paths");
for (String p : testPaths) {
final String[] s = p.split(":");
final String path = s[0];
final String substring = (s.length > 0 ? s[1] : null);
final String url = serverBaseUrl + path;
log.debug(" > url: {}", url);
log.debug(" > content: {}", substring);
final HttpGet get = new HttpGet(url);
// authenticate as admin with password admin
get.setHeader("Authorization", "Basic YWRtaW46YWRtaW4=");
for (int i = 2; i + 1 < s.length; i = i + 2) {
log.debug(" > header: {}:{}", s[i], s[i + 1]);
if (s[i] != null && !s[i].isEmpty() && s[i + 1] != null && !s[i + 1].isEmpty()) {
get.setHeader(s[i], s[i + 1]);
}
}
CloseableHttpResponse response = null;
HttpEntity entity = null;
try {
log.debug(" > execute: {}", get);
response = httpClient.execute(get);
log.debug(" > response: {}", response);
entity = response.getEntity();
final int status = response.getStatusLine().getStatusCode();
if (status != 200) {
log.info("Got {} at {} - will retry", status, url);
continue readyLoop;
} else {
log.debug("Got {} at {} - will retry", status, url);
}
if (substring != null) {
if (entity == null) {
log.info("No entity returned for {} - will retry", url);
continue readyLoop;
}
final String content = EntityUtils.toString(entity);
if (!content.contains(substring)) {
log.info("Returned content for {} does not contain " + "{} - will retry", url, substring);
continue readyLoop;
}
}
} catch (HttpHostConnectException e) {
log.info("Got HttpHostConnectException at " + url + " - will retry");
continue readyLoop;
} finally {
EntityUtils.consumeQuietly(entity);
if (response != null) {
response.close();
}
}
}
serverReady = true;
log.info("Got expected content for all configured requests, server is ready");
}
if (!serverReady) {
throw new Exception("Server not ready after " + timeoutSec + " seconds");
}
}
Aggregations