org.apache.http.client.CredentialsProvider Java Examples

The following examples show how to use org.apache.http.client.CredentialsProvider. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: NexusArtifactClient.java    From cubeai with Apache License 2.0 8 votes vote down vote up
public boolean deleteArtifact(String longUrl) {
    try {
        CloseableHttpClient httpClient;
        if (getUserName() != null && getPassword() != null) {
            URL url = new URL(getUrl());
            HttpHost httpHost = new HttpHost(url.getHost(), url.getPort());
            CredentialsProvider credsProvider = new BasicCredentialsProvider();
            credsProvider.setCredentials(new AuthScope(httpHost),
                new UsernamePasswordCredentials(getUserName(), getPassword()));
            httpClient = HttpClientBuilder.create().setDefaultCredentialsProvider(credsProvider).build();
        } else {
            httpClient = HttpClientBuilder.create().build();
        }
        RestTemplate restTemplate = new RestTemplate(new HttpComponentsClientHttpRequestFactory(httpClient));
        restTemplate.delete(new URI(longUrl));
    } catch (Exception e) {
        return false;
    }
    return true;
}
 
Example #2
Source File: ElasticsearchConnection.java    From components with Apache License 2.0 6 votes vote down vote up
public static RestClient createClient(ElasticsearchDatastoreProperties datastore) throws MalformedURLException {
    String urlStr = datastore.nodes.getValue();
    String[] urls = urlStr.split(",");
    HttpHost[] hosts = new HttpHost[urls.length];
    int i = 0;
    for (String address : urls) {
        URL url = new URL("http://" + address);
        hosts[i] = new HttpHost(url.getHost(), url.getPort(), url.getProtocol());
        i++;
    }
    RestClientBuilder restClientBuilder = RestClient.builder(hosts);
    if (datastore.auth.useAuth.getValue()) {
        final CredentialsProvider credentialsProvider = new BasicCredentialsProvider();
        credentialsProvider.setCredentials(AuthScope.ANY,
                new UsernamePasswordCredentials(datastore.auth.userId.getValue(), datastore.auth.password.getValue()));
        restClientBuilder.setHttpClientConfigCallback(new RestClientBuilder.HttpClientConfigCallback() {

            public HttpAsyncClientBuilder customizeHttpClient(HttpAsyncClientBuilder httpAsyncClientBuilder) {
                return httpAsyncClientBuilder.setDefaultCredentialsProvider(credentialsProvider);
            }
        });
    }
    return restClientBuilder.build();
}
 
Example #3
Source File: SslTrustCorporateProxyHttpClient.java    From zerocode with Apache License 2.0 6 votes vote down vote up
@Override
public CloseableHttpClient createHttpClient() throws NoSuchAlgorithmException, KeyManagementException, KeyStoreException {
    LOGGER.info("###Used SSL Enabled Http Client with Corporate Proxy, for both Http and Https connections");

    SSLContext sslContext = new SSLContextBuilder()
            .loadTrustMaterial(null, (certificate, authType) -> true).build();

    CookieStore cookieStore = new BasicCookieStore();

    CredentialsProvider credsProvider = createProxyCredentialsProvider(proxyHost, proxyPort, proxyUserName, proxyPassword);

    HttpHost proxy = new HttpHost(proxyHost, proxyPort);

    return HttpClients.custom()
            .setSSLContext(sslContext)
            .setSSLHostnameVerifier(new NoopHostnameVerifier())
            .setDefaultCookieStore(cookieStore)
            .setDefaultCredentialsProvider(credsProvider)
            .setProxy(proxy)
            .build();
}
 
Example #4
Source File: ContextCredentialsConfigurationRegistrarTest.java    From spring-cloud-aws with Apache License 2.0 6 votes vote down vote up
@Test
void credentialsProvider_configWithInstanceProfile_instanceProfileCredentialsProviderConfigured()
		throws Exception {
	// Arrange
	this.context = new AnnotationConfigApplicationContext(
			ApplicationConfigurationWithInstanceProfileOnly.class);

	// Act
	AWSCredentialsProvider awsCredentialsProvider = this.context
			.getBean(AWSCredentialsProvider.class);

	// Assert
	assertThat(awsCredentialsProvider).isNotNull();

	@SuppressWarnings("unchecked")
	List<CredentialsProvider> credentialsProviders = (List<CredentialsProvider>) ReflectionTestUtils
			.getField(awsCredentialsProvider, "credentialsProviders");
	assertThat(credentialsProviders.size()).isEqualTo(1);
	assertThat(EC2ContainerCredentialsProviderWrapper.class
			.isInstance(credentialsProviders.get(0))).isTrue();
}
 
