org.apache.http.auth.AuthScope Java Examples

The following examples show how to use org.apache.http.auth.AuthScope. 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: HttpTransportFactory.java    From hadoop-connectors with Apache License 2.0 6 votes vote down vote up
/**
 * Create an {@link ApacheHttpTransport} for calling Google APIs with an optional HTTP proxy.
 *
 * @param proxyUri Optional HTTP proxy URI to use with the transport.
 * @param proxyCredentials Optional HTTP proxy credentials to authenticate with the transport
 *     proxy.
 * @return The resulting HttpTransport.
 * @throws IOException If there is an issue connecting to Google's certification server.
 * @throws GeneralSecurityException If there is a security issue with the keystore.
 */
public static ApacheHttpTransport createApacheHttpTransport(
    @Nullable URI proxyUri, @Nullable Credentials proxyCredentials)
    throws IOException, GeneralSecurityException {
  checkArgument(
      proxyUri != null || proxyCredentials == null,
      "if proxyUri is null than proxyCredentials should be null too");

  ApacheHttpTransport transport =
      new ApacheHttpTransport.Builder()
          .trustCertificates(GoogleUtils.getCertificateTrustStore())
          .setProxy(
              proxyUri == null ? null : new HttpHost(proxyUri.getHost(), proxyUri.getPort()))
          .build();

  if (proxyCredentials != null) {
    ((DefaultHttpClient) transport.getHttpClient())
        .getCredentialsProvider()
        .setCredentials(new AuthScope(proxyUri.getHost(), proxyUri.getPort()), proxyCredentials);
  }

  return transport;
}
 
Example #2
Source File: IdpTest.java    From cxf-fediz with Apache License 2.0 6 votes vote down vote up
@org.junit.Test
public void testSwagger() throws Exception {
    String url = "https://localhost:" + getIdpHttpsPort() + "/fediz-idp/services/rs/swagger.json";

    String user = "alice";
    String password = "ecila";

    final WebClient webClient = new WebClient();
    webClient.getOptions().setUseInsecureSSL(true);
    webClient.getCredentialsProvider().setCredentials(
        new AuthScope("localhost", Integer.parseInt(getIdpHttpsPort())),
        new UsernamePasswordCredentials(user, password));

    final UnexpectedPage swaggerPage = webClient.getPage(url);
    WebResponse response = swaggerPage.getWebResponse();
    Assert.assertEquals("application/json", response.getContentType());
    String json = response.getContentAsString();
    Assert.assertTrue(json.contains("Claims"));

    webClient.close();
}
 
Example #3
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 #4
Source File: HttpGenericOperationUnitTestCase.java    From wildfly-core with GNU Lesser General Public License v2.1 6 votes vote down vote up
private static CloseableHttpClient createHttpClient(String host, int port, String username, String password) {
    try {
        SSLContext sslContext = SSLContexts.createDefault();
        SSLConnectionSocketFactory sslConnectionSocketFactory = new SSLConnectionSocketFactory(sslContext, NoopHostnameVerifier.INSTANCE);
        Registry<ConnectionSocketFactory> registry = RegistryBuilder.<ConnectionSocketFactory>create()
                .register("https", sslConnectionSocketFactory)
                .register("http", PlainConnectionSocketFactory.getSocketFactory())
                .build();
        CredentialsProvider credsProvider = new BasicCredentialsProvider();
        credsProvider.setCredentials(new AuthScope(host, port, MANAGEMENT_REALM, AuthSchemes.DIGEST),
                new UsernamePasswordCredentials(username, password));
        PoolingHttpClientConnectionManager connectionPool = new PoolingHttpClientConnectionManager(registry);
        HttpClientBuilder.create().setConnectionManager(connectionPool).build();
        return HttpClientBuilder.create()
                .setConnectionManager(connectionPool)
                .setRetryHandler(new StandardHttpRequestRetryHandler(5, true))
                .setDefaultCredentialsProvider(credsProvider).build();
    } catch (Exception e) {
        throw new RuntimeException(e);
    }
}
 
