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.apache.cloudstack.cloudian.client.CloudianClient.java

public CloudianClient(final String host, final Integer port, final String scheme, final String username,
        final String password, final boolean validateSSlCertificate, final int timeout)
        throws KeyStoreException, NoSuchAlgorithmException, KeyManagementException {
    final CredentialsProvider provider = new BasicCredentialsProvider();
    provider.setCredentials(AuthScope.ANY, new UsernamePasswordCredentials(username, password));
    final HttpHost adminHost = new HttpHost(host, port, scheme);
    final AuthCache authCache = new BasicAuthCache();
    authCache.put(adminHost, new BasicScheme());

    this.adminApiUrl = adminHost.toURI();
    this.httpContext = HttpClientContext.create();
    this.httpContext.setCredentialsProvider(provider);
    this.httpContext.setAuthCache(authCache);

    final RequestConfig config = RequestConfig.custom().setConnectTimeout(timeout * 1000)
            .setConnectionRequestTimeout(timeout * 1000).setSocketTimeout(timeout * 1000).build();

    if (!validateSSlCertificate) {
        final SSLContext sslcontext = SSLUtils.getSSLContext();
        sslcontext.init(null, new X509TrustManager[] { new TrustAllManager() }, new SecureRandom());
        final SSLConnectionSocketFactory factory = new SSLConnectionSocketFactory(sslcontext,
                NoopHostnameVerifier.INSTANCE);
        this.httpClient = HttpClientBuilder.create().setDefaultCredentialsProvider(provider)
                .setDefaultRequestConfig(config).setSSLSocketFactory(factory).build();
    } else {//  w w w.j ava2s  .  c o  m
        this.httpClient = HttpClientBuilder.create().setDefaultCredentialsProvider(provider)
                .setDefaultRequestConfig(config).build();
    }
}

From source file:org.apache.metamodel.elasticsearch.rest.ElasticSearchRestDataContextFactory.java

private ElasticSearchRestClient createClient(final DataContextProperties properties)
        throws MalformedURLException {
    final URL url = new URL(properties.getUrl());
    final RestClientBuilder builder = RestClient.builder(new HttpHost(url.getHost(), url.getPort()));

    if (properties.getUsername() != null) {
        final CredentialsProvider credentialsProvider = new BasicCredentialsProvider();
        credentialsProvider.setCredentials(AuthScope.ANY,
                new UsernamePasswordCredentials(properties.getUsername(), properties.getPassword()));

        builder.setHttpClientConfigCallback(
                httpClientBuilder -> httpClientBuilder.setDefaultCredentialsProvider(credentialsProvider));
    }//  w  w w  .  j a va 2 s.co m

    return new ElasticSearchRestClient(builder.build());
}

From source file:io.bosh.client.SpringDirectorClientBuilder.java

private ClientHttpRequestFactory createRequestFactory(String host, String username, String password) {
    CredentialsProvider credentialsProvider = new BasicCredentialsProvider();
    credentialsProvider.setCredentials(new AuthScope(host, 25555),
            new UsernamePasswordCredentials(username, password));

    SSLContext sslContext = null;
    try {//from   w  w  w.ja  va  2  s  . c o m
        sslContext = SSLContexts.custom().loadTrustMaterial(null, new TrustSelfSignedStrategy()).useTLS()
                .build();
    } catch (KeyManagementException | NoSuchAlgorithmException | KeyStoreException e) {
        throw new DirectorException("Unable to configure ClientHttpRequestFactory", e);
    }

    SSLConnectionSocketFactory connectionFactory = new SSLConnectionSocketFactory(sslContext,
            new AllowAllHostnameVerifier());

    // disabling redirect handling is critical for the way BOSH uses 302's
    HttpClient httpClient = HttpClientBuilder.create().disableRedirectHandling()
            .setDefaultCredentialsProvider(credentialsProvider).setSSLSocketFactory(connectionFactory).build();

    return new HttpComponentsClientHttpRequestFactory(httpClient);
}

From source file:com.samebug.clients.search.api.client.RawClient.java