Example #5
Source File: BasicCredentialsTest.java    From log4j2-elasticsearch with Apache License 2.0 6 votes vote down vote up
@Test
public void objectIsConfiguredWhenAllParamsAreSet() {

    // given
    BasicCredentials BasicCredentials = createTestBuilder()
            .withUsername(TEST_USER)
            .withPassword(TEST_PASSWORD)
            .build();

    HttpClientFactory.Builder settings = spy(createDefaultTestObjectBuilder());

    // when
    BasicCredentials.applyTo(settings);

    // then
    verify(settings).withDefaultCredentialsProvider((CredentialsProvider) notNull());

}
 
Example #6
Source File: ApacheUtils.java    From ibm-cos-sdk-java with Apache License 2.0 6 votes vote down vote up
private static void addPreemptiveAuthenticationProxy(HttpClientContext clientContext,
                                                     HttpClientSettings settings) {

    if (settings.isPreemptiveBasicProxyAuth()) {
        HttpHost targetHost = new HttpHost(settings.getProxyHost(), settings
                .getProxyPort());
        final CredentialsProvider credsProvider = newProxyCredentialsProvider(settings);
        // 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);

        clientContext.setCredentialsProvider(credsProvider);
        clientContext.setAuthCache(authCache);
    }
}
 
Example #7
Source File: ElasticsearchRestClientInstrumentationIT.java    From apm-agent-java with Apache License 2.0 6 votes vote down vote up
@BeforeClass
public static void startElasticsearchContainerAndClient() throws IOException {
    // Start the container
    container = new ElasticsearchContainer(ELASTICSEARCH_CONTAINER_VERSION);
    container.start();

    final 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));
    lowLevelClient = builder.build();
    client = new RestHighLevelClient(lowLevelClient);

    lowLevelClient.performRequest("PUT", "/" + INDEX);
    reporter.reset();
}
 
Example #8
Source File: AbstractCheckThread.java    From sitemonitoring-production with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
protected CloseableHttpClient buildHttpClient() {
	HttpClientBuilder httpClientBuilder = HttpClients.custom();
	CredentialsProvider credsProvider = new BasicCredentialsProvider();

	try {
		Credentials credentials = check.getCredentials();
		if (credentials != null) {
			basicAuthentication(httpClientBuilder, credsProvider, credentials);
		}
	} catch (Exception ex) {
		throw new RuntimeException("Could not use credentials");
	}
	// set proxy
	if (check.getHttpProxyUsername() != null && !check.getHttpProxyPassword().isEmpty()) {
		credsProvider.setCredentials(new AuthScope(check.getHttpProxyServer(), check.getHttpProxyPort()),
				new UsernamePasswordCredentials(check.getHttpProxyUsername(), check.getHttpProxyPassword()));
		httpClientBuilder.setDefaultCredentialsProvider(credsProvider);
	}
	return httpClientBuilder.build();
}
 
Example #9
Source File: HttpClientConfigurer.java    From pushfish-android with BSD 2-Clause "Simplified" License 6 votes vote down vote up
public void process(final HttpRequest request, final HttpContext context) throws HttpException, IOException {

            AuthState authState = (AuthState) context.getAttribute(ClientContext.TARGET_AUTH_STATE);

            if (authState.getAuthScheme() != null || authState.hasAuthOptions()) {
                return;
            }

            // If no authState has been established and this is a PUT or POST request, add preemptive authorisation
            String requestMethod = request.getRequestLine().getMethod();
            if (requestMethod.equals(HttpPut.METHOD_NAME) || requestMethod.equals(HttpPost.METHOD_NAME)) {
                CredentialsProvider credentialsProvider = (CredentialsProvider) context.getAttribute(ClientContext.CREDS_PROVIDER);
                HttpHost targetHost = (HttpHost) context.getAttribute(ExecutionContext.HTTP_TARGET_HOST);
                Credentials credentials = credentialsProvider.getCredentials(new AuthScope(targetHost.getHostName(), targetHost.getPort()));
                if (credentials == null) {
                    throw new HttpException("No credentials for preemptive authentication");
                }
                authState.update(authScheme, credentials);
            }
        }
 