Example #5
Source File: TestUrlCreds.java    From netcdf-java with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
@Test
public void testUrlCredDefaultProvider() throws HTTPException {
  String url = "https://" + username + ":" + password + "@" + host + "/something/garbage.grb?query";
  logger.info("Testing {}", url);
  try (HTTPMethod method = HTTPFactory.Get(url)) {
    // we should have a default BasicCredentialProvider available, even though
    // we didn't call the factory with a specific provider
    HTTPSession session = method.getSession();
    CredentialsProvider credentialsProvider = session.sessionprovider;
    assertThat(credentialsProvider).isNotNull();
    AuthScope expectedAuthScope = new AuthScope(host, 80);
    Credentials credentials = credentialsProvider.getCredentials(expectedAuthScope);
    assertThat(credentials).isNotNull();
    assertThat(credentials.getUserPrincipal().getName()).isEqualTo(username);
    assertThat(credentials.getPassword()).isEqualTo(password);
  }
}
 
Example #6
Source File: HttpDispatcher.java    From sana.mobile with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
public static HttpDispatcher getInstance(String uri, Credentials credentials) {

        HttpDispatcher dispatcher = new HttpDispatcher(new HttpHost(uri),
                new BasicHttpContext());

        CredentialsProvider credsProvider = new BasicCredentialsProvider();

        AuthScope authScope = new AuthScope(
                dispatcher.host.getHostName(),
                dispatcher.host.getPort());

        credsProvider.setCredentials(authScope, credentials);

        ((DefaultHttpClient) dispatcher.client).getCredentialsProvider().setCredentials(
                authScope, credentials);
        return dispatcher;
    }
 
Example #7
Source File: DefaultSpringCloudConfigClientGateway.java    From quarkus with Apache License 2.0 6 votes vote down vote up
private HttpClientContext setupContext() {
    final HttpClientContext context = HttpClientContext.create();
    if (baseUri.contains("@") || springCloudConfigClientConfig.usernameAndPasswordSet()) {
        final AuthCache authCache = InMemoryAuthCache.INSTANCE;
        authCache.put(HttpHost.create(baseUri), new BasicScheme());
        context.setAuthCache(authCache);
        if (springCloudConfigClientConfig.usernameAndPasswordSet()) {
            final CredentialsProvider provider = new BasicCredentialsProvider();
            final UsernamePasswordCredentials credentials = new UsernamePasswordCredentials(
                    springCloudConfigClientConfig.username.get(), springCloudConfigClientConfig.password.get());
            provider.setCredentials(AuthScope.ANY, credentials);
            context.setCredentialsProvider(provider);
        }
    }
    return context;
}
 
Example #8
Source File: HttpClientUtil.java    From pentaho-kettle with Apache License 2.0 6 votes vote down vote up
/**
 * Returns context with AuthCache or null in case of any exception was thrown.
 *
 * @param host
 * @param port
 * @param user
 * @param password
 * @param schema
 * @return {@link org.apache.http.client.protocol.HttpClientContext HttpClientContext}
 */
public static HttpClientContext createPreemptiveBasicAuthentication( String host, int port, String user,
                                                                     String password, String schema ) {
  HttpClientContext localContext = null;
  try {
    HttpHost target = new HttpHost( host, port, schema );
    CredentialsProvider credsProvider = new BasicCredentialsProvider();
    credsProvider.setCredentials(
      new AuthScope( target.getHostName(), target.getPort() ),
      new UsernamePasswordCredentials( user, password ) );

    // Create AuthCache instance
    AuthCache authCache = new BasicAuthCache();
    // Generate BASIC scheme object and add it to the local
    // auth cache
    BasicScheme basicAuth = new BasicScheme();
    authCache.put( target, basicAuth );

    // Add AuthCache to the execution context
    localContext = HttpClientContext.create();
    localContext.setAuthCache( authCache );
  } catch ( Exception e ) {
    return null;
  }
  return localContext;
}
 
