下面列出了org.apache.http.impl.client.SystemDefaultHttpClient#org.apache.http.auth.AuthScope 实例代码,或者点击链接到github查看源代码,也可以在右侧发表评论。
/**
* Create an {@link ApacheHttpTransport} for calling Google APIs with an optional HTTP proxy.
*
* @param proxyUri Optional HTTP proxy URI to use with the transport.
* @param proxyCredentials Optional HTTP proxy credentials to authenticate with the transport
* proxy.
* @return The resulting HttpTransport.
* @throws IOException If there is an issue connecting to Google's certification server.
* @throws GeneralSecurityException If there is a security issue with the keystore.
*/
public static ApacheHttpTransport createApacheHttpTransport(
@Nullable URI proxyUri, @Nullable Credentials proxyCredentials)
throws IOException, GeneralSecurityException {
checkArgument(
proxyUri != null || proxyCredentials == null,
"if proxyUri is null than proxyCredentials should be null too");
ApacheHttpTransport transport =
new ApacheHttpTransport.Builder()
.trustCertificates(GoogleUtils.getCertificateTrustStore())
.setProxy(
proxyUri == null ? null : new HttpHost(proxyUri.getHost(), proxyUri.getPort()))
.build();
if (proxyCredentials != null) {
((DefaultHttpClient) transport.getHttpClient())
.getCredentialsProvider()
.setCredentials(new AuthScope(proxyUri.getHost(), proxyUri.getPort()), proxyCredentials);
}
return transport;
}
@org.junit.Test
public void testSwagger() throws Exception {
String url = "https://localhost:" + getIdpHttpsPort() + "/fediz-idp/services/rs/swagger.json";
String user = "alice";
String password = "ecila";
final WebClient webClient = new WebClient();
webClient.getOptions().setUseInsecureSSL(true);
webClient.getCredentialsProvider().setCredentials(
new AuthScope("localhost", Integer.parseInt(getIdpHttpsPort())),
new UsernamePasswordCredentials(user, password));
final UnexpectedPage swaggerPage = webClient.getPage(url);
WebResponse response = swaggerPage.getWebResponse();
Assert.assertEquals("application/json", response.getContentType());
String json = response.getContentAsString();
Assert.assertTrue(json.contains("Claims"));
webClient.close();
}
private HttpClientContext getClientContext(final String hostname, final String username, final String password)
throws IOException {
final HttpHost targetHost = new HttpHost(hostname, 443, "https");
final HttpClientContext result = HttpClientContext.create();
// Setup credentials provider
final CredentialsProvider credentialsProvider = new BasicCredentialsProvider();
credentialsProvider.setCredentials(AuthScope.ANY, new UsernamePasswordCredentials(username, password));
result.setCredentialsProvider(credentialsProvider);
// Setup preemptive authentication
final AuthCache authCache = new BasicAuthCache();
final BasicScheme basicAuth = new BasicScheme();
authCache.put(targetHost, basicAuth);
result.setAuthCache(authCache);
final HttpGet httpget = new HttpGet("/");
// Prime the cache
try (CloseableHttpResponse response = this.httpClient.execute(targetHost, httpget, result)) {
// empty try block used to automatically close resources
}
return result;
}
private static CloseableHttpClient createHttpClient(String host, int port, String username, String password) {
try {
SSLContext sslContext = SSLContexts.createDefault();
SSLConnectionSocketFactory sslConnectionSocketFactory = new SSLConnectionSocketFactory(sslContext, NoopHostnameVerifier.INSTANCE);
Registry<ConnectionSocketFactory> registry = RegistryBuilder.<ConnectionSocketFactory>create()
.register("https", sslConnectionSocketFactory)
.register("http", PlainConnectionSocketFactory.getSocketFactory())
.build();
CredentialsProvider credsProvider = new BasicCredentialsProvider();
credsProvider.setCredentials(new AuthScope(host, port, MANAGEMENT_REALM, AuthSchemes.DIGEST),
new UsernamePasswordCredentials(username, password));
PoolingHttpClientConnectionManager connectionPool = new PoolingHttpClientConnectionManager(registry);
HttpClientBuilder.create().setConnectionManager(connectionPool).build();
return HttpClientBuilder.create()
.setConnectionManager(connectionPool)
.setRetryHandler(new StandardHttpRequestRetryHandler(5, true))
.setDefaultCredentialsProvider(credsProvider).build();
} catch (Exception e) {
throw new RuntimeException(e);
}
}
@Test
public void testUrlCredDefaultProvider() throws HTTPException {
String url = "https://" + username + ":" + password + "@" + host + "/something/garbage.grb?query";
logger.info("Testing {}", url);
try (HTTPMethod method = HTTPFactory.Get(url)) {
// we should have a default BasicCredentialProvider available, even though
// we didn't call the factory with a specific provider
HTTPSession session = method.getSession();
CredentialsProvider credentialsProvider = session.sessionprovider;
assertThat(credentialsProvider).isNotNull();
AuthScope expectedAuthScope = new AuthScope(host, 80);
Credentials credentials = credentialsProvider.getCredentials(expectedAuthScope);
assertThat(credentials).isNotNull();
assertThat(credentials.getUserPrincipal().getName()).isEqualTo(username);
assertThat(credentials.getPassword()).isEqualTo(password);
}
}
public static HttpDispatcher getInstance(String uri, Credentials credentials) {
HttpDispatcher dispatcher = new HttpDispatcher(new HttpHost(uri),
new BasicHttpContext());
CredentialsProvider credsProvider = new BasicCredentialsProvider();
AuthScope authScope = new AuthScope(
dispatcher.host.getHostName(),
dispatcher.host.getPort());
credsProvider.setCredentials(authScope, credentials);
((DefaultHttpClient) dispatcher.client).getCredentialsProvider().setCredentials(
authScope, credentials);
return dispatcher;
}
private HttpClientContext setupContext() {
final HttpClientContext context = HttpClientContext.create();
if (baseUri.contains("@") || springCloudConfigClientConfig.usernameAndPasswordSet()) {
final AuthCache authCache = InMemoryAuthCache.INSTANCE;
authCache.put(HttpHost.create(baseUri), new BasicScheme());
context.setAuthCache(authCache);
if (springCloudConfigClientConfig.usernameAndPasswordSet()) {
final CredentialsProvider provider = new BasicCredentialsProvider();
final UsernamePasswordCredentials credentials = new UsernamePasswordCredentials(
springCloudConfigClientConfig.username.get(), springCloudConfigClientConfig.password.get());
provider.setCredentials(AuthScope.ANY, credentials);
context.setCredentialsProvider(provider);
}
}
return context;
}
/**
* Returns context with AuthCache or null in case of any exception was thrown.
*
* @param host
* @param port
* @param user
* @param password
* @param schema
* @return {@link org.apache.http.client.protocol.HttpClientContext HttpClientContext}
*/
public static HttpClientContext createPreemptiveBasicAuthentication( String host, int port, String user,
String password, String schema ) {
HttpClientContext localContext = null;
try {
HttpHost target = new HttpHost( host, port, schema );
CredentialsProvider credsProvider = new BasicCredentialsProvider();
credsProvider.setCredentials(
new AuthScope( target.getHostName(), target.getPort() ),
new UsernamePasswordCredentials( user, password ) );
// 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( target, basicAuth );
// Add AuthCache to the execution context
localContext = HttpClientContext.create();
localContext.setAuthCache( authCache );
} catch ( Exception e ) {
return null;
}
return localContext;
}
@JsonCreator
public ElasticSearchFilter(@JsonProperty("hostname") String hostname, @JsonProperty("port") int port,
@JsonProperty("username") Optional<String> username,
@JsonProperty("password") Optional<String> password) {
Header[] headers = {
new BasicHeader(HttpHeaders.CONTENT_TYPE, "application/json"),
new BasicHeader("Role", "Read")};
final RestClientBuilder restClientBuilder = RestClient.builder(new HttpHost(hostname, port))
.setDefaultHeaders(headers);
if (username.isPresent() && !username.get().isEmpty() && password.isPresent() && !password.get().isEmpty()) {
final CredentialsProvider credentialsProvider = new BasicCredentialsProvider();
credentialsProvider.setCredentials(
AuthScope.ANY,
new UsernamePasswordCredentials(username.get(), password.get())
);
restClientBuilder.setHttpClientConfigCallback(b -> b.setDefaultCredentialsProvider(credentialsProvider));
}
restClient = restClientBuilder.build();
mapper = new ObjectMapper();
}
@Test
public void shouldMakeRemoteGetCalls() {
Robolectric.getBackgroundScheduler().pause();
TestGetRequest apiRequest = new TestGetRequest();
apiGateway.makeRequest(apiRequest, responseCallbacks);
Robolectric.addPendingHttpResponse(200, GENERIC_XML);
Robolectric.getBackgroundScheduler().runOneTask();
HttpRequestInfo sentHttpRequestData = Robolectric.getSentHttpRequestInfo(0);
HttpRequest sentHttpRequest = sentHttpRequestData.getHttpRequest();
assertThat(sentHttpRequest.getRequestLine().getUri(), equalTo("www.example.com"));
assertThat(sentHttpRequest.getRequestLine().getMethod(), equalTo(HttpGet.METHOD_NAME));
assertThat(sentHttpRequest.getHeaders("foo")[0].getValue(), equalTo("bar"));
CredentialsProvider credentialsProvider =
(CredentialsProvider) sentHttpRequestData.getHttpContext().getAttribute(ClientContext.CREDS_PROVIDER);
assertThat(credentialsProvider.getCredentials(AuthScope.ANY).getUserPrincipal().getName(), CoreMatchers.equalTo("spongebob"));
assertThat(credentialsProvider.getCredentials(AuthScope.ANY).getPassword(), CoreMatchers.equalTo("squarepants"));
}
public static void modifyConcurrentUsersOnHttpServer(String restServerName, int numberOfUsers) throws Exception {
DefaultHttpClient client = new DefaultHttpClient();
client.getCredentialsProvider().setCredentials(new AuthScope(host, getAdminPort()),
new UsernamePasswordCredentials("admin", "admin"));
String extSecurityrName = "";
String body = "{\"group-name\": \"Default\", \"concurrent-request-limit\":\"" + numberOfUsers + "\"}";
HttpPut put = new HttpPut("http://" + host + ":" + admin_Port + "/manage/v2/servers/" + restServerName
+ "/properties?server-type=http");
put.addHeader("Content-type", "application/json");
put.setEntity(new StringEntity(body));
HttpResponse response2 = client.execute(put);
HttpEntity respEntity = response2.getEntity();
if (respEntity != null) {
String content = EntityUtils.toString(respEntity);
System.out.println(content);
}
client.getConnectionManager().shutdown();
}
protected void setProxy(HttpClient client) throws IOException {
File cfgfile = new File(NETCFG);
if (cfgfile.exists()) {
Properties cfg = new Properties();
cfg.load(new FileInputStream(cfgfile));
String ph = cfg.getProperty(PROXYHOST, null);
String pp = cfg.getProperty(PROXYPORT, null);
String pu = cfg.getProperty(PROXYUSER, null);
String pw = cfg.getProperty(PROXYPASS, null);
if (ph == null || pp == null) {
return;
}
final HttpHost proxy = new HttpHost(ph, Integer.parseInt(pp));
client.getParams().setParameter(ConnRoutePNames.DEFAULT_PROXY, proxy);
if (pu != null && pw != null) {
((DefaultHttpClient) client).getCredentialsProvider().setCredentials(
new AuthScope(proxy), new UsernamePasswordCredentials(pu, pw));
}
}
}
@Override
protected QueryExecutionFactory initQueryFactory() {
QueryExecutionFactory qef;
// if empty
if (username.isEmpty() && password.isEmpty()) {
qef = new QueryExecutionFactoryHttp(getSparqlEndpoint(), getSparqlGraphs());
} else {
DatasetDescription dd = new DatasetDescription(new ArrayList<>(getSparqlGraphs()), Collections.emptyList());
CredentialsProvider provider = new BasicCredentialsProvider();
UsernamePasswordCredentials credentials
= new UsernamePasswordCredentials(username, password);
provider.setCredentials(AuthScope.ANY, credentials);
HttpClient client = HttpClientBuilder.create()
.setDefaultCredentialsProvider(provider)
.build();
qef = new QueryExecutionFactoryHttp(getSparqlEndpoint(), dd, client);
}
return masqueradeQEF(qef, this);
}
@Override
public Observable<T> executeAsync(T request) {
CredentialsProvider provider = new BasicCredentialsProvider();
UsernamePasswordCredentials credentials
= new UsernamePasswordCredentials(config.getHttpAuthUser(), config.getHttpAuthPassword());
provider.setCredentials(AuthScope.ANY, credentials);
final URI location = config.getNexusUrl().resolve(config.getNexusUrl().getPath() + "/" + request.getRemoteLocation());
try (CloseableHttpClient client = HttpClientBuilder.create().setDefaultCredentialsProvider(provider).build()) {
LOG.info("[{} - {}]: Downloaded artifact {} to {}.", logConstant, request.getId(), request.getModuleId(), request.getLocalPath(config.getArtifactRepo()));
HttpUriRequest get = new HttpGet(location);
CloseableHttpResponse response = client.execute(get);
response.getEntity().writeTo(new FileOutputStream(request.getLocalPath(config.getArtifactRepo()).toFile()));
} catch (IOException e) {
LOG.error("[{} - {}]: Error downloading artifact -> {}, {}", logConstant, request.getId(), e.getMessage(), e);
throw new IllegalStateException(e);
}
return just(request);
}
private CredentialsProvider getCredentialsProvider() {
Project project = getProject();
HelmExtension extension = project.getExtensions().getByType(HelmExtension.class);
String helmUser = extension.getCredentials().getUser();
String helmPass = extension.getCredentials().getPass();
if (helmUser == null) {
throw new IllegalArgumentException("deployment.helmUser not specified");
}
if (helmPass == null) {
throw new IllegalArgumentException("deployment.helmPass not specified");
}
CredentialsProvider provider = new BasicCredentialsProvider();
UsernamePasswordCredentials credentials = new UsernamePasswordCredentials(helmUser, helmPass);
provider.setCredentials(AuthScope.ANY, credentials);
return provider;
}
public static String httpAuthPOST(String url, String user, String password, String agent, String type, String data) throws Exception {
HttpPost request = new HttpPost(url);
request.setHeader("User-Agent", agent);
StringEntity params = new StringEntity(data, "utf-8");
request.addHeader("content-type", type);
request.setEntity(params);
HttpParams httpParams = new BasicHttpParams();
HttpConnectionParams.setConnectionTimeout(httpParams, URL_TIMEOUT);
HttpConnectionParams.setSoTimeout(httpParams, URL_TIMEOUT);
DefaultHttpClient client = new DefaultHttpClient(httpParams);
client.getCredentialsProvider().setCredentials(
new AuthScope(AuthScope.ANY),
new UsernamePasswordCredentials(user, password));
HttpResponse response = client.execute(request);
return fetchResponse(response);
}
public static void main(String[] args) throws IOException {
// 设置Base Auth验证信息
CredentialsProvider provider = new BasicCredentialsProvider();
UsernamePasswordCredentials credentials = new UsernamePasswordCredentials("kermit", "kermit");
provider.setCredentials(AuthScope.ANY, credentials);
// 创建HttpClient
HttpClient client = HttpClientBuilder.create().setDefaultCredentialsProvider(provider).build();
// 发送请求
HttpResponse response = client.execute(new HttpGet(REST_URI));
HttpEntity entity = response.getEntity();
if (entity != null) {
String content = EntityUtils.toString(entity, "UTF-8");
System.out.println(content);
}
}
@BeforeClass
public static void startElasticsearchContainerAndClient() throws IOException {
// Start the container
container = new ElasticsearchContainer(ELASTICSEARCH_CONTAINER_VERSION);
container.start();
// Create the client
CredentialsProvider credentialsProvider = new BasicCredentialsProvider();
credentialsProvider.setCredentials(AuthScope.ANY, new UsernamePasswordCredentials(USER_NAME, PASSWORD));
RestClientBuilder builder = RestClient.builder(HttpHost.create(container.getHttpHostAddress()))
.setHttpClientConfigCallback(httpClientBuilder -> httpClientBuilder.setDefaultCredentialsProvider(credentialsProvider));
client = new RestHighLevelClient(builder);
client.indices().create(new CreateIndexRequest(INDEX), RequestOptions.DEFAULT);
reporter.reset();
}
/**
* Find matching {@link Credentials credentials} for the given authentication scope.
*
* @param map the credentials hash map
* @param authscope the {@link AuthScope authentication scope}
* @return the credentials
*/
private static Credentials matchCredentials(final Map<AuthScopeProxy, Credentials> map, final AuthScope authscope) {
Credentials creds = map.get(new AuthScopeProxy(authscope));
if (creds == null) {
int bestMatchFactor = -1;
AuthScopeProxy bestMatch = null;
for (final AuthScopeProxy proxy : map.keySet()) {
final AuthScope current = proxy.getAuthScope();
final int factor = authscope.match(current);
if (factor > bestMatchFactor) {
bestMatchFactor = factor;
bestMatch = proxy;
}
}
if (bestMatch != null) {
creds = map.get(bestMatch);
}
}
return creds;
}
private AuthScope getAuthScope() {
if (StringUtil.isBlank(getHostname())) {
return AuthScope.ANY;
}
int p;
if (getPort() == null) {
p = AuthScope.ANY_PORT;
} else {
p = getPort();
}
String r = getAuthRealm();
if (StringUtil.isBlank(r)) {
r = AuthScope.ANY_REALM;
}
String s = getProtocolScheme();
if (StringUtil.isBlank(s) || Constants.NTLM.equals(s)) {
s = AuthScope.ANY_SCHEME;
}
return new AuthScope(getHostname(), p, r, s);
}
public static void deleteElementRangeIndexTemporalCollection(String dbName, String collectionName)
throws Exception {
DefaultHttpClient client = new DefaultHttpClient();
client.getCredentialsProvider().setCredentials(new AuthScope(host_name, getAdminPort()),
new UsernamePasswordCredentials("admin", "admin"));
HttpDelete del = new HttpDelete("http://" + host_name + ":" + admin_port + "/manage/v2/databases/" + dbName
+ "/temporal/collections?collection=" + collectionName + "&format=json");
del.addHeader("Content-type", "application/json");
del.addHeader("accept", "application/json");
HttpResponse response = client.execute(del);
HttpEntity respEntity = response.getEntity();
if (response.getStatusLine().getStatusCode() == 400) {
HttpEntity entity = response.getEntity();
String responseString = EntityUtils.toString(entity, "UTF-8");
System.out.println(responseString);
} else if (respEntity != null) {
// EntityUtils to get the response content
String content = EntityUtils.toString(respEntity);
System.out.println(content);
} else {
System.out.println("Collection: " + collectionName + " deleted");
System.out.println("==============================================================");
}
client.getConnectionManager().shutdown();
}
protected HttpClientBuilder withUsernameAndPassword(HttpClientBuilder httpClientBuilder, String username, String password) {
if(username != null && password != null) {
logger.debug("{}: username={} password={}", applianceId, username, password);
CredentialsProvider provider = new BasicCredentialsProvider();
UsernamePasswordCredentials credentials = new UsernamePasswordCredentials(username, password);
provider.setCredentials(AuthScope.ANY, credentials);
httpClientBuilder.setDefaultCredentialsProvider(provider);
}
return httpClientBuilder;
}
@org.junit.Test
public void testNoEndpointAddressOrConstraint() throws Exception {
String url = "https://localhost:" + getIdpHttpsPort() + "/fediz-idp/federation?";
url += "wa=wsignin1.0";
url += "&whr=urn:org:apache:cxf:fediz:idp:realm-A";
url += "&wtrealm=urn:org:apache:cxf:fediz:fedizhelloworld4";
String wreply = "https://localhost:" + getRpHttpsPort() + "/" + getServletContextName() + "/secure/fedservlet";
url += "&wreply=" + wreply;
String user = "alice";
String password = "ecila";
final WebClient webClient = new WebClient();
webClient.getOptions().setUseInsecureSSL(true);
webClient.getCredentialsProvider().setCredentials(
new AuthScope("localhost", Integer.parseInt(getIdpHttpsPort())),
new UsernamePasswordCredentials(user, password));
webClient.getOptions().setJavaScriptEnabled(false);
// This is an error in the IdP
try {
webClient.getPage(url);
Assert.fail("Failure expected on a bad wreply value");
} catch (FailingHttpStatusCodeException ex) {
Assert.assertEquals(ex.getStatusCode(), 400);
}
webClient.close();
}
private void configUserNameAndPassowrd(RestClientBuilder builder) {
String username = JPressOptions.get("article_search_es_username");
String password = JPressOptions.get("article_search_es_password");
if (StrUtil.isBlank(username) || StrUtil.isBlank(password)) {
return;
}
CredentialsProvider credentialsProvider = new BasicCredentialsProvider();
credentialsProvider.setCredentials(AuthScope.ANY, new UsernamePasswordCredentials(username, username));
builder.setHttpClientConfigCallback(httpAsyncClientBuilder ->
httpAsyncClientBuilder.setDefaultCredentialsProvider(credentialsProvider));
}
private static void setupUserPassAuthScheme(AuthScheme scheme, String httpScheme, AuthSchemeProvider provider, ConfigProvider configuration)
{
String username = configuration.getProperty(scheme, "username");
String password = configuration.getProperty(scheme, "password");
if ((username != null) && (password != null)) {
LOG.info("Setting up scheme {}", scheme);
AuthScope authScope = new AuthScope(AuthScope.ANY_HOST, AuthScope.ANY_PORT, AuthScope.ANY_REALM, httpScheme);
Credentials credentials = new UsernamePasswordCredentials(username, password);
setupHttpAuthScheme(httpScheme, provider, authScope, credentials);
} else if ((username != null) || (password != null)) {
LOG.warn("Not setting up scheme {}, missing credentials {}", scheme, (username == null) ? "username" : "password");
}
}
private static void updateProxySetting(HttpConfig config, DefaultHttpClient httpClient) {
if (config == null || httpClient == null){
return;
}
HttpHost[] proxyChain = null;
if (globalProxy != null) {
//全局代理设置
proxyChain = new HttpHost[] {globalProxy};
if (globalProxyCredentials != null){
AuthScope globalProxyAuthScope = new AuthScope(globalProxy.getHostName(), globalProxy.getPort());
httpClient.getCredentialsProvider().setCredentials(globalProxyAuthScope, globalProxyCredentials);
}
}
if (config.isUseProxy() && StringUtil.isNotEmpty(config.getHttpProxyHost())){
HttpHost spProxy = new HttpHost(config.getHttpProxyHost(), config.getHttpProxyPort());
if (globalProxy != null){
proxyChain = new HttpHost[] {globalProxy, spProxy};
} else {
proxyChain = new HttpHost[] {spProxy};
}
if (StringUtil.isNotEmpty(config.getHttpProxyUser())){
AuthScope spProxyAuthScope = new AuthScope(spProxy.getHostName(), spProxy.getPort());
UsernamePasswordCredentials spProxyCredentials = new UsernamePasswordCredentials(
config.getHttpProxyUser(), config.getHttpProxyPassword());
httpClient.getCredentialsProvider().setCredentials(spProxyAuthScope, spProxyCredentials);
}
}
httpClient.setRoutePlanner(new LibHttpRoutePlanner(connectionManager.getSchemeRegistry(), proxyChain));
}
@Override
public SPARQLExecutionResult call() {
Map<String, Set<String>> resultSet = new HashMap<>();
markers.forEach(marker -> resultSet.put(marker, new HashSet<>()));
Model unionModel = ModelFactory.createDefaultModel();
SPARQLServiceConverter converter = new SPARQLServiceConverter(schema);
String sparqlQuery = converter.getSelectQuery(query, inputSubset, rootType);
logger.info(sparqlQuery);
CredentialsProvider credsProvider = new BasicCredentialsProvider();
Credentials credentials =
new UsernamePasswordCredentials(this.sparqlEndpointService.getUser(), this.sparqlEndpointService.getPassword());
credsProvider.setCredentials(AuthScope.ANY, credentials);
HttpClient httpclient = HttpClients.custom()
.setDefaultCredentialsProvider(credsProvider)
.build();
HttpOp.setDefaultHttpClient(httpclient);
Query jenaQuery = QueryFactory.create(sparqlQuery);
QueryEngineHTTP qEngine = QueryExecutionFactory.createServiceRequest(this.sparqlEndpointService.getUrl(), jenaQuery);
qEngine.setClient(httpclient);
ResultSet results = qEngine.execSelect();
results.forEachRemaining(solution -> {
markers.stream().filter(solution::contains).forEach(marker ->
resultSet.get(marker).add(solution.get(marker).asResource().getURI()));
unionModel.add(this.sparqlEndpointService.getModelFromResults(query, solution, schema));
});
SPARQLExecutionResult sparqlExecutionResult = new SPARQLExecutionResult(resultSet, unionModel);
logger.info(sparqlExecutionResult);
return sparqlExecutionResult;
}
private static HttpClientBuilder provideHttpBuilder(final InfluxDBSettings settings) {
final HttpClientBuilder builder = HttpClientBuilder.create();
if (isNoneBlank(settings.userName, settings.userPassword)) {
final CredentialsProvider provider = new BasicCredentialsProvider();
provider.setCredentials(
AuthScope.ANY, new UsernamePasswordCredentials(settings.userName, settings.userPassword));
builder.setDefaultCredentialsProvider(provider);
}
return builder;
}
public InputStream getStream(String baseUrl, RasterLayer layer) throws IOException {
String url = baseUrl;
HttpContext context = null;
if (layer instanceof ProxyLayerSupport) {
context = new BasicHttpContext();
// pass url and layer id to the CompositeInterceptor
context.setAttribute(CompositeInterceptor.BASE_URL, baseUrl);
context.setAttribute(CompositeInterceptor.LAYER_ID, layer.getId());
// handle proxy authentication and interceptors
ProxyLayerSupport proxyLayer = (ProxyLayerSupport) layer;
ProxyAuthentication authentication = proxyLayer.getProxyAuthentication();
url = addCredentialsToUrl(baseUrl, authentication);
// -- add basic authentication
if (null != authentication
&& (ProxyAuthenticationMethod.BASIC.equals(authentication.getMethod()) ||
ProxyAuthenticationMethod.DIGEST.equals(authentication.getMethod()))) {
// Set up the credentials:
Credentials creds = new UsernamePasswordCredentials(authentication.getUser(),
authentication.getPassword());
URL u = new URL(url);
AuthScope scope = new AuthScope(u.getHost(), u.getPort(), authentication.getRealm());
// thread-safe, this is ok
client.getCredentialsProvider().setCredentials(scope, creds);
}
}
// Create the GET method with the correct URL:
HttpGet get = new HttpGet(url);
// Execute the GET:
HttpResponse response = client.execute(get, context);
log.debug("Response: {} - {}", response.getStatusLine().getStatusCode(), response.getStatusLine()
.getReasonPhrase());
return response.getEntity().getContent();
}
private void createClient() {
try {
final CredentialsProvider credentialsProvider;
if (StringUtils.isNotBlank(user)) {
credentialsProvider = new BasicCredentialsProvider();
credentialsProvider.setCredentials(AuthScope.ANY, new UsernamePasswordCredentials(user, password));
} else {
credentialsProvider = null;
}
client = new RestHighLevelClient(RestClient
.builder(EmbeddedServerUtil.toArray(hosts, ",").stream().map(x -> new HttpHost(x, port, protocol))
.<HttpHost>toArray(i -> new HttpHost[i]))
.setHttpClientConfigCallback(clientBuilder -> (credentialsProvider != null)
? clientBuilder.setDefaultCredentialsProvider(credentialsProvider)
: clientBuilder));
} catch (Throwable t) {
lastLoggedAt.updateAndGet(lastLoggedAt -> {
long now = System.currentTimeMillis();
long elapsed = now - lastLoggedAt;
if (elapsed > TimeUnit.MINUTES.toMillis(1)) {
LOG.severe("Can't connect to ElasticSearch server: " + connectionString() + t);
return now;
} else {
return lastLoggedAt;
}
});
}
}