Example usage for org.apache.http.auth AuthScope ANY

List of usage examples for org.apache.http.auth AuthScope ANY

Introduction

In this page you can find the example usage for org.apache.http.auth AuthScope ANY.

Prototype

AuthScope ANY

To view the source code for org.apache.http.auth AuthScope ANY.

Click Source Link

Document

Default scope matching any host, port, realm and authentication scheme.

Usage

From source file:com.urswolfer.gerrit.client.rest.http.GerritRestClient.java

private HttpClientBuilder getHttpClient(HttpContext httpContext) {
    HttpClientBuilder client = HttpClients.custom();

    client.useSystemProperties(); // see also: com.intellij.util.net.ssl.CertificateManager

    OkHttpClient c = new OkHttpClient();
    c.setFollowRedirects(true);//  ww  w.  j  a  va2 s  .c  om
    // we need to get redirected result after login (which is done with POST) for extracting xGerritAuth
    client.setRedirectStrategy(new LaxRedirectStrategy());

    c.setCookieHandler(cookieManager);

    c.setConnectTimeout(CONNECTION_TIMEOUT_MS, TimeUnit.MILLISECONDS);
    c.setReadTimeout(CONNECTION_TIMEOUT_MS, TimeUnit.MILLISECONDS);
    c.setWriteTimeout(CONNECTION_TIMEOUT_MS, TimeUnit.MILLISECONDS);

    CredentialsProvider credentialsProvider = getCredentialsProvider();
    client.setDefaultCredentialsProvider(credentialsProvider);

    if (authData.isLoginAndPasswordAvailable()) {
        credentialsProvider.setCredentials(AuthScope.ANY,
                new UsernamePasswordCredentials(authData.getLogin(), authData.getPassword()));

        BasicScheme basicAuth = new BasicScheme();
        httpContext.setAttribute(PREEMPTIVE_AUTH, basicAuth);
        client.addInterceptorFirst(new PreemptiveAuthHttpRequestInterceptor(authData));
    }

    client.addInterceptorLast(new UserAgentHttpRequestInterceptor());

    for (HttpClientBuilderExtension httpClientBuilderExtension : httpClientBuilderExtensions) {
        client = httpClientBuilderExtension.extend(client, authData);
        credentialsProvider = httpClientBuilderExtension.extendCredentialProvider(client, credentialsProvider,
                authData);
    }

    return client;
}

From source file:org.glassfish.jersey.apache.connector.AuthTest.java

@Test
public void testAuthInteractiveGet() {
    CredentialsProvider credentialsProvider = new org.apache.http.impl.client.BasicCredentialsProvider();
    credentialsProvider.setCredentials(AuthScope.ANY, new UsernamePasswordCredentials("name", "password"));
    ClientConfig cc = new ClientConfig();
    cc.property(ApacheClientProperties.CREDENTIALS_PROVIDER, credentialsProvider);
    cc.connectorProvider(new ApacheConnectorProvider());
    Client client = ClientBuilder.newClient(cc);

    WebTarget r = client.target(getBaseUri()).path("test");

    assertEquals("GET", r.request().get(String.class));
}

From source file:org.botlibre.util.Utils.java

public static String httpAuthGET(String url, String user, String password) throws Exception {
    HttpGet request = new HttpGet(url);

    DefaultHttpClient client = new DefaultHttpClient();
    client.getCredentialsProvider().setCredentials(new AuthScope(AuthScope.ANY),
            new UsernamePasswordCredentials(user, password));
    HttpResponse response = client.execute(request);
    return fetchResponse(response);
}

From source file:org.sonatype.nexus.apachehttpclient.Hc4ProviderImplTest.java

