Example usage for org.apache.http.auth UsernamePasswordCredentials UsernamePasswordCredentials

List of usage examples for org.apache.http.auth UsernamePasswordCredentials UsernamePasswordCredentials

Introduction

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

Prototype

public UsernamePasswordCredentials(final String userName, final String password) 

Source Link

Document

The constructor with the username and password arguments.

Usage

From source file:de.escidoc.core.http.HttpClientBuilderImpl.java

@Override
public HttpClientBuilder withUsernamePasswordCredentials(final String urlString, final String username,
        final String password) {
    final URL url;
    try {/*  w w  w .  j a va2  s.  c  o  m*/
        url = new URL(urlString);
    } catch (final MalformedURLException e) {
        throw new IllegalArgumentException("Invalid url '" + urlString + "'.", e);
    }
    final AuthScope authScope = new AuthScope(url.getHost(), AuthScope.ANY_PORT, AuthScope.ANY_REALM);
    final Credentials usernamePasswordCredentials = new UsernamePasswordCredentials(username, password);
    this.httpClient.getCredentialsProvider().setCredentials(authScope, usernamePasswordCredentials);
    return this;
}

From source file:multichain.command.builders.QueryBuilderCommon.java

protected void initialize(String ip, String port, String login, String password,
        RuntimeParameters queryParameter) {
    httppost = new HttpPost("http://" + ip + ":" + port);

    CredentialsProvider provider = new BasicCredentialsProvider();
    UsernamePasswordCredentials credentials = new UsernamePasswordCredentials(login, password);
    provider.setCredentials(AuthScope.ANY, credentials);
    queryParameters = queryParameter;//  w w w  .j  ava 2 s . com

    httpclient = HttpClientBuilder.create().setDefaultCredentialsProvider(provider).build();

}

From source file:com.marklogic.client.test.util.TestServerBootstrapper.java

private void installBootstrapExtension() throws IOException {

    DefaultHttpClient client = new DefaultHttpClient();

    client.getCredentialsProvider().setCredentials(new AuthScope("localhost", port),
            new UsernamePasswordCredentials(username, password));

    HttpPut put = new HttpPut("http://" + host + ":" + port + "/v1/config/resources/bootstrap?method=POST");

    put.setEntity(new FileEntity(new File("src/test/resources/bootstrap.xqy"), "application/xquery"));
    HttpResponse response = client.execute(put);
    @SuppressWarnings("unused")
    HttpEntity entity = response.getEntity();
    System.out.println("Installed bootstrap extension.  Response is " + response.toString());

}

From source file:org.hawkular.client.core.jaxrs.RestFactory.java

public T createAPI(ClientInfo clientInfo) {
    final HttpClient httpclient;
    if (clientInfo.getEndpointUri().toString().startsWith("https")) {
        httpclient = getHttpClient();/*from  ww w.jav a2s. c o  m*/
    } else {
        httpclient = HttpClientBuilder.create().build();
    }
    final ResteasyClient client;
    if (clientInfo.getUsername().isPresent() && clientInfo.getPassword().isPresent()) {
        HttpHost targetHost = new HttpHost(clientInfo.getEndpointUri().getHost(),
                clientInfo.getEndpointUri().getPort());
        CredentialsProvider credsProvider = new BasicCredentialsProvider();
        credsProvider.setCredentials(new AuthScope(targetHost.getHostName(), targetHost.getPort()),
                new UsernamePasswordCredentials(clientInfo.getUsername().get(),
                        clientInfo.getPassword().get()));
        // Create AuthCache instance
        AuthCache authCache = new BasicAuthCache();
        // Generate BASIC scheme object and add it to the local auth cache
        BasicScheme basicAuth = new BasicScheme();
        authCache.put(targetHost, basicAuth);
        // Add AuthCache to the execution context
        HttpClientContext context = HttpClientContext.create();
        context.setCredentialsProvider(credsProvider);
        context.setAuthCache(authCache);
        ApacheHttpClient4Engine engine = new ApacheHttpClient4Engine(httpclient, context);

        client = new ResteasyClientBuilder().httpEngine(engine).build();
    } else {
        ApacheHttpClient4Engine engine = new ApacheHttpClient4Engine(getHttpClient());
        client = new ResteasyClientBuilder().httpEngine(engine).build();
    }

    client.register(JacksonJaxbJsonProvider.class);
    client.register(JacksonObjectMapperProvider.class);
    client.register(RequestLoggingFilter.class);
    client.register(new RequestHeadersFilter(clientInfo.getHeaders()));
    client.register(ResponseLoggingFilter.class);
    client.register(HCJacksonJson2Provider.class);
    client.register(ConvertersProvider.class);

    ProxyBuilder<T> proxyBuilder = client.target(clientInfo.getEndpointUri()).proxyBuilder(apiClassType);
    if (classLoader != null) {
        proxyBuilder = proxyBuilder.classloader(classLoader);
    }
    return proxyBuilder.build();
}

