org.apache.http.auth.UsernamePasswordCredentials Java Examples

The following examples show how to use org.apache.http.auth.UsernamePasswordCredentials. 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: 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 #3
Source File: AxivionSuite.java    From warnings-ng-plugin with MIT License 6 votes vote down vote up
private UsernamePasswordCredentials withValidCredentials() {
    final List<StandardUsernamePasswordCredentials> all =
            CredentialsProvider.lookupCredentials(
                    StandardUsernamePasswordCredentials.class,
                    (Item) null,
                    ACL.SYSTEM,
                    Collections.emptyList());

    StandardUsernamePasswordCredentials jenkinsCredentials =
            CredentialsMatchers.firstOrNull(all,
                    CredentialsMatchers.withId(credentialsId));

    if (jenkinsCredentials == null) {
        throw new ParsingException("Could not find the credentials for " + credentialsId);
    }

    return new UsernamePasswordCredentials(
            jenkinsCredentials.getUsername(),
            Secret.toString(jenkinsCredentials.getPassword()));
}
 
Example #4
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 #5
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 #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: 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 #8
Source File: RestAutoConfigure.java    From microservices-platform with Apache License 2.0 6 votes vote down vote up
/**
 * 异步httpclient连接数配置
 */
private void setHttpClientConfig(RestClientBuilder builder, RestClientPoolProperties poolProperties, RestClientProperties restProperties){
    builder.setHttpClientConfigCallback(httpClientBuilder -> {
        httpClientBuilder.setMaxConnTotal(poolProperties.getMaxConnectNum())
                .setMaxConnPerRoute(poolProperties.getMaxConnectPerRoute());

        PropertyMapper map = PropertyMapper.get().alwaysApplyingWhenNonNull();
        map.from(restProperties::getUsername).to(username -> {
            CredentialsProvider credentialsProvider = new BasicCredentialsProvider();
            credentialsProvider.setCredentials(AuthScope.ANY,
                    new UsernamePasswordCredentials(username, restProperties.getPassword()));
            httpClientBuilder.setDefaultCredentialsProvider(credentialsProvider);
        });
        return httpClientBuilder;
    });
}
 
Example #9
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 #10
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 #11
Source File: ServerConnectionManager.java    From hop with Apache License 2.0 6 votes vote down vote up
public HttpClient createHttpClient( String user, String password,
                                    String proxyHost, int proxyPort, AuthScope authScope ) {
  HttpHost httpHost = new HttpHost( proxyHost, proxyPort );

  RequestConfig requestConfig = RequestConfig.custom()
    .setProxy( httpHost )
    .build();

  CredentialsProvider provider = new BasicCredentialsProvider();
  UsernamePasswordCredentials credentials = new UsernamePasswordCredentials( user, password );
  provider.setCredentials( authScope, credentials );

  return
    HttpClientBuilder
      .create()
      .setDefaultCredentialsProvider( provider )
      .setDefaultRequestConfig( requestConfig )
      .setConnectionManager( manager )
      .build();
}
 
Example #12
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 #13
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 #14
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 #15
Source File: KeycloakSmsAuthenticator.java    From keycloak-sms-authenticator with Eclipse Public License 2.0 6 votes vote down vote up
private CredentialsProvider getCredentialsProvider(String smsUsr, String smsPwd, String proxyUsr, String proxyPwd, URL smsURL, URL proxyURL) {
    CredentialsProvider credsProvider = new BasicCredentialsProvider();

    // If defined, add BASIC Authentication parameters
    if (isNotEmpty(smsUsr) && isNotEmpty(smsPwd)) {
        credsProvider.setCredentials(
                new AuthScope(smsURL.getHost(), smsURL.getPort()),
                new UsernamePasswordCredentials(smsUsr, smsPwd));

    }

    // If defined, add Proxy Authentication parameters
    if (isNotEmpty(proxyUsr) && isNotEmpty(proxyPwd)) {
        credsProvider.setCredentials(
                new AuthScope(proxyURL.getHost(), proxyURL.getPort()),
                new UsernamePasswordCredentials(proxyUsr, proxyPwd));

    }
    return credsProvider;
}
 
Example #16
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 #17
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 #18
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();

    // 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();
}
 