@Test
public void credentialsProviderReplaced() {
    testSubject = new Hc4ProviderImpl(applicationConfiguration, userAgentBuilder, eventBus, jmxInstaller, null);

    final Builder builder = testSubject
            .prepareHttpClient(applicationConfiguration.getGlobalRemoteStorageContext());

    final RemoteAuthenticationSettings remoteAuthenticationSettings = new UsernamePasswordRemoteAuthenticationSettings(
            "user", "pass");
    testSubject.applyAuthenticationConfig(builder, remoteAuthenticationSettings, null);

    final DefaultRemoteHttpProxySettings httpProxy = new DefaultRemoteHttpProxySettings();
    httpProxy.setHostname("http-proxy");
    httpProxy.setPort(8080);/* www  .j  a  v a  2s.c om*/
    httpProxy.setProxyAuthentication(
            new UsernamePasswordRemoteAuthenticationSettings("http-proxy", "http-pass"));
    final DefaultRemoteHttpProxySettings httpsProxy = new DefaultRemoteHttpProxySettings();
    httpsProxy.setHostname("https-proxy");
    httpsProxy.setPort(9090);
    httpsProxy.setProxyAuthentication(
            new UsernamePasswordRemoteAuthenticationSettings("https-proxy", "https-pass"));
    final DefaultRemoteProxySettings remoteProxySettings = new DefaultRemoteProxySettings();
    remoteProxySettings.setHttpProxySettings(httpProxy);
    remoteProxySettings.setHttpsProxySettings(httpsProxy);

    testSubject.applyProxyConfig(builder, remoteProxySettings);

    final CredentialsProvider credentialsProvider = builder.getCredentialsProvider();

    assertThat(credentialsProvider.getCredentials(AuthScope.ANY), notNullValue(Credentials.class));
    assertThat(credentialsProvider.getCredentials(AuthScope.ANY).getUserPrincipal().getName(), equalTo("user"));
    assertThat(credentialsProvider.getCredentials(AuthScope.ANY).getPassword(), equalTo("pass"));

    final AuthScope httpProxyAuthScope = new AuthScope(new HttpHost("http-proxy", 8080));
    assertThat(credentialsProvider.getCredentials(httpProxyAuthScope), notNullValue(Credentials.class));
    assertThat(credentialsProvider.getCredentials(httpProxyAuthScope).getUserPrincipal().getName(),
            equalTo("http-proxy"));
    assertThat(credentialsProvider.getCredentials(httpProxyAuthScope).getPassword(), equalTo("http-pass"));

    final AuthScope httpsProxyAuthScope = new AuthScope(new HttpHost("https-proxy", 9090));
    assertThat(credentialsProvider.getCredentials(httpsProxyAuthScope), notNullValue(Credentials.class));
    assertThat(credentialsProvider.getCredentials(httpsProxyAuthScope).getUserPrincipal().getName(),
            equalTo("https-proxy"));
    assertThat(credentialsProvider.getCredentials(httpsProxyAuthScope).getPassword(), equalTo("https-pass"));
}

From source file:aajavafx.Schedule1Controller.java

public ObservableList<EmployeeProperty> getEmployee() throws IOException, JSONException {
    Employees myEmployee = new Employees();

    Gson gson = new Gson();
    ObservableList<EmployeeProperty> employeesProperty = FXCollections.observableArrayList();
    JSONObject jo = new JSONObject();

    CredentialsProvider provider = new BasicCredentialsProvider();
    UsernamePasswordCredentials credentials = new UsernamePasswordCredentials("EMPLOYEE", "password");
    provider.setCredentials(AuthScope.ANY, credentials);
    HttpClient client = HttpClientBuilder.create().setDefaultCredentialsProvider(provider).build();
    HttpGet get = new HttpGet("http://localhost:8080/MainServerREST/api/employees");
    HttpResponse response = client.execute(get);
    System.out.println("RESPONSE IS: " + response);

    JSONArray jsonArray = new JSONArray(
            IOUtils.toString(response.getEntity().getContent(), Charset.forName("UTF-8")));
    System.out.println(jsonArray);
    for (int i = 0; i < jsonArray.length(); i++) {
        jo = (JSONObject) jsonArray.getJSONObject(i);
        myEmployee = gson.fromJson(jo.toString(), Employees.class);
        if (myEmployee.getEmpRegistered() == true) {
            employeesProperty.add(new EmployeeProperty(myEmployee.getEmpId(), myEmployee.getEmpFirstname(),
                    myEmployee.getEmpLastname(), myEmployee.getEmpUsername()));
        }//from  w ww .ja  v a2s .  c  o m
    }
    return employeesProperty;
}

From source file:org.apache.solr.client.solrj.impl.HttpClientUtil.java