RawClient(@NotNull final Config config) {
    HttpClientBuilder httpBuilder = HttpClientBuilder.create();
    requestConfigBuilder = RequestConfig.custom();
    CredentialsProvider provider = new BasicCredentialsProvider();

    requestConfigBuilder.setConnectTimeout(config.connectTimeout).setSocketTimeout(config.requestTimeout)
            .setConnectionRequestTimeout(500);
    try {//from  w  w  w  .  jav a  2 s.c  o  m
        IdeHttpClientHelpers.ApacheHttpClient4.setProxyForUrlIfEnabled(requestConfigBuilder, config.serverRoot);
        IdeHttpClientHelpers.ApacheHttpClient4.setProxyCredentialsForUrlIfEnabled(provider, config.serverRoot);
    } catch (Throwable e) {
        // fallback to traditional proxy config for backward compatiblity
        try {
            final HttpConfigurable proxySettings = HttpConfigurable.getInstance();
            final ProxyCredentialsFacade facade = new ProxyCredentialsFacade(proxySettings);
            if (proxySettings != null && proxySettings.USE_HTTP_PROXY
                    && !StringUtil.isEmptyOrSpaces(proxySettings.PROXY_HOST)) {
                requestConfigBuilder.setProxy(new HttpHost(proxySettings.PROXY_HOST, proxySettings.PROXY_PORT));
                if (proxySettings.PROXY_AUTHENTICATION) {
                    provider.setCredentials(AuthScope.ANY,
                            new UsernamePasswordCredentials(facade.getLogin(), facade.getPassword()));
                }
            }
        } catch (Throwable ignored) {
            // if even that fails, we cannot do more
        }
    }
    defaultRequestConfig = requestConfigBuilder.build();
    trackingConfig = requestConfigBuilder.setSocketTimeout(TrackingRequestTimeout_Millis).build();
    List<BasicHeader> defaultHeaders = new ArrayList<BasicHeader>();
    defaultHeaders.add(new BasicHeader("User-Agent", USER_AGENT));
    if (config.apiKey != null)
        defaultHeaders.add(new BasicHeader("X-Samebug-ApiKey", config.apiKey));
    if (config.workspaceId != null)
        defaultHeaders.add(new BasicHeader("X-Samebug-WorkspaceId", config.workspaceId.toString()));

    httpClient = httpBuilder.setDefaultRequestConfig(defaultRequestConfig).setMaxConnTotal(MaxConnections)
            .setMaxConnPerRoute(MaxConnections).setDefaultCredentialsProvider(provider)
            .setDefaultHeaders(defaultHeaders).build();
    if (config.isApacheLoggingEnabled)
        enableApacheLogging();
}

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

public static Collection<Object[]> getReferencedCatalogUrls(String base)
        throws IOException, ParserConfigurationException, SAXException, XPathException {
    Properties setupProps = SetupProperties.setup(null);
    String userId = setupProps.getProperty("userId");
    String pw = setupProps.getProperty("pw");

    HttpResponse resp = OSLCUtils.getResponseFromUrl(base, base, new UsernamePasswordCredentials(userId, pw),
            OSLCConstants.CT_DISC_CAT_XML);
    //If we're not looking at a catalog, return empty list.
    if (!resp.getEntity().getContentType().getValue().contains(OSLCConstants.CT_DISC_CAT_XML)) {
        System.out.println("The url: " + base + " does not refer to a ServiceProviderCatalog.");
        System.out.println(//  w w  w .ja v  a2s. c  o  m
                "The content-type of a ServiceProviderCatalog should be " + OSLCConstants.CT_DISC_CAT_XML);
        System.out.println("The content-type returned was " + resp.getEntity().getContentType());
        EntityUtils.consume(resp.getEntity());
        return new ArrayList<Object[]>();
    }
    Document baseDoc = OSLCUtils.createXMLDocFromResponseBody(EntityUtils.toString(resp.getEntity()));

    //ArrayList to contain the urls from all SPCs
    Collection<Object[]> data = new ArrayList<Object[]>();
    data.add(new Object[] { base });

    //Get all ServiceProviderCatalog urls from the base document in order to test them as well,
    //recursively checking them for other ServiceProviderCatalogs further down.
    NodeList spcs = (NodeList) OSLCUtils.getXPath().evaluate(
            "//oslc_disc:entry/oslc_disc:ServiceProviderCatalog/@rdf:about", baseDoc, XPathConstants.NODESET);
    for (int i = 0; i < spcs.getLength(); i++) {
        String uri = spcs.item(i).getNodeValue();
        uri = OSLCUtils.absoluteUrlFromRelative(base, uri);
        if (!uri.equals(base)) {
            Collection<Object[]> subCollection = getReferencedCatalogUrls(uri);
            Iterator<Object[]> iter = subCollection.iterator();
            while (iter.hasNext()) {
                data.add(iter.next());
            }
        }
    }
    return data;
}

From source file:net.bioclipse.dbxp.business.DbxpManager.java

public static HttpResponse postValues(HashMap<String, String> postvars, String url)
        throws NoSuchAlgorithmException, ClientProtocolException, IOException {
    DefaultHttpClient httpclient = new DefaultHttpClient();
    httpclient.getCredentialsProvider().setCredentials(new AuthScope(AuthScope.ANY_HOST, AuthScope.ANY_PORT),
            new UsernamePasswordCredentials(userName, password));

    List<NameValuePair> formparams = new ArrayList<NameValuePair>();
    Iterator<Entry<String, String>> it = postvars.entrySet().iterator();
    while (it.hasNext()) {
        Map.Entry<String, String> next = (Map.Entry<String, String>) it.next();
        Map.Entry<String, String> pairs = next;
        formparams.add(new BasicNameValuePair(pairs.getKey(), pairs.getValue()));
    }//w w  w  . j  av a  2  s.  co m
    UrlEncodedFormEntity entity = new UrlEncodedFormEntity(formparams, "UTF-8");
    HttpPost httppost = new HttpPost(url);
    httppost.setEntity(entity);
    HttpContext localContext = new BasicHttpContext();
    return httpclient.execute(httppost, localContext);
}