Example #10
Source File: GeoServerIT.java    From geowave with Apache License 2.0 6 votes vote down vote up
protected static Pair<CloseableHttpClient, HttpClientContext> createClientAndContext() {
  final CredentialsProvider provider = new BasicCredentialsProvider();
  provider.setCredentials(
      new AuthScope("localhost", ServicesTestEnvironment.JETTY_PORT),
      new UsernamePasswordCredentials(
          ServicesTestEnvironment.GEOSERVER_USER,
          ServicesTestEnvironment.GEOSERVER_PASS));
  final AuthCache authCache = new BasicAuthCache();
  final HttpHost targetHost =
      new HttpHost("localhost", ServicesTestEnvironment.JETTY_PORT, "http");
  authCache.put(targetHost, new BasicScheme());

  // Add AuthCache to the execution context
  final HttpClientContext context = HttpClientContext.create();
  context.setCredentialsProvider(provider);
  context.setAuthCache(authCache);
  return ImmutablePair.of(
      HttpClientBuilder.create().setDefaultCredentialsProvider(provider).build(),
      context);
}
 
Example #11
Source File: ElasticsearchAuditLogSink.java    From Groza with Apache License 2.0 6 votes vote down vote up
@PostConstruct
public void init() {
    try {
        log.trace("Adding elastic rest endpoint... host [{}], port [{}], scheme name [{}]",
                host, port, schemeName);
        RestClientBuilder builder = RestClient.builder(
                new HttpHost(host, port, schemeName));

        if (StringUtils.isNotEmpty(userName) &&
                StringUtils.isNotEmpty(password)) {
            log.trace("...using username [{}] and password ***", userName);
            final CredentialsProvider credentialsProvider = new BasicCredentialsProvider();
            credentialsProvider.setCredentials(AuthScope.ANY,
                    new UsernamePasswordCredentials(userName, password));
            builder.setHttpClientConfigCallback(httpClientBuilder -> httpClientBuilder.setDefaultCredentialsProvider(credentialsProvider));
        }

        this.restClient = builder.build();
    } catch (Exception e) {
        log.error("Sink init failed!", e);
        throw new RuntimeException(e.getMessage(), e);
    }
}
 
Example #12
Source File: HttpSender.java    From cloudhopper-commons with Apache License 2.0 6 votes vote down vote up
public void process(final HttpRequest request, final HttpContext context) throws HttpException, IOException {
    
    AuthState authState = (AuthState) context.getAttribute(ClientContext.TARGET_AUTH_STATE);
    
    // If no auth scheme avaialble yet, try to initialize it preemptively
    if (authState.getAuthScheme() == null) {
        AuthScheme authScheme = (AuthScheme) context.getAttribute("preemptive-auth");
        CredentialsProvider credsProvider = (CredentialsProvider) context.getAttribute(ClientContext.CREDS_PROVIDER);
        HttpHost targetHost = (HttpHost) context.getAttribute(ExecutionContext.HTTP_TARGET_HOST);
        if (authScheme != null) {
            Credentials creds = credsProvider.getCredentials(new AuthScope(targetHost.getHostName(), targetHost.getPort()));
            if (creds == null) {
                throw new HttpException("No credentials for preemptive authentication");
            }
            authState.setAuthScheme(authScheme);
            authState.setCredentials(creds);
        }
    }
    
}
 
Example #13
Source File: SPARQLProtocolSession.java    From rdf4j with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
protected void setUsernameAndPasswordForUrl(String username, String password, String url) {

		if (username != null && password != null) {
			logger.debug("Setting username '{}' and password for server at {}.", username, url);
			java.net.URI requestURI = java.net.URI.create(url);
			String host = requestURI.getHost();
			int port = requestURI.getPort();
			AuthScope scope = new AuthScope(host, port);
			UsernamePasswordCredentials cred = new UsernamePasswordCredentials(username, password);
			CredentialsProvider credsProvider = new BasicCredentialsProvider();
			credsProvider.setCredentials(scope, cred);
			httpContext.setCredentialsProvider(credsProvider);
			AuthCache authCache = new BasicAuthCache();
			BasicScheme basicAuth = new BasicScheme();
			HttpHost httpHost = new HttpHost(requestURI.getHost(), requestURI.getPort(), requestURI.getScheme());
			authCache.put(httpHost, basicAuth);
			httpContext.setAuthCache(authCache);
		} else {
			httpContext.removeAttribute(HttpClientContext.AUTH_CACHE);
			httpContext.removeAttribute(HttpClientContext.CREDS_PROVIDER);
		}
	}
 