private static HttpClientBuilder setupBuilder(HttpClientBuilder builder, SolrParams config) {

    Builder requestConfigBuilder = RequestConfig.custom()
            .setRedirectsEnabled(config.getBool(HttpClientUtil.PROP_FOLLOW_REDIRECTS, false))
            .setDecompressionEnabled(false)
            .setConnectTimeout(config.getInt(HttpClientUtil.PROP_CONNECTION_TIMEOUT, DEFAULT_CONNECT_TIMEOUT))
            .setSocketTimeout(config.getInt(HttpClientUtil.PROP_SO_TIMEOUT, DEFAULT_SO_TIMEOUT));

    String cpolicy = cookiePolicy;
    if (cpolicy != null) {
        requestConfigBuilder.setCookieSpec(cpolicy);
    }// w  w w . j  a  v a  2  s  . c  om

    RequestConfig requestConfig = requestConfigBuilder.build();

    HttpClientBuilder retBuilder = builder.setDefaultRequestConfig(requestConfig);

    if (config.getBool(HttpClientUtil.PROP_USE_RETRY, true)) {
        retBuilder = retBuilder.setRetryHandler(new SolrHttpRequestRetryHandler(3));

    } else {
        retBuilder = retBuilder.setRetryHandler(NO_RETRY);
    }

    final String basicAuthUser = config.get(HttpClientUtil.PROP_BASIC_AUTH_USER);
    final String basicAuthPass = config.get(HttpClientUtil.PROP_BASIC_AUTH_PASS);

    if (basicAuthUser != null && basicAuthPass != null) {
        CredentialsProvider credsProvider = new BasicCredentialsProvider();
        credsProvider.setCredentials(AuthScope.ANY,
                new UsernamePasswordCredentials(basicAuthUser, basicAuthPass));
        retBuilder.setDefaultCredentialsProvider(credsProvider);
    }

    if (config.getBool(HttpClientUtil.PROP_ALLOW_COMPRESSION, false)) {
        retBuilder.addInterceptorFirst(new UseCompressionRequestInterceptor());
        retBuilder.addInterceptorFirst(new UseCompressionResponseInterceptor());
    } else {
        retBuilder.disableContentCompression();
    }

    return retBuilder;
}

From source file:com.ibm.watson.developer_cloud.professor_languo.pipeline.RnrMergerAndRanker.java

/**
 * Rank {@code answers} to {@code question}
 * //  w w  w.  j  av  a2  s.c o m
 * @param question {@link Question} from which {@link answers} are formed
 * @param answers list of {@link CandidateAnswer}'s
 * @return Ranked answers
 */
private Observable<CandidateAnswer> apply(Question question, Observable<CandidateAnswer> answers) {

    try {
        // Create authorized HttpClient
        CloseableHttpClient client = RankerCreationUtil.createHttpClient(AuthScope.ANY, creds);

        // Build feature vector data for candidate answers in csv format
        String csvAnswerData = RankerCreationUtil.getCsvAnswerData(answers.toList().toBlocking().first(), null);

        // Send rank request
        String rank_request_url = ranker_url + "/" + current_ranker_id
                + RetrieveAndRankSearcherConstants.RANK_REQUEST_HANDLER;
        JSONObject responseJSON = RankerCreationUtil.rankAnswers(client, rank_request_url, csvAnswerData);
        JSONArray rankedAnswerArray = (JSONArray) responseJSON.get("answers");

        // If there is an error with the service, wait a moment
        // and retry up to retry limit
        int retryAttempt = 1;
        while (rankedAnswerArray == null) {
            if (retryAttempt > retryLimit) {
                throw new PipelineException(MessageFormat
                        .format(Messages.getString("RetrieveAndRank.QUERY_RETRY_FAILED"), retryAttempt)); //$NON-NLS-1$
            }
            Thread.sleep(3000);
            logger.info(MessageFormat.format(Messages.getString("RetrieveAndRank.QUERY_RETRY"), retryAttempt)); //$NON-NLS-1$
            responseJSON = RankerCreationUtil.rankAnswers(client, rank_request_url, csvAnswerData);
            rankedAnswerArray = (JSONArray) responseJSON.get("answers");
            retryAttempt++;
        }

        // Iterate through JSONArray of ranked answers and match with the
        // original
        List<CandidateAnswer> answerList = answers.toList().toBlocking().first();

        // Set confidence to the top answers chosen by the ranker,
        // ignore the rest
        List<CandidateAnswer> rankedAnswerList = new ArrayList<CandidateAnswer>();

        for (int i = 0; i < answerList.size(); i++) {
            for (int j = 0; j < rankedAnswerArray.size(); j++) {
                JSONObject ans = (JSONObject) rankedAnswerArray.get(j);
                // Get the answer_id
                String answer_id = (String) ans.get(RetrieveAndRankConstants.ANSWER_ID_HEADER);
                double confidence = (double) ans.get(RetrieveAndRankConstants.CONFIDENCE_HEADER);
                if (answerList.get(i).getAnswerLabel().equals(answer_id)) {
                    // Set the answer's confidence
                    answerList.get(i).setConfidence(confidence);
                    rankedAnswerList.add(answerList.get(i));
                }
            }
        }

        return Observable.from(rankedAnswerList);

    } catch (ClientProtocolException e) {
        logger.error(e.getMessage());
    } catch (IOException e) {
        logger.error(e.getMessage());
        // Something wrong with the service. Set all confidence to 0
        List<CandidateAnswer> answerList = answers.toList().toBlocking().first();
        for (CandidateAnswer answer : answerList) {
            answer.setConfidence(0);
        }
    } catch (Exception e) {
        logger.error(e.getMessage());
    }
    return answers;
}

