org.apache.http.impl.client.BasicCredentialsProvider Java Examples

The following examples show how to use org.apache.http.impl.client.BasicCredentialsProvider. 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: ElasticsearchRestClientInstrumentationIT.java    From apm-agent-java with Apache License 2.0 8 votes vote down vote up
@BeforeClass
public static void startElasticsearchContainerAndClient() throws IOException {
    container = new ElasticsearchContainer(ELASTICSEARCH_CONTAINER_VERSION);
    container.start();

    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();
}
 
Example #2
Source File: HttpConnectionManager.java    From timer with Apache License 2.0 6 votes vote down vote up
/**
 * 默认是 Bsic认证机制
 *
 * @param ip
 * @param username
 * @param password
 * @return
 */
public static HttpClient getHtpClient(String ip, int port, String username, String password) {
    HttpHost proxy = new HttpHost(ip, port);
    Lookup<AuthSchemeProvider> authProviders =
            RegistryBuilder.<AuthSchemeProvider>create()
                    .register(AuthSchemes.BASIC, new BasicSchemeFactory())
                    .build();
    BasicCredentialsProvider credsProvider = new BasicCredentialsProvider();
    if (username != null && password != null) {
        credsProvider.setCredentials(AuthScope.ANY, new UsernamePasswordCredentials(username, password));
    } else {
        credsProvider.setCredentials(AuthScope.ANY, null);
    }

    RequestConfig requestConfig = RequestConfig.custom().setCookieSpec(CookieSpecs.STANDARD_STRICT).build();
    CloseableHttpClient httpClient = HttpClients
            .custom()
            .setConnectionManager(cm)
            .setProxy(proxy)
            .setRedirectStrategy(new LaxRedirectStrategy())
            .setDefaultRequestConfig(requestConfig)
            .setDefaultAuthSchemeRegistry(authProviders)
            .setDefaultCredentialsProvider(credsProvider)
            .build();
    return httpClient;
}
 
Example #3
Source File: HelmPublish.java    From gradle-plugins with Apache License 2.0 6 votes vote down vote up
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;
}
 
Example #4
Source File: HopServer.java    From hop with Apache License 2.0 6 votes vote down vote up
private void addCredentials( HttpClientContext context ) {

    String host = environmentSubstitute( hostname );
    int port = Const.toInt( environmentSubstitute( this.port ), 80 );
    String userName = environmentSubstitute( username );
    String password = Encr.decryptPasswordOptionallyEncrypted( environmentSubstitute( this.password ) );
    String proxyHost = environmentSubstitute( proxyHostname );

    CredentialsProvider provider = new BasicCredentialsProvider();
    UsernamePasswordCredentials credentials = new UsernamePasswordCredentials( userName, password );
    if ( !Utils.isEmpty( proxyHost ) && host.equals( "localhost" ) ) {
      host = "127.0.0.1";
    }
    provider.setCredentials( new AuthScope( host, port ), credentials );
    context.setCredentialsProvider( provider );
    // Generate BASIC scheme object and add it to the local auth cache
    HttpHost target = new HttpHost( host, port, isSslMode() ? HTTPS : HTTP );
    AuthCache authCache = new BasicAuthCache();
    BasicScheme basicAuth = new BasicScheme();
    authCache.put( target, basicAuth );
    context.setAuthCache( authCache );
  }
 
Example #5
Source File: AvaticaCommonsHttpClientImpl.java    From calcite-avatica with Apache License 2.0 6 votes vote down vote up
@Override public void setUsernamePassword(AuthenticationType authType, String username,
    String password) {
  this.credentials = new UsernamePasswordCredentials(
      Objects.requireNonNull(username), Objects.requireNonNull(password));

  this.credentialsProvider = new BasicCredentialsProvider();
  credentialsProvider.setCredentials(AuthScope.ANY, credentials);

  RegistryBuilder<AuthSchemeProvider> authRegistryBuilder = RegistryBuilder.create();
  switch (authType) {
  case BASIC:
    authRegistryBuilder.register(AuthSchemes.BASIC, new BasicSchemeFactory());
    break;
  case DIGEST:
    authRegistryBuilder.register(AuthSchemes.DIGEST, new DigestSchemeFactory());
    break;
  default:
    throw new IllegalArgumentException("Unsupported authentiation type: " + authType);
  }
  this.authRegistry = authRegistryBuilder.build();
}
 