Example #19
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 #20
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 #21
Source File: NotificationUtil.java    From qy-wechat-notification-plugin with Apache License 2.0 6 votes vote down vote up
/**
 * 推送信息
 * @param url
 * @param data
 */
public static String push(String url, String data, NotificationConfig buildConfig) throws HttpProcessException {
    HttpConfig httpConfig;
    //使用代理请求
    if(buildConfig.useProxy){
        HttpClient httpClient;
        HttpHost proxy = new HttpHost(buildConfig.proxyHost, buildConfig.proxyPort);
        //用户密码
        if(StringUtils.isNotEmpty(buildConfig.proxyUsername) && buildConfig.proxyPassword != null){
            // 设置认证
            CredentialsProvider provider = new BasicCredentialsProvider();
            provider.setCredentials(new AuthScope(proxy), new UsernamePasswordCredentials(buildConfig.proxyUsername, Secret.toString(buildConfig.proxyPassword)));
            httpClient = HttpClients.custom().setDefaultCredentialsProvider(provider).setProxy(proxy).build();
        }else{
            httpClient = HttpClients.custom().setProxy(proxy).build();
        }
        //代理请求
        httpConfig = HttpConfig.custom().client(httpClient).url(url).json(data).encoding("utf-8");
    }else{
        //普通请求
        httpConfig = HttpConfig.custom().url(url).json(data).encoding("utf-8");
    }

    String result = HttpClientUtil.post(httpConfig);
    return result;
}
 
Example #22
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 #23
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 #24
Source File: ElasticsearchConfig.java    From staccato with Apache License 2.0 6 votes vote down vote up
/**
 * Registers an instance of the high level client for Elasticsearch.
 *
 * @return An instance of Elasticsearch's high level rest client
 */
@Bean
public RestHighLevelClient restHighLevelClient() {
    RestClientBuilder builder = RestClient.builder(new HttpHost(configProps.getHost(), configProps.getPort(), configProps.getScheme()));
    RestClientBuilder.HttpClientConfigCallback httpClientConfigCallback = httpAsyncClientBuilder -> {
        httpAsyncClientBuilder
                .setMaxConnTotal(configProps.getRestClientMaxConnectionsTotal())
                .setMaxConnPerRoute(configProps.getRestClientMaxConnectionsPerRoute());

        if (null != configProps.getUser() && !configProps.getUser().isEmpty()) {
            CredentialsProvider credentialsProvider = new BasicCredentialsProvider();
            credentialsProvider.setCredentials(AuthScope.ANY,
                    new UsernamePasswordCredentials(configProps.getUser(), configProps.getPassword()));
            httpAsyncClientBuilder.setDefaultCredentialsProvider(credentialsProvider);
        }

        return httpAsyncClientBuilder;
    };

    builder.setHttpClientConfigCallback(httpClientConfigCallback);
    builder.setMaxRetryTimeoutMillis(configProps.getRestClientMaxRetryTimeoutMillis());

    //return new RestHighLevelClient(builder.build());
    return new RestHighLevelClient(builder);
}
 
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: SPARQLEndpointExecution.java    From hypergraphql with Apache License 2.0 5 votes vote down vote up
@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;
}
 
Example #27
Source File: UrlAuthenticatorDialog.java    From netcdf-java with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
/**
 * constructor
 *
 * @param parent JFrame
 */
public UrlAuthenticatorDialog(javax.swing.JFrame parent) {
  PrefPanel pp = new PrefPanel("UrlAuthenticatorDialog", null);
  serverF = pp.addTextField("server", "Server", "wwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwww");
  realmF = pp.addTextField("realm", "Realm", "");
  serverF.setEditable(false);
  realmF.setEditable(false);

  userF = pp.addTextField("user", "User", "");
  passwF = pp.addPasswordField("password", "Password", "");
  pp.addActionListener(e -> {
    char[] pw = passwF.getPassword();
    if (pw == null)
      return;
    pwa = new UsernamePasswordCredentials(userF.getText(), new String(pw));
    dialog.setVisible(false);
  });
  // button to dismiss
  JButton cancel = new JButton("Cancel");
  pp.addButton(cancel);
  cancel.addActionListener(new ActionListener() {
    public void actionPerformed(ActionEvent evt) {
      pwa = null;
      dialog.setVisible(false);
    }
  });
  pp.finish();

  dialog = new IndependentDialog(parent, true, "HTTP Authentication", pp);
  dialog.setLocationRelativeTo(parent);
  dialog.setLocation(100, 100);
}
 
