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:org.georchestra.extractorapp.ws.extractor.csw.MetadataEntity.java

/**
 * Stores the metadata retrieved from CSW using the request value.
 * /*from  w w  w.java 2  s .c o m*/
 * @param fileName file name where the metadata must be saved.
 * 
 * @throws IOException
 */
public void save(final String fileName) throws IOException {

    InputStream content = null;
    BufferedReader reader = null;
    PrintWriter writer = null;
    try {
        writer = new PrintWriter(fileName, "UTF-8");

        HttpGet get = new HttpGet(this.request.buildURI());
        CloseableHttpClient httpclient = HttpClients.createDefault();
        HttpClientContext localContext = HttpClientContext.create();

        // if credentials are actually provided, use them to configure
        // the HttpClient object.
        try {
            if (this.request.getUser() != null && request.getPassword() != null) {
                Credentials credentials = new UsernamePasswordCredentials(request.getUser(),
                        request.getPassword());
                AuthScope authScope = new AuthScope(get.getURI().getHost(), get.getURI().getPort());
                CredentialsProvider credentialsProvider = new BasicCredentialsProvider();
                credentialsProvider.setCredentials(authScope, credentials);
                localContext.setCredentialsProvider(credentialsProvider);
            }
        } catch (Exception e) {
            LOG.error(
                    "Unable to set basic-auth on http client to get the Metadata remotely, trying without ...",
                    e);
        }
        content = httpclient.execute(get, localContext).getEntity().getContent();
        reader = new BufferedReader(new InputStreamReader(content));

        String line = reader.readLine();
        while (line != null) {

            writer.println(line);

            line = reader.readLine();
        }

    } catch (Exception e) {

        final String msg = "The metadata could not be extracted";
        LOG.error(msg, e);

        throw new IOException(e);

    } finally {

        if (writer != null)
            writer.close();

        if (reader != null)
            reader.close();

        if (content != null)
            content.close();
    }
}

From source file:de.escidoc.core.test.common.fedora.TripleStoreTestBase.java

protected DefaultHttpClient getHttpClient() throws Exception {
    DefaultHttpClient httpClient = new DefaultHttpClient();
    URL url = new URL(getFedoraUrl());
    AuthScope m_authScope = new AuthScope(url.getHost(), AuthScope.ANY_PORT, AuthScope.ANY_REALM);
    UsernamePasswordCredentials m_creds = new UsernamePasswordCredentials("fedoraAdmin", "fedoraAdmin");
    httpClient.getCredentialsProvider().setCredentials(m_authScope, m_creds);

    return httpClient;
}

From source file:org.apache.olingo.client.core.http.ProxyWrappingHttpClientFactory.java

@Override
public HttpClient create(final HttpMethod method, final URI uri) {
    // Use wrapped factory to obtain an httpclient instance for given method and uri
    final DefaultHttpClient httpclient = wrapped.create(method, uri);

    final HttpHost proxyHost = new HttpHost(proxy.getHost(), proxy.getPort());

    // Sets usage of HTTP proxy
    httpclient.getParams().setParameter(ConnRoutePNames.DEFAULT_PROXY, proxyHost);

    // Sets proxy authentication, if credentials were provided
    if (proxyUsername != null && proxyPassword != null) {
        httpclient.getCredentialsProvider().setCredentials(new AuthScope(proxyHost),
                new UsernamePasswordCredentials(proxyUsername, proxyPassword));
    }/*from   w w w . j a v a2s  . c  o  m*/

    return httpclient;
}

From source file:com.emc.storageos.driver.dellsc.scapi.rest.RestClient.java

/**
 * Instantiates a new Rest client./*from w  w w .  j  a va  2s  .c  om*/
 *
 * @param host Host name or IP address of the Dell Storage Manager server.
 * @param port Port the DSM data collector is listening on.
 * @param user The DSM user name to use.
 * @param password The DSM password.
 */
public RestClient(String host, int port, String user, String password) {
    this.baseUrl = String.format("https://%s:%d/api/rest", host, port);

    try {
        // Set up auth handling
        CredentialsProvider credsProvider = new BasicCredentialsProvider();
        credsProvider.setCredentials(new AuthScope(host, port),
                new UsernamePasswordCredentials(user, password));
        AuthCache authCache = new BasicAuthCache();
        BasicScheme basicAuth = new BasicScheme();
        HttpHost target = new HttpHost(host, port, "https");
        authCache.put(target, basicAuth);

        // Set up our context
        httpContext = HttpClientContext.create();
        httpContext.setCookieStore(new BasicCookieStore());
        httpContext.setAuthCache(authCache);

        // Create our HTTPS client
        SSLContext sslContext = SSLContexts.custom().loadTrustMaterial(null, new TrustStrategy() {
            @Override
            public boolean isTrusted(X509Certificate[] arg0, String arg1) throws CertificateException {
                return true;
            }
        }).build();

        SSLConnectionSocketFactory sslSocketFactory = new SSLConnectionSocketFactory(sslContext,
                SSLConnectionSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER);

        this.httpClient = HttpClients.custom().setHostnameVerifier(new AllowAllHostnameVerifier())
                .setDefaultCredentialsProvider(credsProvider).setSSLSocketFactory(sslSocketFactory).build();
    } catch (NoSuchAlgorithmException | KeyStoreException | KeyManagementException e) {
        // Hopefully default SSL handling is set up
        LOG.warn("Failed to configure HTTP handling, falling back to default handler.");
        LOG.debug("Config error: {}", e);
        this.httpClient = HttpClients.createDefault();
    }
}