Example #6
Source File: ElasticsearchCustomSchemaFactory.java    From Quicksql with MIT License 6 votes vote down vote up
/**
 * Builds elastic rest client from user configuration
 *
 * @param coordinates list of {@code hostname/port} to connect to
 * @return newly initialized low-level rest http client for ES
 */
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 #7
Source File: HttpEndpoint.java    From Brutusin-RPC with Apache License 2.0 6 votes vote down vote up
public static void main(String[] args) throws Exception {

        HttpClientContextFactory ctxFact = new HttpClientContextFactory() {
            public HttpClientContext create() {
                CredentialsProvider credsProvider = new BasicCredentialsProvider();
                credsProvider.setCredentials(
                        new AuthScope("localhost", 8080, AuthScope.ANY_REALM, "basic"),
                        new UsernamePasswordCredentials("user", "password"));
                HttpClientContext context = HttpClientContext.create();
                context.setCredentialsProvider(credsProvider);
                return context;
            }
        };

        HttpEndpoint endpoint = new HttpEndpoint(new URI("http://localhost:8080/rpc/http"), ctxFact);

        HttpResponse resp = endpoint.exec("rpc.http.version", null, null);
        if (resp.isIsBinary()) {
            System.out.println("binary");
            System.out.println(resp.getInputStream().getName());
        } else {
            System.out.println(resp.getRpcResponse().getResult());
        }
    }
 
Example #8
Source File: LegacyMmsConnection.java    From Silence with GNU General Public License v3.0 6 votes vote down vote up
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(SilencePreferences.getMmsUserAgent(context, USER_AGENT))
                    .setConnectionManager(new BasicHttpClientConnectionManager())
                    .setDefaultRequestConfig(config)
                    .setDefaultCredentialsProvider(credsProvider)
                    .build();
}
 
Example #9
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 #10
Source File: EsRestClientContainer.java    From frostmourne with MIT License 6 votes vote down vote up
public void init() {
    RestClientBuilder restClientBuilder = RestClient.builder(parseHttpHost(esHosts)
            .toArray(new HttpHost[0]));

    if (this.settings != null && this.settings.size() > 0 &&
            !Strings.isNullOrEmpty(this.settings.get("username"))
            && !Strings.isNullOrEmpty(this.settings.get("password"))) {
        String userName = this.settings.get("username");
        String password = this.settings.get("password");
        final CredentialsProvider credentialsProvider =
                new BasicCredentialsProvider();
        credentialsProvider.setCredentials(AuthScope.ANY,
                new UsernamePasswordCredentials(userName, password));
        restClientBuilder.setHttpClientConfigCallback(httpAsyncClientBuilder -> {
            httpAsyncClientBuilder.disableAuthCaching();
            return httpAsyncClientBuilder.setDefaultCredentialsProvider(credentialsProvider);
        });
    }
    restHighLevelClient = new RestHighLevelClient(restClientBuilder);
    this.restLowLevelClient = restHighLevelClient.getLowLevelClient();
    if (sniff) {
        sniffer = Sniffer.builder(restLowLevelClient).setSniffIntervalMillis(5 * 60 * 1000).build();
    }
}
 