Example #14
Source File: DigestAuthHandler.java    From restfiddle with Apache License 2.0 6 votes vote down vote up
public void setCredentialsProvider(RfRequestDTO requestDTO, HttpClientBuilder clientBuilder) {
DigestAuthDTO digestAuthDTO = requestDTO.getDigestAuthDTO();
if (digestAuthDTO == null) {
    return;
}
String userName = digestAuthDTO.getUsername();
String password = digestAuthDTO.getPassword();
if (userName == null || userName.isEmpty() || password == null || password.isEmpty()) {
    return;
}
CredentialsProvider credentialsProvider = new BasicCredentialsProvider();
credentialsProvider.setCredentials(new AuthScope(AuthScope.ANY_HOST, AuthScope.ANY_PORT, AuthScope.ANY_REALM),
	new UsernamePasswordCredentials(userName, password));

clientBuilder.setDefaultCredentialsProvider(credentialsProvider);
   }
 
Example #15
Source File: SlackNotificationImpl.java    From tcSlackBuildNotifier with MIT License 6 votes vote down vote up
public void setProxy(String proxyHost, Integer proxyPort, Credentials credentials) {
      this.proxyHost = proxyHost;
      this.proxyPort = proxyPort;
      
if (this.proxyHost.length() > 0 && !this.proxyPort.equals(0)) {
          HttpClientBuilder clientBuilder = HttpClients.custom()
              .useSystemProperties()
              .setProxy(new HttpHost(proxyHost, proxyPort, "http"));
              
          if (credentials != null) {
              CredentialsProvider credsProvider = new BasicCredentialsProvider();
              credsProvider.setCredentials(new AuthScope(proxyHost, proxyPort), credentials);
              clientBuilder.setDefaultCredentialsProvider(credsProvider);
              Loggers.SERVER.debug("SlackNotification ::using proxy credentials " + credentials.getUserPrincipal().getName());
          }
          
          this.client = clientBuilder.build();
}
  }
 
Example #16
Source File: AsyncClientAuthentication.java    From yunpian-java-sdk with MIT License 6 votes vote down vote up
public static void main(String[] args) throws Exception {
    CredentialsProvider credsProvider = new BasicCredentialsProvider();
    credsProvider.setCredentials(new AuthScope("localhost", 443),
            new UsernamePasswordCredentials("username", "password"));
    CloseableHttpAsyncClient httpclient = HttpAsyncClients.custom().setDefaultCredentialsProvider(credsProvider)
            .build();
    try {
        HttpGet httpget = new HttpGet("http://localhost/");

        System.out.println("Executing request " + httpget.getRequestLine());
        Future<HttpResponse> future = httpclient.execute(httpget, null);
        HttpResponse response = future.get();
        System.out.println("Response: " + response.getStatusLine());
        System.out.println("Shutting down");
    } finally {
        httpclient.close();
    }
}
 
Example #17
Source File: AbstractCheckThread.java    From sitemonitoring-production with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
protected CloseableHttpClient buildHttpClient() {
	HttpClientBuilder httpClientBuilder = HttpClients.custom();
	CredentialsProvider credsProvider = new BasicCredentialsProvider();

	try {
		Credentials credentials = check.getCredentials();
		if (credentials != null) {
			basicAuthentication(httpClientBuilder, credsProvider, credentials);
		}
	} catch (Exception ex) {
		throw new RuntimeException("Could not use credentials");
	}
	// set proxy
	if (check.getHttpProxyUsername() != null && !check.getHttpProxyPassword().isEmpty()) {
		credsProvider.setCredentials(new AuthScope(check.getHttpProxyServer(), check.getHttpProxyPort()),
				new UsernamePasswordCredentials(check.getHttpProxyUsername(), check.getHttpProxyPassword()));
		httpClientBuilder.setDefaultCredentialsProvider(credsProvider);
	}
	return httpClientBuilder.build();
}
 
