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:cf.spring.servicebroker.AbstractServiceBrokerTest.java

protected BasicCredentialsProvider credentials() {
    final BasicCredentialsProvider credentialsProvider = new BasicCredentialsProvider();
    credentialsProvider.setCredentials(AuthScope.ANY, new UsernamePasswordCredentials(USERNAME, PASSWORD));
    return credentialsProvider;
}

From source file:org.springframework.cloud.deployer.admin.shell.command.support.HttpClientUtils.java

/**
 * Ensures that the passed-in {@link RestTemplate} is using the Apache HTTP Client. If the optional {@code username} AND
 * {@code password} are not empty, then a {@link BasicCredentialsProvider} will be added to the {@link CloseableHttpClient}.
 *
 * Furthermore, you can set the underlying {@link SSLContext} of the {@link HttpClient} allowing you to accept self-signed
 * certificates./*w  ww. j  av a 2s  . co  m*/
 *
 * @param restTemplate Must not be null
 * @param username Can be null
 * @param password Can be null
 * @param skipSslValidation Use with caution! If true certificate warnings will be ignored.
 */
public static void prepareRestTemplate(RestTemplate restTemplate, String username, String password,
        boolean skipSslValidation) {

    Assert.notNull(restTemplate, "The provided RestTemplate must not be null.");

    final HttpClientBuilder httpClientBuilder = HttpClientBuilder.create();

    if (StringUtils.hasText(username) && StringUtils.hasText(password)) {
        final BasicCredentialsProvider credentialsProvider = new BasicCredentialsProvider();
        credentialsProvider.setCredentials(AuthScope.ANY, new UsernamePasswordCredentials(username, password));
        httpClientBuilder.setDefaultCredentialsProvider(credentialsProvider);
    }

    if (skipSslValidation) {
        httpClientBuilder.setSSLContext(HttpClientUtils.buildCertificateIgnoringSslContext());
        httpClientBuilder.setSSLHostnameVerifier(new NoopHostnameVerifier());
    }

    final CloseableHttpClient httpClient = httpClientBuilder.build();
    final HttpComponentsClientHttpRequestFactory requestFactory = new HttpComponentsClientHttpRequestFactory(
            httpClient);
    restTemplate.setRequestFactory(requestFactory);
}

From source file:org.wildfly.swarm.jaxrs.SimpleHttp.java

protected Response getUrlContents(String theUrl, boolean useAuth, boolean followRedirects) {

    StringBuilder content = new StringBuilder();
    int code;/*  ww w . j a v a2s.  c  o  m*/

    try {

        CredentialsProvider provider = new BasicCredentialsProvider();

        HttpClientBuilder builder = HttpClientBuilder.create();
        if (!followRedirects) {
            builder.disableRedirectHandling();
        }
        if (useAuth) {
            UsernamePasswordCredentials credentials = new UsernamePasswordCredentials("admin", "password");
            provider.setCredentials(AuthScope.ANY, credentials);
            builder.setDefaultCredentialsProvider(provider);
        }
        HttpClient client = builder.build();

        HttpResponse response = client.execute(new HttpGet(theUrl));
        code = response.getStatusLine().getStatusCode();

        if (null == response.getEntity()) {
            throw new RuntimeException("No response content present");
        }

        BufferedReader bufferedReader = new BufferedReader(
                new InputStreamReader(response.getEntity().getContent()));

        String line;

        while ((line = bufferedReader.readLine()) != null) {
            content.append(line + "\n");
        }
        bufferedReader.close();
    } catch (Exception e) {
        throw new RuntimeException(e);
    }

    return new Response(code, content.toString());
}

From source file:org.wso2.developerstudio.appfactory.core.client.RssClient.java