Example #11
Source File: EsMediaSourceController.java    From DataLink with Apache License 2.0 6 votes vote down vote up
private void verify(String url, String user, String pass) {
    try {
        CredentialsProvider provider = new BasicCredentialsProvider();
        UsernamePasswordCredentials credentials = new UsernamePasswordCredentials(user, pass);
        provider.setCredentials(AuthScope.ANY, credentials);
        HttpClient client = HttpClientBuilder.create().setDefaultCredentialsProvider(provider).build();
        HttpResponse response = client.execute(new HttpGet(url));
        if (response.getStatusLine().getStatusCode() != HttpStatus.SC_OK) {
            throw new ValidationException("verify elasticsearch node [" + url + "] failure, response status: " + response);
        }

        logger.info("Verify Es MediaSource successfully.");
    } catch (Exception e) {
        throw new ValidationException("verify elasticsearch node [" + url + "] failure, cause of: " + e);
    }
}
 
Example #12
Source File: FormatClientSupport.java    From nexus-public with Eclipse Public License 1.0 6 votes vote down vote up
protected CloseableHttpResponse execute(final HttpUriRequest request, String username, String password)
    throws IOException
{
  log.debug("Authorizing request for {} using credentials provided for username: {}",
      request.getURI(), username);
  CredentialsProvider credsProvider = new BasicCredentialsProvider();
  credsProvider.setCredentials(AuthScope.ANY, new UsernamePasswordCredentials(username, password));

  HttpHost host = URIUtils.extractHost(request.getURI());

  AuthCache authCache = new BasicAuthCache();
  authCache.put(host, new BasicScheme());

  HttpClientContext clientContext = new HttpClientContext(httpClientContext);
  clientContext.setAuthCache(authCache);
  clientContext.setCredentialsProvider(credsProvider);

  return execute(request, clientContext);
}
 
Example #13
Source File: AbstractBeyonderTest.java    From elasticsearch-beyonder with Apache License 2.0 6 votes vote down vote up
private static void startRestClient() throws IOException {
    if (client == null) {
        RestClientBuilder builder = RestClient.builder(HttpHost.create(testCluster));
        if (testClusterUser != null) {
            final CredentialsProvider credentialsProvider =
                    new BasicCredentialsProvider();
            credentialsProvider.setCredentials(AuthScope.ANY,
                    new UsernamePasswordCredentials(testClusterUser, testClusterPass));
            builder.setHttpClientConfigCallback(httpClientBuilder -> httpClientBuilder
                    .setDefaultCredentialsProvider(credentialsProvider));
        }

        client = builder.build();
        testClusterRunning();
    }
}
 
Example #14
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 #15
Source File: RestClient.java    From kylin with Apache License 2.0 6 votes vote down vote up
private void init(String host, int port, String userName, String password) {
    this.host = host;
    this.port = port;
    this.userName = userName;
    this.password = password;
    this.baseUrl = SCHEME_HTTP + host + ":" + port + KYLIN_API_PATH;

    final HttpParams httpParams = new BasicHttpParams();
    HttpConnectionParams.setSoTimeout(httpParams, httpSocketTimeoutMs);
    HttpConnectionParams.setConnectionTimeout(httpParams, httpConnectionTimeoutMs);

    final PoolingClientConnectionManager cm = new PoolingClientConnectionManager();
    KylinConfig config = KylinConfig.getInstanceFromEnv();
    cm.setDefaultMaxPerRoute(config.getRestClientDefaultMaxPerRoute());
    cm.setMaxTotal(config.getRestClientMaxTotal());

    client = new DefaultHttpClient(cm, httpParams);

    if (userName != null && password != null) {
        CredentialsProvider provider = new BasicCredentialsProvider();
        UsernamePasswordCredentials credentials = new UsernamePasswordCredentials(userName, password);
        provider.setCredentials(AuthScope.ANY, credentials);
        client.setCredentialsProvider(provider);
    }
}
 
Example #16
Source File: MavenITSupport.java    From nexus-public with Eclipse Public License 1.0 6 votes vote down vote up
protected Maven2Client createMaven2Client(final URL repositoryUrl, final String username, final String password)
    throws Exception
{
  AuthScope scope = new AuthScope(repositoryUrl.getHost(), -1);
  CredentialsProvider credentialsProvider = new BasicCredentialsProvider();
  credentialsProvider.setCredentials(scope, new UsernamePasswordCredentials(username, password));
  RequestConfig.Builder requestConfigBuilder = RequestConfig.custom();
  requestConfigBuilder.setExpectContinueEnabled(true);
  HttpClientContext httpClientContext = HttpClientContext.create();
  httpClientContext.setRequestConfig(requestConfigBuilder.build());
  return new Maven2Client(
      HttpClients.custom().setDefaultCredentialsProvider(credentialsProvider).build(),
      httpClientContext,
      repositoryUrl.toURI()
  );
}
 