Example #28
Source File: HttpClient.java    From ats-framework with Apache License 2.0 5 votes vote down vote up
/**
 * Set up authentication for HTTP Basic/HTTP Digest/SPNEGO.
 *
 * @param httpClientBuilder The client builder
 * @return The context
 * @throws HttpException
 */
private void setupAuthentication( HttpClientBuilder httpClientBuilder ) throws HttpException {

    CredentialsProvider credsProvider = new BasicCredentialsProvider();
    credsProvider.setCredentials(new AuthScope(AuthScope.ANY_HOST, AuthScope.ANY_PORT),
                                 new UsernamePasswordCredentials(username, password));
    httpClientBuilder.setDefaultCredentialsProvider(credsProvider);

    if (authType == AuthType.always) {
        AuthCache authCache = new BasicAuthCache();
        // Generate BASIC scheme object and add it to the local auth cache
        BasicScheme basicAuth = new BasicScheme();

        HttpHost target = new HttpHost(host, port, isOverSsl
                                                             ? "https"
                                                             : "http");
        authCache.put(target, basicAuth);

        // Add AuthCache to the execution context
        httpContext.setAuthCache(authCache);
    } else {
        if (!StringUtils.isNullOrEmpty(kerberosServicePrincipalName)) {
            GssClient gssClient = new GssClient(username, password, kerberosClientKeytab, krb5ConfFile);
            AuthSchemeProvider nsf = new SPNegoSchemeFactory(gssClient, kerberosServicePrincipalName,
                                                             kerberosServicePrincipalType);
            final Registry<AuthSchemeProvider> authSchemeRegistry = RegistryBuilder.<AuthSchemeProvider> create()
                                                                                   .register(AuthSchemes.SPNEGO,
                                                                                             nsf)
                                                                                   .build();
            httpClientBuilder.setDefaultAuthSchemeRegistry(authSchemeRegistry);
        }
    }
}
 
Example #29
Source File: RResourceITSupport.java    From nexus-repository-r with Eclipse Public License 1.0 5 votes vote down vote up
protected void setUnauthorizedUser() {
  String randomRoleName = "role_" + UUID.randomUUID().toString();

  Role role = securityRule.createRole(randomRoleName, UNRELATED_PRIVILEGE);
  securityRule.createUser(randomRoleName, randomRoleName, role.getRoleId());
  credentials = new UsernamePasswordCredentials(randomRoleName, randomRoleName);
}
 
Example #30
Source File: TestHttpClient4.java    From davmail with GNU General Public License v2.0 5 votes vote down vote up
public void testBasicAuthentication() throws IOException {
    Settings.setLoggingLevel("org.apache.http", Level.DEBUG);

    RegistryBuilder<ConnectionSocketFactory> schemeRegistry = RegistryBuilder.create();
    schemeRegistry.register("https", new SSLConnectionSocketFactory(new DavGatewaySSLSocketFactory(),
            SSLConnectionSocketFactory.getDefaultHostnameVerifier()));

    CredentialsProvider provider = new BasicCredentialsProvider();
    UsernamePasswordCredentials credentials
            = new UsernamePasswordCredentials(username, password);
    provider.setCredentials(AuthScope.ANY, credentials);

    PoolingHttpClientConnectionManager poolingHttpClientConnectionManager = new PoolingHttpClientConnectionManager(schemeRegistry.build());
    HttpClientBuilder clientBuilder = HttpClientBuilder.create()
            .disableRedirectHandling()
            .setDefaultCredentialsProvider(provider)
            .setConnectionManager(poolingHttpClientConnectionManager);
    try (CloseableHttpClient httpClient = clientBuilder.build()) {

        HttpGet httpget = new HttpGet("https://outlook.office365.com/EWS/Exchange.asmx");
        try (CloseableHttpResponse response = httpClient.execute(httpget)) {
            assertEquals(HttpStatus.SC_OK, response.getStatusLine().getStatusCode());
            String responseString = new BasicResponseHandler().handleResponse(response);
            System.out.println(responseString);
        }
    }
}