Example #18
Source File: HttpService.java    From arcusplatform with Apache License 2.0 6 votes vote down vote up
public static CloseableHttpResponse execute(HttpUriRequest req, @Nullable Credentials auth) throws IOException {
   if (auth != null) {
      URI uri = req.getURI();
      AuthScope scope = new AuthScope(uri.getHost(), uri.getPort());

      CredentialsProvider provider = new BasicCredentialsProvider();
      provider.setCredentials(scope, auth);

      HttpClientContext context = HttpClientContext.create();
      context.setCredentialsProvider(provider);

      return get().execute(req, context);
   }

   return execute(req);
}
 
Example #19
Source File: ElasticsearchClientFactory.java    From metron with Apache License 2.0 6 votes vote down vote up
private static CredentialsProvider getCredentialsProvider(
    ElasticsearchClientConfig esClientConfig) {
  Optional<Entry<String, String>> credentials = esClientConfig.getCredentials();
  if (credentials.isPresent()) {
    LOG.info(
        "Found auth credentials - setting up user/pass authenticated client connection for ES.");
    final CredentialsProvider credentialsProvider = new BasicCredentialsProvider();
    UsernamePasswordCredentials upcredentials = new UsernamePasswordCredentials(
        credentials.get().getKey(), credentials.get().getValue());
    credentialsProvider.setCredentials(AuthScope.ANY, upcredentials);
    return credentialsProvider;
  } else {
    LOG.info(
        "Elasticsearch client credentials not provided. Defaulting to non-authenticated client connection.");
    return null;
  }
}
 
Example #20
Source File: ElasticsearchCollector.java    From Quicksql with MIT License 6 votes vote down vote up
private static RestClient connect(Map<String, Integer> coordinates,
    Map<String, String> userConfig) {
    Objects.requireNonNull(coordinates, "coordinates");
    Preconditions.checkArgument(! coordinates.isEmpty(), "no ES coordinates specified");
    final Set<HttpHost> set = new LinkedHashSet<>();
    for (Map.Entry<String, Integer> entry : coordinates.entrySet()) {
        set.add(new HttpHost(entry.getKey(), entry.getValue()));
    }

    final CredentialsProvider credentialsProvider = new BasicCredentialsProvider();
    credentialsProvider.setCredentials(AuthScope.ANY,
        new UsernamePasswordCredentials(userConfig.getOrDefault("esUser", "none"),
            userConfig.getOrDefault("esPass", "none")));

    return RestClient.builder(set.toArray(new HttpHost[0]))
        .setHttpClientConfigCallback(httpClientBuilder ->
            httpClientBuilder.setDefaultCredentialsProvider(credentialsProvider))
        .setMaxRetryTimeoutMillis(300000).build();
}
 
Example #21
Source File: HDInsightInstance.java    From reef with Apache License 2.0 6 votes vote down vote up
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;
}
 
Example #22
Source File: ResolveSnapshotVersion.java    From vertx-deploy-tools with Apache License 2.0 6 votes vote down vote up
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.getMetadataLocation());
    HttpUriRequest get = new HttpGet(location);

    Path filename = createTempFile(request.getArtifactId());

    try (CloseableHttpClient client = HttpClientBuilder.create().setDefaultCredentialsProvider(provider).build();
         CloseableHttpResponse response = client.execute(get)) {
        LOG.info("[{} - {}]: Downloaded Metadata for {}.", LogConstants.DEPLOY_ARTIFACT_REQUEST, request.getId(), request.getModuleId());
        response.getEntity().writeTo(new FileOutputStream(filename.toFile()));
        request.setVersion(retrieveAndParseMetadata(filename, request));
    } catch (IOException e) {
        LOG.error("[{} - {}]: Error downloading Metadata  -> {}, {}", LogConstants.DEPLOY_ARTIFACT_REQUEST, request.getId(), e.getMessage(), e);
        throw new IllegalStateException(e);
    }
    return just(request);
}
 