From source file:org.wso2.bps.integration.tests.bpmn.BPMNTestUtils.java

/**
 * Returns HTTP GET response entity string from given url using admin credentials
 *
 * @param url request url suffix/*from w w w. jav a2s  .co  m*/
 * @return HttpResponse from get request
 */
public static String getRequest(String url) throws IOException {

    String restUrl = getRestEndPoint(url);
    log.info("Sending HTTP GET request: " + restUrl);
    client = new DefaultHttpClient();
    request = new HttpGet(restUrl);

    request.addHeader(BasicScheme.authenticate(new UsernamePasswordCredentials("admin", "admin"),
            Charset.defaultCharset().toString(), false));
    client.getConnectionManager().closeExpiredConnections();
    HttpResponse response = client.execute(request);
    return EntityUtils.toString(response.getEntity());
}

From source file:com.villemos.ispace.httpcrawler.HttpClientConfigurer.java

public static HttpClient setupClient(boolean ignoreAuthenticationFailure, String domain, Integer port,
        String proxyHost, Integer proxyPort, String authUser, String authPassword, CookieStore cookieStore)
        throws NoSuchAlgorithmException, KeyManagementException {

    DefaultHttpClient client = null;/*from  ww w .  j a  v  a  2  s  . c o  m*/

    /** Always ignore authentication protocol errors. */
    if (ignoreAuthenticationFailure) {
        SSLContext sslContext = SSLContext.getInstance("SSL");

        // set up a TrustManager that trusts everything
        sslContext.init(null, new TrustManager[] { new EasyX509TrustManager() }, new SecureRandom());

        SchemeRegistry schemeRegistry = new SchemeRegistry();

        SSLSocketFactory sf = new SSLSocketFactory(sslContext);
        Scheme httpsScheme = new Scheme("https", sf, 443);
        schemeRegistry.register(httpsScheme);

        SocketFactory sfa = new PlainSocketFactory();
        Scheme httpScheme = new Scheme("http", sfa, 80);
        schemeRegistry.register(httpScheme);

        HttpParams params = new BasicHttpParams();
        ClientConnectionManager cm = new SingleClientConnManager(params, schemeRegistry);

        client = new DefaultHttpClient(cm, params);
    } else {
        client = new DefaultHttpClient();
    }

    if (proxyHost != null && proxyPort != null) {
        HttpHost proxy = new HttpHost(proxyHost, proxyPort);
        client.getParams().setParameter(ConnRoutePNames.DEFAULT_PROXY, proxy);
    } else {
        ProxySelectorRoutePlanner routePlanner = new ProxySelectorRoutePlanner(
                client.getConnectionManager().getSchemeRegistry(), ProxySelector.getDefault());
        client.setRoutePlanner(routePlanner);
    }

    /** The target location may demand authentication. We setup preemptive authentication. */
    if (authUser != null && authPassword != null) {
        client.getCredentialsProvider().setCredentials(new AuthScope(domain, port),
                new UsernamePasswordCredentials(authUser, authPassword));
    }

    /** Set default cookie policy and store. Can be overridden for a specific method using for example;
     *    method.getParams().setParameter(ClientPNames.COOKIE_POLICY, CookiePolicy.BROWSER_COMPATIBILITY); 
     */
    client.setCookieStore(cookieStore);
    // client.getParams().setParameter(ClientPNames.COOKIE_POLICY, CookiePolicy.RFC_2965);      
    client.getParams().setParameter(ClientPNames.COOKIE_POLICY, CookiePolicy.BEST_MATCH);

    return client;
}

From source file:org.opennms.minion.core.impl.ScvEnabledRestClientImpl.java

@Override
public void ping() throws Exception {
    // Setup a client with pre-emptive authentication
    HttpHost target = new HttpHost(url.getHost(), url.getPort(), url.getProtocol());
    CredentialsProvider credsProvider = new BasicCredentialsProvider();
    credsProvider.setCredentials(new AuthScope(target.getHostName(), target.getPort()),
            new UsernamePasswordCredentials(username, password));
    CloseableHttpClient httpclient = HttpClients.custom().setDefaultCredentialsProvider(credsProvider).build();
    try {//ww w.  j a va2  s. c o m
        AuthCache authCache = new BasicAuthCache();
        BasicScheme basicAuth = new BasicScheme();
        authCache.put(target, basicAuth);

        HttpClientContext localContext = HttpClientContext.create();
        localContext.setAuthCache(authCache);

        // Issue a simple GET against the Info endpoint
        HttpGet httpget = new HttpGet(url.toExternalForm() + "/rest/info");
        CloseableHttpResponse response = httpclient.execute(target, httpget, localContext);
        response.close();
    } finally {
        httpclient.close();
    }
}