Example #9
Source File: ElasticSearchFilter.java    From timbuctoo with GNU General Public License v3.0 6 votes vote down vote up
@JsonCreator
public ElasticSearchFilter(@JsonProperty("hostname") String hostname, @JsonProperty("port") int port,
                           @JsonProperty("username") Optional<String> username,
                           @JsonProperty("password") Optional<String> password) {
  Header[] headers = {
    new BasicHeader(HttpHeaders.CONTENT_TYPE, "application/json"),
    new BasicHeader("Role", "Read")};
  final RestClientBuilder restClientBuilder = RestClient.builder(new HttpHost(hostname, port))
    .setDefaultHeaders(headers);
  if (username.isPresent() && !username.get().isEmpty() && password.isPresent() && !password.get().isEmpty()) {
    final CredentialsProvider credentialsProvider = new BasicCredentialsProvider();

    credentialsProvider.setCredentials(
      AuthScope.ANY,
      new UsernamePasswordCredentials(username.get(), password.get())
    );

    restClientBuilder.setHttpClientConfigCallback(b -> b.setDefaultCredentialsProvider(credentialsProvider));
  }
  restClient = restClientBuilder.build();
  mapper = new ObjectMapper();
}
 
Example #10
Source File: ApiGatewayTest.java    From Inside_Android_Testing with Apache License 2.0 6 votes vote down vote up
@Test
public void shouldMakeRemoteGetCalls() {
    Robolectric.getBackgroundScheduler().pause();

    TestGetRequest apiRequest = new TestGetRequest();
    apiGateway.makeRequest(apiRequest, responseCallbacks);

    Robolectric.addPendingHttpResponse(200, GENERIC_XML);

    Robolectric.getBackgroundScheduler().runOneTask();

    HttpRequestInfo sentHttpRequestData = Robolectric.getSentHttpRequestInfo(0);
    HttpRequest sentHttpRequest = sentHttpRequestData.getHttpRequest();
    assertThat(sentHttpRequest.getRequestLine().getUri(), equalTo("www.example.com"));
    assertThat(sentHttpRequest.getRequestLine().getMethod(), equalTo(HttpGet.METHOD_NAME));

    assertThat(sentHttpRequest.getHeaders("foo")[0].getValue(), equalTo("bar"));

    CredentialsProvider credentialsProvider =
            (CredentialsProvider) sentHttpRequestData.getHttpContext().getAttribute(ClientContext.CREDS_PROVIDER);
    assertThat(credentialsProvider.getCredentials(AuthScope.ANY).getUserPrincipal().getName(), CoreMatchers.equalTo("spongebob"));
    assertThat(credentialsProvider.getCredentials(AuthScope.ANY).getPassword(), CoreMatchers.equalTo("squarepants"));
}
 
Example #11
Source File: ClientApiFunctionalTest.java    From java-client-api with Apache License 2.0 6 votes vote down vote up
public static void modifyConcurrentUsersOnHttpServer(String restServerName, int numberOfUsers) throws Exception {
	DefaultHttpClient client = new DefaultHttpClient();
	client.getCredentialsProvider().setCredentials(new AuthScope(host, getAdminPort()),
			new UsernamePasswordCredentials("admin", "admin"));
	String extSecurityrName = "";
	String body = "{\"group-name\": \"Default\", \"concurrent-request-limit\":\"" + numberOfUsers + "\"}";

	HttpPut put = new HttpPut("http://" + host + ":" + admin_Port + "/manage/v2/servers/" + restServerName
			+ "/properties?server-type=http");
	put.addHeader("Content-type", "application/json");
	put.setEntity(new StringEntity(body));
	HttpResponse response2 = client.execute(put);
	HttpEntity respEntity = response2.getEntity();
	if (respEntity != null) {
		String content = EntityUtils.toString(respEntity);
		System.out.println(content);
	}
	client.getConnectionManager().shutdown();
}
 
Example #12
Source File: CheckinWorker.java    From dummydroid with Apache License 2.0 6 votes vote down vote up
protected void setProxy(HttpClient client) throws IOException {
	File cfgfile = new File(NETCFG);
	if (cfgfile.exists()) {
		Properties cfg = new Properties();
		cfg.load(new FileInputStream(cfgfile));
		String ph = cfg.getProperty(PROXYHOST, null);
		String pp = cfg.getProperty(PROXYPORT, null);
		String pu = cfg.getProperty(PROXYUSER, null);
		String pw = cfg.getProperty(PROXYPASS, null);
		if (ph == null || pp == null) {
			return;
		}
		final HttpHost proxy = new HttpHost(ph, Integer.parseInt(pp));
		client.getParams().setParameter(ConnRoutePNames.DEFAULT_PROXY, proxy);
		if (pu != null && pw != null) {
			((DefaultHttpClient) client).getCredentialsProvider().setCredentials(
					new AuthScope(proxy), new UsernamePasswordCredentials(pu, pw));
		}
	}
}
 