Example #17
Source File: CMODataAbapClient.java    From devops-cm-client with Apache License 2.0 6 votes vote down vote up
public CMODataAbapClient(String endpoint, String user, String password) throws URISyntaxException {

        this.endpoint = new URI(endpoint);
        this.requestBuilder = new TransportRequestBuilder(this.endpoint);

        // the same instance needs to be used as long as we are in the same session. Hence multiple
        // clients must share the same cookie store. Reason: we are logged on with the first request
        // and get a cookie. That cookie - expressing the user has already been logged in - needs to be
        // present in all subsequent requests.
        CookieStore sessionCookieStore = new BasicCookieStore();

        BasicCredentialsProvider basicCredentialsProvider = new BasicCredentialsProvider();
        basicCredentialsProvider.setCredentials(
                new AuthScope(this.endpoint.getHost(), this.endpoint.getPort()),
                new UsernamePasswordCredentials(user, password));

        this.clientFactory = new HttpClientFactory(sessionCookieStore, basicCredentialsProvider);
    }
 
Example #18
Source File: HttpPublisher.java    From logsniffer with GNU Lesser General Public License v3.0 6 votes vote down vote up
/**
 * Init method for this publisher.
 * 
 * @param velocityRenderer
 *            the velocityRenderer to set
 * @param httpClient
 *            http client
 */
protected void init(final VelocityEventRenderer velocityRenderer,
		final HttpClient httpClient) {
	this.velocityRenderer = velocityRenderer;
	this.httpClient = httpClient;
	if (getHttpAuthentication() != null) {
		CredentialsProvider credsProvider = new BasicCredentialsProvider();
		credsProvider.setCredentials(new AuthScope(AuthScope.ANY_HOST,
				AuthScope.ANY_PORT), new UsernamePasswordCredentials(
				getHttpAuthentication().getUsername(),
				getHttpAuthentication().getPassword()));
		// Add AuthCache to the execution context
		HttpClientContext context = HttpClientContext.create();
		context.setCredentialsProvider(credsProvider);
	}
}
 
Example #19
Source File: NexusArtifactClient.java    From cubeai with Apache License 2.0 6 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 #20
Source File: FormatClientSupport.java    From nexus-public with Eclipse Public License 1.0 6 votes vote down vote up
protected CloseableHttpResponse execute(final HttpUriRequest request, String username, String password)
    throws IOException
{
  log.debug("Authorizing request for {} using credentials provided for username: {}",
      request.getURI(), username);
  CredentialsProvider credsProvider = new BasicCredentialsProvider();
  credsProvider.setCredentials(AuthScope.ANY, new UsernamePasswordCredentials(username, password));

  HttpHost host = URIUtils.extractHost(request.getURI());

  AuthCache authCache = new BasicAuthCache();
  authCache.put(host, new BasicScheme());

  HttpClientContext clientContext = new HttpClientContext(httpClientContext);
  clientContext.setAuthCache(authCache);
  clientContext.setCredentialsProvider(credsProvider);

  return execute(request, clientContext);
}
 
Example #21
Source File: BrooklynWebServerTest.java    From brooklyn-server with Apache License 2.0 6 votes vote down vote up
@Test
public void verifySecurityInitializedExplicitUser() throws Exception {
    webServer = new BrooklynWebServer(newManagementContext(brooklynProperties));
    webServer.start();

    CredentialsProvider credentialsProvider = new BasicCredentialsProvider();
    credentialsProvider.setCredentials(AuthScope.ANY, new UsernamePasswordCredentials("myuser", "somepass"));
    HttpClient client = HttpTool.httpClientBuilder()
        .credentials(new UsernamePasswordCredentials("myuser", "somepass"))
        .uri(webServer.getRootUrl())
        .build();

    try {
        HttpToolResponse response = HttpTool.execAndConsume(client, new HttpGet(webServer.getRootUrl()));
        assertEquals(response.getResponseCode(), 401);
    } finally {
        webServer.stop();
    }
}
 