public static String getDBinfo(String operation, String dsBaseUrl) {
    String url = dsBaseUrl + "NDataSourceAdmin";
    DefaultHttpClient client = new DefaultHttpClient();
    client = (DefaultHttpClient) HttpsJaggeryClient.wrapClient(client, url);
    client.getCredentialsProvider().setCredentials(new AuthScope(AuthScope.ANY_HOST, AuthScope.ANY_PORT),
            new UsernamePasswordCredentials(Authenticator.getInstance().getCredentials().getUser(),
                    Authenticator.getInstance().getCredentials().getPassword()));

    // Generate BASIC scheme object and stick it to the execution context
    BasicScheme basicAuth = new BasicScheme();
    BasicHttpContext context = new BasicHttpContext();
    context.setAttribute("preemptive-auth", basicAuth);
    client.addRequestInterceptor(new PreemptiveAuth(), 0);

    HttpPost post = new HttpPost(url);
    String sopactionValue = "urn:" + operation;
    post.addHeader("SOAPAction", sopactionValue);
    String body = createPayLoad(operation);
    try {/*from   w w  w  .  j a v  a2s .c o m*/
        StringEntity entity = new StringEntity(body.toString(), "text/xml", HTTP.DEFAULT_CONTENT_CHARSET);
        post.setEntity(entity);
        HttpResponse response = client.execute(post);
        if (200 == response.getStatusLine().getStatusCode()) {
            HttpEntity entityGetAppsOfUser = response.getEntity();
            BufferedReader rd = new BufferedReader(new InputStreamReader(entityGetAppsOfUser.getContent()));
            StringBuilder sb = new StringBuilder();
            String line = "";
            while ((line = rd.readLine()) != null) {
                sb.append(line);
            }
            String respond = sb.toString();
            EntityUtils.consume(entityGetAppsOfUser);
            return respond;
        }
    } catch (Exception e) {
        // log.error("Jenkins Client err", e);
    }
    return null;
}

From source file:org.surfnet.example.api.resources.StudentResource.java

@GET
public Student getStudent(@Auth ClientDetails clientDetails,
        @PathParam("studentIdentifier") String studentIdentifier) {
    if ("@me".equalsIgnoreCase(studentIdentifier)) {
        studentIdentifier = ((Student) clientDetails.getPrincipal()).getIdentifier();
    }/*from  ww w . java2 s .  c o m*/
    return principalService.getPrincipal(new UsernamePasswordCredentials(studentIdentifier, "not-used"));
}

From source file:io.github.jonestimd.neo4j.client.http.ApacheHttpDriver.java

private static BasicCredentialsProvider credentialsProvider(String userName, String password, String host,
        int port) {
    BasicCredentialsProvider credentialsProvider = new BasicCredentialsProvider();
    credentialsProvider.setCredentials(new AuthScope(host, port),
            new UsernamePasswordCredentials(userName, password));
    return credentialsProvider;
}

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

public InputStream getInput(PopulatorContext context) {

    InputStream input;//from  w w  w  . j a  v  a  2  s. com
    DefaultHttpClient httpclient = new DefaultHttpClient();

    try {
        URL xcri = new URL(context.getURI());
        if ("file".equals(xcri.getProtocol())) {
            input = xcri.openStream();

        } else {
            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);
            HttpEntity entity = response.getEntity();

            if (HttpStatus.SC_OK != response.getStatusLine().getStatusCode()) {
                throw new IllegalStateException(
                        "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());

    }

    return input;
}

From source file:org.peterbaldwin.vlcremote.net.ServerConnectionTest.java

@Override
protected Integer doInBackground(Server... servers) {
    if (servers == null || servers.length != 1) {
        return -1;
    }/*from  w  w  w  .jav a 2 s .co  m*/
    URL url;
    try {
        url = new URL("http://" + servers[0].getUri().getAuthority() + TEST_PATH);
        HttpURLConnection connection = (HttpURLConnection) url.openConnection();
        connection.setConnectTimeout(1000);
        try {
            Header auth = BasicScheme.authenticate(
                    new UsernamePasswordCredentials(servers[0].getUser(), servers[0].getPassword()), HTTP.UTF_8,
                    false);
            connection.setRequestProperty(auth.getName(), auth.getValue());
            return connection.getResponseCode();
        } finally {
            connection.disconnect();
        }
    } catch (IOException ex) {

    }
    return -1;
}

From source file:org.energyos.espi.thirdparty.web.ClientRestTemplate.java

public ClientRestTemplate(String username, String password) {
    DefaultHttpClient httpClient = new DefaultHttpClient();
    BasicCredentialsProvider credentialsProvider = new BasicCredentialsProvider();
    credentialsProvider.setCredentials(new AuthScope(AuthScope.ANY_HOST, AuthScope.ANY_PORT),
            new UsernamePasswordCredentials(username, password));
    httpClient.setCredentialsProvider(credentialsProvider);
    httpClient.addRequestInterceptor(new PreemptiveAuthInterceptor(), 0);
    ClientHttpRequestFactory rf = new HttpComponentsClientHttpRequestFactory(httpClient);

    this.setRequestFactory(rf);
}

From source file:com.netdimensions.client.Client.java

public Client(final String url, final String userName, final String password) {
    this(url, new UsernamePasswordCredentials(userName, password));
}