Example #13
Source File: EndpointTestSource.java    From RDFUnit with Apache License 2.0 6 votes vote down vote up
@Override
protected QueryExecutionFactory initQueryFactory() {

    QueryExecutionFactory qef;
    // if empty
    if (username.isEmpty() && password.isEmpty()) {
        qef = new QueryExecutionFactoryHttp(getSparqlEndpoint(), getSparqlGraphs());
    } else {
        DatasetDescription dd = new DatasetDescription(new ArrayList<>(getSparqlGraphs()), Collections.emptyList());
        CredentialsProvider provider = new BasicCredentialsProvider();
        UsernamePasswordCredentials credentials
                = new UsernamePasswordCredentials(username, password);
        provider.setCredentials(AuthScope.ANY, credentials);

        HttpClient client = HttpClientBuilder.create()
                .setDefaultCredentialsProvider(provider)
                .build();
        qef = new QueryExecutionFactoryHttp(getSparqlEndpoint(), dd, client);
    }

    return masqueradeQEF(qef, this);
}
 
Example #14
Source File: DownloadHttpArtifact.java    From vertx-deploy-tools with Apache License 2.0 6 votes vote down vote up
@Override
public Observable<T> executeAsync(T request) {
    CredentialsProvider provider = new BasicCredentialsProvider();
    UsernamePasswordCredentials credentials
            = new UsernamePasswordCredentials(config.getHttpAuthUser(), config.getHttpAuthPassword());
    provider.setCredentials(AuthScope.ANY, credentials);
    final URI location = config.getNexusUrl().resolve(config.getNexusUrl().getPath() + "/" + request.getRemoteLocation());
    try (CloseableHttpClient client = HttpClientBuilder.create().setDefaultCredentialsProvider(provider).build()) {
        LOG.info("[{} - {}]: Downloaded artifact {} to {}.", logConstant, request.getId(), request.getModuleId(), request.getLocalPath(config.getArtifactRepo()));
        HttpUriRequest get = new HttpGet(location);
        CloseableHttpResponse response = client.execute(get);
        response.getEntity().writeTo(new FileOutputStream(request.getLocalPath(config.getArtifactRepo()).toFile()));
    } catch (IOException e) {
        LOG.error("[{} - {}]: Error downloading artifact -> {}, {}", logConstant, request.getId(), e.getMessage(), e);
        throw new IllegalStateException(e);
    }
    return just(request);
}
 
Example #15
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 #16
Source File: Utils.java    From BotLibre with Eclipse Public License 1.0 6 votes vote down vote up
public static String httpAuthPOST(String url, String user, String password, String agent, String type, String data) throws Exception {
	HttpPost request = new HttpPost(url);
	request.setHeader("User-Agent", agent);
	StringEntity params = new StringEntity(data, "utf-8");
	request.addHeader("content-type", type);
	request.setEntity(params);
	HttpParams httpParams = new BasicHttpParams();
	HttpConnectionParams.setConnectionTimeout(httpParams, URL_TIMEOUT);
	HttpConnectionParams.setSoTimeout(httpParams, URL_TIMEOUT);
	DefaultHttpClient client = new DefaultHttpClient(httpParams);
	client.getCredentialsProvider().setCredentials(
			new AuthScope(AuthScope.ANY),
			new UsernamePasswordCredentials(user, password));
	HttpResponse response = client.execute(request);
	return fetchResponse(response);
}
 