Example #22
Source File: WxPayServiceApacheHttpImpl.java    From weixin-java-tools with Apache License 2.0 6 votes vote down vote up
private HttpClientBuilder createHttpClientBuilder(boolean useKey) throws WxPayException {
  HttpClientBuilder httpClientBuilder = HttpClients.custom();
  if (useKey) {
    this.initSSLContext(httpClientBuilder);
  }

  if (StringUtils.isNotBlank(this.getConfig().getHttpProxyHost())
    && this.getConfig().getHttpProxyPort() > 0) {
    // 使用代理服务器 需要用户认证的代理服务器
    CredentialsProvider provider = new BasicCredentialsProvider();
    provider.setCredentials(
      new AuthScope(this.getConfig().getHttpProxyHost(), this.getConfig().getHttpProxyPort()),
      new UsernamePasswordCredentials(this.getConfig().getHttpProxyUsername(), this.getConfig().getHttpProxyPassword()));
    httpClientBuilder.setDefaultCredentialsProvider(provider);
  }
  return httpClientBuilder;
}
 
Example #23
Source File: ConnectorCommon.java    From nextcloud-java-api with GNU General Public License v3.0 6 votes vote down vote up
private HttpClientContext prepareContext()
{
    HttpHost targetHost = new HttpHost(serverConfig.getServerName(), serverConfig.getPort(), serverConfig.isUseHTTPS() ? "https" : "http");
    AuthCache authCache = new BasicAuthCache();
    authCache.put(targetHost, new BasicScheme());

    CredentialsProvider credsProvider = new BasicCredentialsProvider();
    UsernamePasswordCredentials credentials
     = new UsernamePasswordCredentials(serverConfig.getUserName(), serverConfig.getPassword());
    credsProvider.setCredentials(AuthScope.ANY, credentials);

    // Add AuthCache to the execution context
    HttpClientContext context = HttpClientContext.create();
    context.setCredentialsProvider(credsProvider);
    context.setAuthCache(authCache);
    return context;
}
 
Example #24
Source File: RestUtils.java    From slack-api with MIT License 6 votes vote down vote up
public static CloseableHttpClient createHttpClient(int timeout, ProxyServerInfo proxyServerInfo) {
	RequestConfig requestConfig = RequestConfig.custom().setSocketTimeout(timeout).setConnectTimeout(timeout).build();
	PoolingHttpClientConnectionManager connectionManager = new PoolingHttpClientConnectionManager();
	HttpClientBuilder httpClientBuilder = HttpClientBuilder.create().setConnectionManager(connectionManager).setDefaultRequestConfig(requestConfig);
	if (proxyServerInfo != null) {
	    HttpHost proxy = new HttpHost(proxyServerInfo.getHost(), proxyServerInfo.getPort(), proxyServerInfo.getProtocol());
		httpClientBuilder = httpClientBuilder.setProxy(proxy);
		if (proxyServerInfo.getPrincipal() != null && proxyServerInfo.getPassword() != null) {
			Credentials credentials = new UsernamePasswordCredentials(proxyServerInfo.getPrincipal(), proxyServerInfo.getPassword());
			AuthScope authScope = new AuthScope(proxyServerInfo.getHost(), proxyServerInfo.getPort());
			CredentialsProvider credentialsProvider = new BasicCredentialsProvider();
			credentialsProvider.setCredentials(authScope, credentials);
			httpClientBuilder = httpClientBuilder.setDefaultCredentialsProvider(credentialsProvider);
		}
	}
	return httpClientBuilder.build();
}
 