From source file:org.sonatype.nexus.internal.httpclient.HttpClientFactoryImplTest.java

@Test
public void credentialsProviderReplaced() {
    testSubject = new HttpClientFactoryImpl(Providers.of(systemStatus),
            Providers.of(globalRemoteStorageContext), eventBus, jmxInstaller, null);

    RemoteStorageContextCustomizer customizer = new RemoteStorageContextCustomizer(globalRemoteStorageContext);
    final Builder builder = testSubject.prepare(customizer);

    final RemoteAuthenticationSettings remoteAuthenticationSettings = new UsernamePasswordRemoteAuthenticationSettings(
            "user", "pass");
    customizer.applyAuthenticationConfig(builder, remoteAuthenticationSettings, null);

    final DefaultRemoteHttpProxySettings httpProxy = new DefaultRemoteHttpProxySettings();
    httpProxy.setHostname("http-proxy");
    httpProxy.setPort(8080);/*from   ww  w . j a  v  a  2  s. com*/
    httpProxy.setProxyAuthentication(
            new UsernamePasswordRemoteAuthenticationSettings("http-proxy", "http-pass"));

    final DefaultRemoteHttpProxySettings httpsProxy = new DefaultRemoteHttpProxySettings();
    httpsProxy.setHostname("https-proxy");
    httpsProxy.setPort(9090);
    httpsProxy.setProxyAuthentication(
            new UsernamePasswordRemoteAuthenticationSettings("https-proxy", "https-pass"));

    final DefaultRemoteProxySettings remoteProxySettings = new DefaultRemoteProxySettings();
    remoteProxySettings.setHttpProxySettings(httpProxy);
    remoteProxySettings.setHttpsProxySettings(httpsProxy);

    customizer.applyProxyConfig(builder, remoteProxySettings);

    final CredentialsProvider credentialsProvider = builder.getCredentialsProvider();

    assertThat(credentialsProvider.getCredentials(AuthScope.ANY), notNullValue(Credentials.class));
    assertThat(credentialsProvider.getCredentials(AuthScope.ANY).getUserPrincipal().getName(), equalTo("user"));
    assertThat(credentialsProvider.getCredentials(AuthScope.ANY).getPassword(), equalTo("pass"));

    final AuthScope httpProxyAuthScope = new AuthScope(new HttpHost("http-proxy", 8080));
    assertThat(credentialsProvider.getCredentials(httpProxyAuthScope), notNullValue(Credentials.class));
    assertThat(credentialsProvider.getCredentials(httpProxyAuthScope).getUserPrincipal().getName(),
            equalTo("http-proxy"));
    assertThat(credentialsProvider.getCredentials(httpProxyAuthScope).getPassword(), equalTo("http-pass"));

    final AuthScope httpsProxyAuthScope = new AuthScope(new HttpHost("https-proxy", 9090));
    assertThat(credentialsProvider.getCredentials(httpsProxyAuthScope), notNullValue(Credentials.class));
    assertThat(credentialsProvider.getCredentials(httpsProxyAuthScope).getUserPrincipal().getName(),
            equalTo("https-proxy"));
    assertThat(credentialsProvider.getCredentials(httpsProxyAuthScope).getPassword(), equalTo("https-pass"));
}