Example #17
Source File: RestRequestByHttpClient.java    From activiti-in-action-codes with Apache License 2.0 6 votes vote down vote up
public static void main(String[] args) throws IOException {

        // 设置Base Auth验证信息
        CredentialsProvider provider = new BasicCredentialsProvider();
        UsernamePasswordCredentials credentials = new UsernamePasswordCredentials("kermit", "kermit");
        provider.setCredentials(AuthScope.ANY, credentials);

        // 创建HttpClient
        HttpClient client = HttpClientBuilder.create().setDefaultCredentialsProvider(provider).build();

        // 发送请求
        HttpResponse response = client.execute(new HttpGet(REST_URI));
        HttpEntity entity = response.getEntity();
        if (entity != null) {
            String content = EntityUtils.toString(entity, "UTF-8");
            System.out.println(content);
        }
    }
 
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: DefaultCredentialsProvider.java    From htmlunit with Apache License 2.0 6 votes vote down vote up
/**
 * Find matching {@link Credentials credentials} for the given authentication scope.
 *
 * @param map the credentials hash map
 * @param authscope the {@link AuthScope authentication scope}
 * @return the credentials
 */
private static Credentials matchCredentials(final Map<AuthScopeProxy, Credentials> map, final AuthScope authscope) {
    Credentials creds = map.get(new AuthScopeProxy(authscope));
    if (creds == null) {
        int bestMatchFactor = -1;
        AuthScopeProxy bestMatch = null;
        for (final AuthScopeProxy proxy : map.keySet()) {
            final AuthScope current = proxy.getAuthScope();
            final int factor = authscope.match(current);
            if (factor > bestMatchFactor) {
                bestMatchFactor = factor;
                bestMatch = proxy;
            }
        }
        if (bestMatch != null) {
            creds = map.get(bestMatch);
        }
    }
    return creds;
}
 
Example #20
Source File: WebAuthentication.java    From fess with Apache License 2.0 6 votes vote down vote up
private AuthScope getAuthScope() {
    if (StringUtil.isBlank(getHostname())) {
        return AuthScope.ANY;
    }

    int p;
    if (getPort() == null) {
        p = AuthScope.ANY_PORT;
    } else {
        p = getPort();
    }

    String r = getAuthRealm();
    if (StringUtil.isBlank(r)) {
        r = AuthScope.ANY_REALM;
    }

    String s = getProtocolScheme();
    if (StringUtil.isBlank(s) || Constants.NTLM.equals(s)) {
        s = AuthScope.ANY_SCHEME;
    }

    return new AuthScope(getHostname(), p, r, s);
}
 
Example #21
Source File: ConnectedRESTQA.java    From java-client-api with Apache License 2.0 5 votes vote down vote up
public static void deleteElementRangeIndexTemporalCollection(String dbName, String collectionName)
		throws Exception {
	DefaultHttpClient client = new DefaultHttpClient();
	client.getCredentialsProvider().setCredentials(new AuthScope(host_name, getAdminPort()),
			new UsernamePasswordCredentials("admin", "admin"));

	HttpDelete del = new HttpDelete("http://" + host_name + ":" + admin_port + "/manage/v2/databases/" + dbName
			+ "/temporal/collections?collection=" + collectionName + "&format=json");

	del.addHeader("Content-type", "application/json");
	del.addHeader("accept", "application/json");

	HttpResponse response = client.execute(del);
	HttpEntity respEntity = response.getEntity();
	if (response.getStatusLine().getStatusCode() == 400) {
		HttpEntity entity = response.getEntity();
		String responseString = EntityUtils.toString(entity, "UTF-8");
		System.out.println(responseString);
	} else if (respEntity != null) {
		// EntityUtils to get the response content
		String content = EntityUtils.toString(respEntity);
		System.out.println(content);
	} else {
		System.out.println("Collection: " + collectionName + " deleted");
		System.out.println("==============================================================");
	}
	client.getConnectionManager().shutdown();
}
 
Example #22
Source File: HttpTransactionExecutor.java    From SmartApplianceEnabler with GNU General Public License v2.0 5 votes vote down vote up
protected HttpClientBuilder withUsernameAndPassword(HttpClientBuilder httpClientBuilder, String username, String password) {
    if(username != null && password != null) {
        logger.debug("{}: username={} password={}", applianceId, username, password);
        CredentialsProvider provider = new BasicCredentialsProvider();
        UsernamePasswordCredentials credentials = new UsernamePasswordCredentials(username, password);
        provider.setCredentials(AuthScope.ANY, credentials);
        httpClientBuilder.setDefaultCredentialsProvider(provider);
    }
    return httpClientBuilder;
}
 