From source file:com.jaeksoft.searchlib.crawler.web.spider.ProxyHandler.java

public void check(RequestConfig.Builder configBuilder, URI uri, CredentialsProvider credentialsProvider) {
    if (proxy == null || uri == null)
        return;/* ww w  .  ja  v  a2s . c o m*/
    if (exclusionSet.contains(uri.getHost()))
        return;
    configBuilder.setProxy(proxy);
    if (!StringUtils.isEmpty(username))
        credentialsProvider.setCredentials(new AuthScope(proxy),
                new UsernamePasswordCredentials(username, password));
}

From source file:com.twotoasters.android.hoot.HootTransportHttpClient.java

@Override
public void setup(Hoot hoot) {
    HttpParams params = new BasicHttpParams();
    ConnManagerParams.setMaxTotalConnections(params, 10);
    ConnManagerParams.setTimeout(params, hoot.getTimeout());
    HttpProtocolParams.setVersion(params, HttpVersion.HTTP_1_1);
    HttpConnectionParams.setConnectionTimeout(params, hoot.getTimeout());
    HttpConnectionParams.setSoTimeout(params, hoot.getTimeout());
    HttpConnectionParams.setTcpNoDelay(params, true);

    SchemeRegistry schemeRegistry = new SchemeRegistry();
    schemeRegistry.register(new Scheme("http", PlainSocketFactory.getSocketFactory(), 80));
    SSLSocketFactory sslSocketFactory = SSLSocketFactory.getSocketFactory();
    sslSocketFactory.setHostnameVerifier(hoot.getSSLHostNameVerifier());
    schemeRegistry.register(new Scheme("https", sslSocketFactory, 443));

    ClientConnectionManager cm = new ThreadSafeClientConnManager(params, schemeRegistry);
    mClient = new DefaultHttpClient(cm, params);
    if (hoot.isBasicAuth()) {
        mClient.getCredentialsProvider().setCredentials(AuthScope.ANY,
                new UsernamePasswordCredentials(hoot.getBasicAuthUsername(), hoot.getBasicAuthPassword()));
    }/*from   w  ww.  j a  va 2  s  .c o  m*/
}

From source file:org.jboss.as.test.integration.web.security.basic.WebSecurityBASICTestCase.java

@Override
protected void makeCall(String user, String pass, int expectedStatusCode) throws Exception {
    DefaultHttpClient httpclient = new DefaultHttpClient();
    try {// w w  w . j ava 2s.c o m
        httpclient.getCredentialsProvider().setCredentials(new AuthScope(url.getHost(), url.getPort()),
                new UsernamePasswordCredentials(user, pass));

        HttpGet httpget = new HttpGet(url.toExternalForm() + "secured/");

        System.out.println("executing request" + httpget.getRequestLine());
        HttpResponse response = httpclient.execute(httpget);
        HttpEntity entity = response.getEntity();

        System.out.println("----------------------------------------");
        StatusLine statusLine = response.getStatusLine();
        System.out.println(statusLine);
        if (entity != null) {
            System.out.println("Response content length: " + entity.getContentLength());
        }
        assertEquals(expectedStatusCode, statusLine.getStatusCode());
        EntityUtils.consume(entity);
    } finally {
        // When HttpClient instance is no longer needed,
        // shut down the connection manager to ensure
        // immediate deallocation of all system resources
        httpclient.getConnectionManager().shutdown();
    }
}

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

@Before
public void setup() throws IOException, ParserConfigurationException, SAXException, XPathException {
    Properties setupProps = SetupProperties.setup(null);
    if (setupProps.getProperty("testBackwardsCompatability") != null
            && Boolean.parseBoolean(setupProps.getProperty("testBackwardsCompatability"))) {
        setupProps = SetupProperties.setup(setupProps.getProperty("version1Properties"));
    }//from  ww w  .j a va  2s.c om
    String userId = setupProps.getProperty("userId");
    String pw = setupProps.getProperty("pw");
    basicCreds = new UsernamePasswordCredentials(userId, pw);
    templatedDocument = OSLCUtils.readFileAsString(new File(setupProps.getProperty("createTemplateXmlFile")));
    updateDocument = OSLCUtils.readFileAsString(new File(setupProps.getProperty("updateTemplateXmlFile")));
    jsonDocument = OSLCUtils.readFileAsString(new File(setupProps.getProperty("createTemplateJsonFile")));
    jsonUpdate = OSLCUtils.readFileAsString(new File(setupProps.getProperty("updateTemplateJsonFile")));
}