From source file:com.adobe.ags.curly.controller.AuthHandler.java

private CredentialsProvider getCredentialsProvider() {
    CredentialsProvider creds = new BasicCredentialsProvider();
    creds.setCredentials(AuthScope.ANY,/*from   w w  w  . j av  a  2s.  co m*/
            new UsernamePasswordCredentials(model.userNameProperty().get(), model.passwordProperty().get()));
    return creds;
}

From source file:org.eclipse.lyo.testsuite.server.oslcv1tests.OAuthTests.java

@Before
public void setup() {
    Properties setupProps = SetupProperties.setup(null);
    if (setupProps.getProperty("testBackwardsCompatability") != null
            && Boolean.parseBoolean(setupProps.getProperty("testBackwardsCompatability"))) {
        setupProps = SetupProperties.setup(setupProps.getProperty("version1Properties"));
    }/*w  ww  .  j  a  va  2 s  . c om*/
    baseUrl = setupProps.getProperty("baseUri");
    String userId = setupProps.getProperty("userId");
    String password = setupProps.getProperty("pw");
    basicCreds = new UsernamePasswordCredentials(userId, password);
    postParameters = setupProps.getProperty("OAuthAuthorizationParameters");
    String requestUrl = setupProps.getProperty("OAuthRequestTokenUrl");
    String authorizeUrl = setupProps.getProperty("OAuthAuthorizationUrl");
    String accessUrl = setupProps.getProperty("OAuthAccessTokenUrl");
    //Setup the OAuth provider
    provider = new OAuthServiceProvider(requestUrl, authorizeUrl, accessUrl);
    //Setup the OAuth consumer
    String consumerSecret = setupProps.getProperty("OAuthConsumerSecret");
    String consumerToken = setupProps.getProperty("OAuthConsumerToken");
    consumer = new OAuthConsumer("", consumerToken, consumerSecret, provider);
}

From source file:org.graylog2.bindings.providers.JestClientProvider.java

@Inject
public JestClientProvider(@Named("elasticsearch_hosts") List<URI> elasticsearchHosts,
        @Named("elasticsearch_connect_timeout") Duration elasticsearchConnectTimeout,
        @Named("elasticsearch_socket_timeout") Duration elasticsearchSocketTimeout,
        @Named("elasticsearch_idle_timeout") Duration elasticsearchIdleTimeout,
        @Named("elasticsearch_max_total_connections") int elasticsearchMaxTotalConnections,
        @Named("elasticsearch_max_total_connections_per_route") int elasticsearchMaxTotalConnectionsPerRoute,
        @Named("elasticsearch_discovery_enabled") boolean discoveryEnabled,
        @Named("elasticsearch_discovery_filter") @Nullable String discoveryFilter,
        @Named("elasticsearch_discovery_frequency") Duration discoveryFrequency, Gson gson) {
    this.factory = new JestClientFactory();
    this.credentialsProvider = new BasicCredentialsProvider();
    final List<String> hosts = elasticsearchHosts.stream().map(hostUri -> {
        if (!Strings.isNullOrEmpty(hostUri.getUserInfo())) {
            final Iterator<String> splittedUserInfo = Splitter.on(":").split(hostUri.getUserInfo()).iterator();
            if (splittedUserInfo.hasNext()) {
                final String username = splittedUserInfo.next();
                final String password = splittedUserInfo.hasNext() ? splittedUserInfo.next() : null;
                credentialsProvider//from w ww .jav a 2s . co m
                        .setCredentials(
                                new AuthScope(hostUri.getHost(), hostUri.getPort(), AuthScope.ANY_REALM,
                                        hostUri.getScheme()),
                                new UsernamePasswordCredentials(username, password));
            }
        }
        return hostUri.toString();
    }).collect(Collectors.toList());

    final HttpClientConfig.Builder httpClientConfigBuilder = new HttpClientConfig.Builder(hosts)
            .credentialsProvider(credentialsProvider)
            .connTimeout(Math.toIntExact(elasticsearchConnectTimeout.toMillis()))
            .readTimeout(Math.toIntExact(elasticsearchSocketTimeout.toMillis()))
            .maxConnectionIdleTime(elasticsearchIdleTimeout.getSeconds(), TimeUnit.SECONDS)
            .maxTotalConnection(elasticsearchMaxTotalConnections)
            .defaultMaxTotalConnectionPerRoute(elasticsearchMaxTotalConnectionsPerRoute).multiThreaded(true)
            .discoveryEnabled(discoveryEnabled).discoveryFilter(discoveryFilter)
            .discoveryFrequency(discoveryFrequency.getSeconds(), TimeUnit.SECONDS).gson(gson);

    factory.setHttpClientConfig(httpClientConfigBuilder.build());
}