Example #23
Source File: IdpTest.java    From cxf-fediz with Apache License 2.0 5 votes vote down vote up
@org.junit.Test
public void testNoEndpointAddressOrConstraint() throws Exception {
    String url = "https://localhost:" + getIdpHttpsPort() + "/fediz-idp/federation?";
    url += "wa=wsignin1.0";
    url += "&whr=urn:org:apache:cxf:fediz:idp:realm-A";
    url += "&wtrealm=urn:org:apache:cxf:fediz:fedizhelloworld4";
    String wreply = "https://localhost:" + getRpHttpsPort() + "/" + getServletContextName() + "/secure/fedservlet";
    url += "&wreply=" + wreply;

    String user = "alice";
    String password = "ecila";

    final WebClient webClient = new WebClient();
    webClient.getOptions().setUseInsecureSSL(true);
    webClient.getCredentialsProvider().setCredentials(
        new AuthScope("localhost", Integer.parseInt(getIdpHttpsPort())),
        new UsernamePasswordCredentials(user, password));

    webClient.getOptions().setJavaScriptEnabled(false);
    // This is an error in the IdP
    try {
        webClient.getPage(url);
        Assert.fail("Failure expected on a bad wreply value");
    } catch (FailingHttpStatusCodeException ex) {
        Assert.assertEquals(ex.getStatusCode(), 400);
    }

    webClient.close();
}
 
Example #24
Source File: ElasticSearcher.java    From jpress with GNU Lesser General Public License v3.0 5 votes vote down vote up
private void configUserNameAndPassowrd(RestClientBuilder builder) {
    String username = JPressOptions.get("article_search_es_username");
    String password = JPressOptions.get("article_search_es_password");

    if (StrUtil.isBlank(username) || StrUtil.isBlank(password)) {
        return;
    }

    CredentialsProvider credentialsProvider = new BasicCredentialsProvider();
    credentialsProvider.setCredentials(AuthScope.ANY, new UsernamePasswordCredentials(username, username));
    builder.setHttpClientConfigCallback(httpAsyncClientBuilder ->
            httpAsyncClientBuilder.setDefaultCredentialsProvider(credentialsProvider));
}
 
Example #25
Source File: WebServicesClient.java    From attic-apex-core with Apache License 2.0 5 votes vote down vote up
private static void setupUserPassAuthScheme(AuthScheme scheme, String httpScheme, AuthSchemeProvider provider, ConfigProvider configuration)
{
  String username = configuration.getProperty(scheme, "username");
  String password = configuration.getProperty(scheme, "password");
  if ((username != null) && (password != null)) {
    LOG.info("Setting up scheme {}", scheme);
    AuthScope authScope = new AuthScope(AuthScope.ANY_HOST, AuthScope.ANY_PORT, AuthScope.ANY_REALM, httpScheme);
    Credentials credentials = new UsernamePasswordCredentials(username, password);
    setupHttpAuthScheme(httpScheme, provider, authScope, credentials);
  } else if ((username != null) || (password != null)) {
    LOG.warn("Not setting up scheme {}, missing credentials {}", scheme, (username == null) ? "username" : "password");
  }
}
 