Example #25
Source File: Mp3Converter.java    From alexa-meets-polly with Apache License 2.0 6 votes vote down vote up
public static String convertMp3(final String mp3Path) throws URISyntaxException, IOException {
    // get credentials for webservice from application config
    final String apiKey = SkillConfig.getTranslatorConvertServiceUser();
    final String apiPass = SkillConfig.getTranslatorConvertServicePass();
    // build uri
    final String bucketName = SkillConfig.getS3BucketName();
    final URIBuilder uri = new URIBuilder(SkillConfig.getTranslatorConvertServiceUrl()).addParameter("bucket", bucketName).addParameter("path", mp3Path);
    // set up web request
    final HttpGet httpGet = new HttpGet(uri.build());
    httpGet.setHeader("Content-Type", "text/plain");
    // set up credentials
    final CredentialsProvider provider = new BasicCredentialsProvider();
    final UsernamePasswordCredentials credentials = new UsernamePasswordCredentials(apiKey, apiPass);
    provider.setCredentials(AuthScope.ANY, credentials);
    // send request to convert webservice
    final HttpResponse response =
            HttpClientBuilder.create().setDefaultCredentialsProvider(provider).build().execute(httpGet);

    //Validate.inclusiveBetween(200, 399, response.getStatusLine().getStatusCode(), response.getStatusLine().getReasonPhrase());
    // work on response
    final HttpEntity entity = response.getEntity();
    return IOUtils.toString(entity.getContent(), "UTF-8");
}
 
Example #26
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 #27
Source File: ElasticConnection.java    From kafka-connect-elasticsearch-source with Apache License 2.0 6 votes vote down vote up
public ElasticConnection(String host, int port, String user, String pwd,
                         int maxConnectionAttempts, long connectionRetryBackoff) {

    logger.info("elastic auth enabled");

    final CredentialsProvider credentialsProvider = new BasicCredentialsProvider();
    credentialsProvider.setCredentials(AuthScope.ANY,
            new UsernamePasswordCredentials(user, pwd));

    //TODO add configuration for https also, and many nodes instead of only one
    client = new RestHighLevelClient(
            RestClient.builder(
                    new HttpHost(host, port)).setHttpClientConfigCallback(
                    httpClientBuilder -> httpClientBuilder.setDefaultCredentialsProvider(credentialsProvider)
            )
    );

    this.maxConnectionAttempts = maxConnectionAttempts;
    this.connectionRetryBackoff = connectionRetryBackoff;

}
 
Example #28
Source File: TestUrlCreds.java    From netcdf-java with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
@Test
public void testUrlCred() throws HTTPException {
  String url = "https://" + username + ":" + password + "@" + host + "/something/garbage.grb?query";
  logger.info("Testing {}", url);
  try (HTTPMethod method = HTTPFactory.Get(url)) {
    HTTPSession session = method.getSession();
    method.close();
    session.setCredentialsProvider(new BasicCredentialsProvider());
    try (HTTPMethod method2 = HTTPFactory.Get(session, url)) {
      HTTPSession session2 = method2.getSession();
      CredentialsProvider credentialsProvider = session2.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);
    }
  }
}
 
Example #29
Source File: InfluxDBPublisher.java    From beam with Apache License 2.0 5 votes vote down vote up
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;
}
 
Example #30
Source File: ElasticsearchContainerTest.java    From testcontainers-java with MIT License 5 votes vote down vote up
private RestClient getClient(ElasticsearchContainer container) {
    if (client == null) {
        final CredentialsProvider credentialsProvider = new BasicCredentialsProvider();
        credentialsProvider.setCredentials(AuthScope.ANY,
            new UsernamePasswordCredentials(ELASTICSEARCH_USERNAME, ELASTICSEARCH_PASSWORD));

        client = RestClient.builder(HttpHost.create(container.getHttpHostAddress()))
            .setHttpClientConfigCallback(httpClientBuilder -> httpClientBuilder.setDefaultCredentialsProvider(credentialsProvider))
            .build();
    }

    return client;
}