Example #23
Source File: WxMpServiceImpl.java    From weixin-java-tools with Apache License 2.0 5 votes vote down vote up
public void setWxMpConfigStorage(WxMpConfigStorage wxConfigProvider) {
  this.wxMpConfigStorage = wxConfigProvider;

  String http_proxy_host = wxMpConfigStorage.getHttp_proxy_host();
  int http_proxy_port = wxMpConfigStorage.getHttp_proxy_port();
  String http_proxy_username = wxMpConfigStorage.getHttp_proxy_username();
  String http_proxy_password = wxMpConfigStorage.getHttp_proxy_password();

  final HttpClientBuilder builder = HttpClients.custom();
  if (StringUtils.isNotBlank(http_proxy_host)) {
    // 使用代理服务器
    if (StringUtils.isNotBlank(http_proxy_username)) {
      // 需要用户认证的代理服务器
      CredentialsProvider credsProvider = new BasicCredentialsProvider();
      credsProvider.setCredentials(
          new AuthScope(http_proxy_host, http_proxy_port),
          new UsernamePasswordCredentials(http_proxy_username, http_proxy_password));
      builder
          .setDefaultCredentialsProvider(credsProvider);
    } else {
      // 无需用户认证的代理服务器
    }
    httpProxy = new HttpHost(http_proxy_host, http_proxy_port);
  }
  if (wxConfigProvider.getSSLContext() != null){
    SSLConnectionSocketFactory sslsf = new SSLConnectionSocketFactory(
        wxConfigProvider.getSSLContext(),
        new String[] { "TLSv1" },
        null,
        SSLConnectionSocketFactory.BROWSER_COMPATIBLE_HOSTNAME_VERIFIER);
    builder.setSSLSocketFactory(sslsf);
  }
  httpClient = builder.build();
}
 
Example #24
Source File: CommonsXmlRpcTransport.java    From oodt with Apache License 2.0 5 votes vote down vote up
public CommonsXmlRpcTransport(URL url, HttpClient client) {
    this.userAgentHeader = new BasicHeader("User-Agent", "Apache XML-RPC 2.0");
    this.http11 = false;
    this.gzip = false;
    this.rgzip = false;
    this.url = url;
    if(client == null) {
        RequestConfig config = RequestConfig.custom()
                .setSocketTimeout(timeout * 1000)
                .setConnectTimeout(connecttimeout * 1000)
                .build();
        CredentialsProvider credsProvider = new BasicCredentialsProvider();
        if(!user.equals(null)) {
            credsProvider.setCredentials(AuthScope.ANY, new UsernamePasswordCredentials(user));
        }
        else if(!user.equals(null)&& !password.equals(null)){
            credsProvider.setCredentials(AuthScope.ANY, new UsernamePasswordCredentials(user, password));
        }
        else if(!auth.equals(null)){

        }

        System.out.println("building empty registry");
        Registry<AuthSchemeProvider> r = RegistryBuilder.<AuthSchemeProvider>create().build();
        HttpClient newClient = HttpClients.custom().setDefaultAuthSchemeRegistry(r).setDefaultCredentialsProvider(credsProvider).setDefaultRequestConfig(config).build();
        this.client = newClient;
    } else {
        this.client = client;
    }

}
 
Example #25
Source File: ElasticSearchClient.java    From scava with Eclipse Public License 2.0 5 votes vote down vote up
private boolean createClientDocker()
{
	CredentialsProvider credentialsProvider = new BasicCredentialsProvider();
	credentialsProvider.setCredentials(AuthScope.ANY, new UsernamePasswordCredentials("admin", "admin"));
	
	TrustStrategy trustStrategy = new TrustSelfSignedStrategy();
	SSLContext sslContext;
	try {
		sslContext = SSLContexts.custom().loadTrustMaterial(trustStrategy).build();
		HostnameVerifier hostnameVerifier = NoopHostnameVerifier.INSTANCE;
		
		RestClientBuilder restClientBuilder = createRestClientBuilder(hostname, scheme);
		
		restClientBuilder.setHttpClientConfigCallback(new HttpClientConfigCallback() {
			@Override
			public HttpAsyncClientBuilder customizeHttpClient(HttpAsyncClientBuilder httpClientBuilder) {
				httpClientBuilder.setSSLContext(sslContext).setSSLHostnameVerifier(hostnameVerifier).build();
				httpClientBuilder.setDefaultCredentialsProvider(credentialsProvider);
				return httpClientBuilder;
			}
		});

		return createHighLevelClient(restClientBuilder);
	} catch (KeyManagementException | NoSuchAlgorithmException | KeyStoreException e) {
		logger.error("Error while creating secure connection to ElasticSearch: ", e);
	}
	
	return false;
}
 