Example #26
Source File: HttpRequestHelper.java    From YiBo with Apache License 2.0 5 votes vote down vote up
private static void updateProxySetting(HttpConfig config, DefaultHttpClient httpClient) {
	if (config == null || httpClient == null){
		return;
	}

	HttpHost[] proxyChain = null;

	if (globalProxy != null) {
		//全局代理设置
		proxyChain = new HttpHost[] {globalProxy};
		if (globalProxyCredentials != null){
			AuthScope globalProxyAuthScope = new AuthScope(globalProxy.getHostName(), globalProxy.getPort());
			httpClient.getCredentialsProvider().setCredentials(globalProxyAuthScope, globalProxyCredentials);
		}
	}

	if (config.isUseProxy() && StringUtil.isNotEmpty(config.getHttpProxyHost())){
		HttpHost spProxy = new HttpHost(config.getHttpProxyHost(), config.getHttpProxyPort());
		if (globalProxy != null){
			proxyChain = new HttpHost[] {globalProxy, spProxy};
		} else {
			proxyChain = new HttpHost[] {spProxy};
		}
		if (StringUtil.isNotEmpty(config.getHttpProxyUser())){
			AuthScope spProxyAuthScope = new AuthScope(spProxy.getHostName(), spProxy.getPort());
			UsernamePasswordCredentials spProxyCredentials = new UsernamePasswordCredentials(
					config.getHttpProxyUser(), config.getHttpProxyPassword());
			httpClient.getCredentialsProvider().setCredentials(spProxyAuthScope, spProxyCredentials);
		}
	}

	httpClient.setRoutePlanner(new LibHttpRoutePlanner(connectionManager.getSchemeRegistry(), proxyChain));
}
 
Example #27
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 #28
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 #29
Source File: LayerHttpServiceImpl.java    From geomajas-project-server with GNU Affero General Public License v3.0 5 votes vote down vote up
public InputStream getStream(String baseUrl, RasterLayer layer) throws IOException {
	String url = baseUrl;
	HttpContext context = null;
	if (layer instanceof ProxyLayerSupport) {
		context = new BasicHttpContext();
		// pass url and layer id to the CompositeInterceptor
		context.setAttribute(CompositeInterceptor.BASE_URL, baseUrl);
		context.setAttribute(CompositeInterceptor.LAYER_ID, layer.getId());
		// handle proxy authentication and interceptors
		ProxyLayerSupport proxyLayer = (ProxyLayerSupport) layer;
		ProxyAuthentication authentication = proxyLayer.getProxyAuthentication();
		url = addCredentialsToUrl(baseUrl, authentication);

		// -- add basic authentication
		if (null != authentication
				&& (ProxyAuthenticationMethod.BASIC.equals(authentication.getMethod()) ||
					ProxyAuthenticationMethod.DIGEST.equals(authentication.getMethod()))) {
			// Set up the credentials:
			Credentials creds = new UsernamePasswordCredentials(authentication.getUser(),
					authentication.getPassword());
			URL u = new URL(url);
			AuthScope scope = new AuthScope(u.getHost(), u.getPort(), authentication.getRealm());
			// thread-safe, this is ok
			client.getCredentialsProvider().setCredentials(scope, creds);
		}
	}

	// Create the GET method with the correct URL:
	HttpGet get = new HttpGet(url);

	// Execute the GET:
	HttpResponse response = client.execute(get, context);
	log.debug("Response: {} - {}", response.getStatusLine().getStatusCode(), response.getStatusLine()
			.getReasonPhrase());

	return response.getEntity().getContent();
}
 
Example #30
Source File: ElasticSearchIndexBootStrapper.java    From ranger with Apache License 2.0 5 votes vote down vote up
private void createClient() {
	try {
		final CredentialsProvider credentialsProvider;
		if (StringUtils.isNotBlank(user)) {
			credentialsProvider = new BasicCredentialsProvider();
			credentialsProvider.setCredentials(AuthScope.ANY, new UsernamePasswordCredentials(user, password));
		} else {
			credentialsProvider = null;
		}

		client = new RestHighLevelClient(RestClient
				.builder(EmbeddedServerUtil.toArray(hosts, ",").stream().map(x -> new HttpHost(x, port, protocol))
						.<HttpHost>toArray(i -> new HttpHost[i]))
				.setHttpClientConfigCallback(clientBuilder -> (credentialsProvider != null)
						? clientBuilder.setDefaultCredentialsProvider(credentialsProvider)
						: clientBuilder));
	} catch (Throwable t) {
		lastLoggedAt.updateAndGet(lastLoggedAt -> {
			long now = System.currentTimeMillis();
			long elapsed = now - lastLoggedAt;
			if (elapsed > TimeUnit.MINUTES.toMillis(1)) {
				LOG.severe("Can't connect to ElasticSearch server: " + connectionString() + t);
				return now;
			} else {
				return lastLoggedAt;
			}
		});
	}
}