From source file:uk.ac.ox.oucs.vle.XcriPopulatorInput.java

public InputStream getInput(PopulatorContext context) throws PopulatorException {

    InputStream input = null;/*from w  w  w . j a v  a  2s  .  c o m*/
    HttpEntity entity = null;

    try {
        URL xcri = new URL(context.getURI());

        HttpHost targetHost = new HttpHost(xcri.getHost(), xcri.getPort(), xcri.getProtocol());

        httpClient.getCredentialsProvider().setCredentials(
                new AuthScope(targetHost.getHostName(), targetHost.getPort()),
                new UsernamePasswordCredentials(context.getUser(), context.getPassword()));

        HttpGet httpget = new HttpGet(xcri.toURI());
        HttpResponse response = httpClient.execute(targetHost, httpget);
        entity = response.getEntity();

        if (HttpStatus.SC_OK != response.getStatusLine().getStatusCode()) {
            throw new PopulatorException("Invalid Response [" + response.getStatusLine().getStatusCode() + "]");
        }

        input = entity.getContent();

    } catch (MalformedURLException e) {
        throw new PopulatorException(e.getLocalizedMessage());

    } catch (IllegalStateException e) {
        throw new PopulatorException(e.getLocalizedMessage());

    } catch (IOException e) {
        throw new PopulatorException(e.getLocalizedMessage());

    } catch (URISyntaxException e) {
        throw new PopulatorException(e.getLocalizedMessage());

    } finally {
        if (null == input && null != entity) {
            try {
                entity.getContent().close();
            } catch (IOException e) {
                log.error("IOException [" + e + "]");
            }
        }
    }
    return input;
}

From source file:org.alfresco.tutorials.webscripts.HelloWorldWebScriptIT.java

@Test
public void testWebScriptCall() throws Exception {
    String webscriptURL = "http://localhost:8080/alfresco/service/sample/helloworld";
    CredentialsProvider credsProvider = new BasicCredentialsProvider();
    credsProvider.setCredentials(new AuthScope("localhost", 8080),
            new UsernamePasswordCredentials(ALFRESCO_USERNAME, ALFRESCO_PWD));
    CloseableHttpClient httpclient = HttpClients.custom().setDefaultCredentialsProvider(credsProvider).build();

    try {//from  w w  w.  j  av a2s  . com
        HttpGet httpget = new HttpGet(webscriptURL);
        HttpResponse httpResponse = httpclient.execute(httpget);
        assertEquals("HTTP Response Status is not OK(200)", HttpStatus.SC_OK,
                httpResponse.getStatusLine().getStatusCode());
        HttpEntity entity = httpResponse.getEntity();
        assertNotNull("Response from Web Script is null", entity);
        String response = EntityUtils.toString(entity);
        JSONParser parser = new JSONParser();
        JSONObject jsonResponseObj = (JSONObject) parser.parse(response);
        assertTrue("Folder not found", (boolean) jsonResponseObj.get("foundFolder"));
        assertTrue("Doc not found", (boolean) jsonResponseObj.get("foundDoc"));
    } finally {
        httpclient.close();
    }
}

From source file:org.commonjava.indy.httprox.AbstractHttproxFunctionalTest.java

protected CloseableHttpClient proxiedHttp(final String user, final String pass, SSLSocketFactory socketFactory)
        throws Exception {
    CredentialsProvider creds = null;/*from   w  ww. ja  v  a2  s  .  c  o  m*/

    if (user != null) {
        creds = new BasicCredentialsProvider();
        creds.setCredentials(new AuthScope(HOST, proxyPort), new UsernamePasswordCredentials(user, pass));
    }

    HttpHost proxy = new HttpHost(HOST, proxyPort);

    final HttpRoutePlanner planner = new DefaultProxyRoutePlanner(proxy);
    HttpClientBuilder builder = HttpClients.custom().setRoutePlanner(planner)
            .setDefaultCredentialsProvider(creds).setProxy(proxy).setSSLSocketFactory(socketFactory);

    return builder.build();
}

From source file:org.apache.brooklyn.rest.BrooklynRestApiLauncherTestFixture.java

protected HttpClient newClient(String user) throws Exception {
    HttpTool.HttpClientBuilder builder = httpClientBuilder().uri(getBaseUriRest());
    if (user != null) {
        builder.credentials(new UsernamePasswordCredentials(user, "ignoredPassword"));
    }/*from ww  w  .  ja  v a 2s. c o  m*/
    return builder.build();
}

From source file:org.thingsboard.server.dao.audit.sink.ElasticsearchAuditLogSink.java

@PostConstruct
public void init() {
    try {/*  www . j a  v  a 2  s .  c o  m*/
        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);
    }
}