Example #26
Source File: ServerContext.java    From azure-devops-intellij with MIT License 5 votes vote down vote up
public synchronized HttpClient getHttpClient() {
    checkDisposed();
    if (httpClient == null && authenticationInfo != null) {
        final Credentials credentials = AuthHelper.getCredentials(type, authenticationInfo);
        final CredentialsProvider credentialsProvider = new BasicCredentialsProvider();
        credentialsProvider.setCredentials(AuthScope.ANY, credentials);
        final HttpClientBuilder httpClientBuilder = HttpClientBuilder.create()
                .setSSLContext(PluginServiceProvider.getInstance().getCertificateService().getSSLContext());

        httpClient = httpClientBuilder.setDefaultCredentialsProvider(credentialsProvider).build();
    }
    return httpClient;
}
 
Example #27
Source File: JolokiaClientFactory.java    From hawkular-agent with Apache License 2.0 5 votes vote down vote up
@Override
public void authenticate(HttpClientBuilder pBuilder, String pUser, String pPassword) {
    CredentialsProvider credentialsProvider = new BasicCredentialsProvider();
    credentialsProvider.setCredentials(
            new AuthScope(AuthScope.ANY),
            new UsernamePasswordCredentials(pUser, pPassword));
    pBuilder.setDefaultCredentialsProvider(credentialsProvider);
    pBuilder.addInterceptorFirst(new PreemptiveAuthInterceptor(new BearerScheme()));
}
 
Example #28
Source File: ElasticsearchAutoConfiguration.java    From spring-boot-demo with MIT License 5 votes vote down vote up
/**
 * get restHistLevelClient
 *
 * @param builder                 RestClientBuilder
 * @param elasticsearchProperties elasticsearch default properties
 * @return {@link org.elasticsearch.client.RestHighLevelClient}
 * @author fxbin
 */
private static RestHighLevelClient getRestHighLevelClient(RestClientBuilder builder, ElasticsearchProperties elasticsearchProperties) {

    // Callback used the default {@link RequestConfig} being set to the {@link CloseableHttpClient}
    builder.setRequestConfigCallback(requestConfigBuilder -> {
        requestConfigBuilder.setConnectTimeout(elasticsearchProperties.getConnectTimeout());
        requestConfigBuilder.setSocketTimeout(elasticsearchProperties.getSocketTimeout());
        requestConfigBuilder.setConnectionRequestTimeout(elasticsearchProperties.getConnectionRequestTimeout());
        return requestConfigBuilder;
    });

    // Callback used to customize the {@link CloseableHttpClient} instance used by a {@link RestClient} instance.
    builder.setHttpClientConfigCallback(httpClientBuilder -> {
        httpClientBuilder.setMaxConnTotal(elasticsearchProperties.getMaxConnectTotal());
        httpClientBuilder.setMaxConnPerRoute(elasticsearchProperties.getMaxConnectPerRoute());
        return httpClientBuilder;
    });

    // Callback used the basic credential auth
    ElasticsearchProperties.Account account = elasticsearchProperties.getAccount();
    if (!StringUtils.isEmpty(account.getUsername()) && !StringUtils.isEmpty(account.getUsername())) {
        final CredentialsProvider credentialsProvider = new BasicCredentialsProvider();

        credentialsProvider.setCredentials(AuthScope.ANY, new UsernamePasswordCredentials(account.getUsername(), account.getPassword()));
    }
    return new RestHighLevelClient(builder);
}
 
Example #29
Source File: HttpMgmtProxy.java    From wildfly-core with GNU Lesser General Public License v2.1 5 votes vote down vote up
public HttpMgmtProxy(URL mgmtURL) {
    this.url = mgmtURL;
    CredentialsProvider credsProvider = new BasicCredentialsProvider();
            credsProvider.setCredentials(new AuthScope(url.getHost(), url.getPort()), new UsernamePasswordCredentials(Authentication.USERNAME, Authentication.PASSWORD));

    this.httpClient = HttpClients.custom()
            .setDefaultCredentialsProvider(credsProvider)
            .build();
}
 
Example #30
Source File: AuthHandler.java    From curly with Apache License 2.0 5 votes vote down vote up
private CredentialsProvider getCredentialsProvider() {
    CredentialsProvider creds = new BasicCredentialsProvider();
    creds.setCredentials(AuthScope.ANY, new UsernamePasswordCredentials(
            model.userNameProperty().get(),
            model.passwordProperty().get()
    ));
    return creds;
}