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:sk.datalan.solr.impl.HttpClientUtil.java

public static HttpClientBuilder configureClient(final HttpClientConfiguration config) {
    HttpClientBuilder clientBuilder = HttpClientBuilder.create();

    // max total connections
    if (config.isSetMaxConnections()) {
        clientBuilder.setMaxConnTotal(config.getMaxConnections());
    }/*from www.ja  v  a 2  s  .c om*/

    // max connections per route
    if (config.isSetMaxConnectionsPerRoute()) {
        clientBuilder.setMaxConnPerRoute(config.getMaxConnectionsPerRoute());
    }

    RequestConfig.Builder requestConfigBuilder = RequestConfig.custom().setCookieSpec(CookieSpecs.BEST_MATCH)
            .setExpectContinueEnabled(true).setStaleConnectionCheckEnabled(true);

    // connection timeout
    if (config.isSetConnectionTimeout()) {
        requestConfigBuilder.setConnectTimeout(config.getConnectionTimeout());
    }

    // soucket timeout
    if (config.isSetSocketTimeout()) {
        requestConfigBuilder.setSocketTimeout(config.getSocketTimeout());
    }

    // soucket timeout
    if (config.isSetFollowRedirects()) {
        requestConfigBuilder.setRedirectsEnabled(config.getFollowRedirects());
    }
    clientBuilder.setDefaultRequestConfig(requestConfigBuilder.build());

    if (config.isSetUseRetry()) {
        if (config.getUseRetry()) {
            clientBuilder.setRetryHandler(new DefaultHttpRequestRetryHandler());
        } else {
            clientBuilder.setRetryHandler(NO_RETRY);
        }
    }

    // basic authentication
    if (config.isSetBasicAuthUsername() && config.isSetBasicAuthPassword()) {
        CredentialsProvider credsProvider = new BasicCredentialsProvider();
        credsProvider.setCredentials(AuthScope.ANY,
                new UsernamePasswordCredentials(config.getBasicAuthUsername(), config.getBasicAuthPassword()));
    }

    if (config.isSetAllowCompression()) {
        clientBuilder.addInterceptorFirst(new UseCompressionRequestInterceptor());
        clientBuilder.addInterceptorFirst(new UseCompressionResponseInterceptor());
    }

    // SSL context for secure connections can be created either based on
    // system or application specific properties.
    SSLContext sslcontext = SSLContexts.createSystemDefault();
    // Use custom hostname verifier to customize SSL hostname verification.
    X509HostnameVerifier hostnameVerifier = new BrowserCompatHostnameVerifier();

    // Create a registry of custom connection socket factories for supported
    // protocol schemes.
    Registry<ConnectionSocketFactory> socketFactoryRegistry = RegistryBuilder.<ConnectionSocketFactory>create()
            .register("http", PlainConnectionSocketFactory.INSTANCE)
            .register("https", new SSLConnectionSocketFactory(sslcontext, hostnameVerifier)).build();

    clientBuilder.setConnectionManager(new PoolingHttpClientConnectionManager(socketFactoryRegistry));

    return clientBuilder;
}

From source file:org.kitodo.data.elasticsearch.KitodoRestClient.java

/**
 * Create REST client with basic authentication.
 * //from   w ww  .  j  a  v a 2  s.  c  om
 * @param host
 *            default host is localhost
 * @param port
 *            default port ist 9200
 * @param protocol
 *            default protocol is http
 */
private void initiateClientWithAuth(String host, Integer port, String protocol) {
    String user = ConfigMain.getParameter("elasticsearch.user", "elastic");
    String password = ConfigMain.getParameter("elasticsearch.password", "changeme");

    final CredentialsProvider credentialsProvider = new BasicCredentialsProvider();
    credentialsProvider.setCredentials(AuthScope.ANY, new UsernamePasswordCredentials(user, password));

    client = RestClient.builder(new HttpHost(host, port, protocol))
            .setHttpClientConfigCallback(
                    httpClientBuilder -> httpClientBuilder.setDefaultCredentialsProvider(credentialsProvider))
            .build();
    highLevelClient = new RestHighLevelClient(client);
}

From source file:org.droidparts.http.worker.HttpClientWorker.java

@Override
protected void setProxy(String protocol, String host, int port, String user, String password) {
    HttpHost proxyHost = new HttpHost(host, port, protocol);
    httpClient.getParams().setParameter(DEFAULT_PROXY, proxyHost);
    if (isNotEmpty(user) && isNotEmpty(password)) {
        AuthScope authScope = new AuthScope(host, port);
        UsernamePasswordCredentials credentials = new UsernamePasswordCredentials(user, password);
        httpClient.getCredentialsProvider().setCredentials(authScope, credentials);
    }//  ww w  .j a v a2 s  .  c o m
}

From source file:com.marand.thinkmed.medications.connector.impl.rest.RestMedicationsConnector.java

@Override
public void afterPropertiesSet() throws Exception {
    final HttpClientContext context = HttpClientContext.create();
    final BasicCredentialsProvider credentialsProvider = new BasicCredentialsProvider();
    credentialsProvider.setCredentials(new AuthScope(host, port),
            new UsernamePasswordCredentials(username, password));
    context.setCredentialsProvider(credentialsProvider);

    final ResteasyClient client = new ResteasyClientBuilder().httpEngine(new ApacheHttpClient4Engine(
            HttpClientBuilder.create().setConnectionManager(new PoolingHttpClientConnectionManager()).build(),
            context)).build();/*  ww w . j  a  va2  s.c  o m*/
    final ResteasyWebTarget target = client.target(restUri);
    restClient = target.proxy(MedicationsConnectorRestClient.class);
}

From source file:org.casquesrouges.missing.HttpAdapter.java

@Override
public void run() {
    handler.sendMessage(Message.obtain(handler, HttpAdapter.START));
    httpClient = new DefaultHttpClient();

    httpClient.getCredentialsProvider().setCredentials(new AuthScope(null, 80),
            new UsernamePasswordCredentials(login, pass));

    HttpConnectionParams.setSoTimeout(httpClient.getParams(), 25000);
    try {// ww  w .j  a va2s.c  om
        HttpResponse response = null;
        switch (method) {
        case GET:
            response = httpClient.execute(new HttpGet(url));
            break;
        case POST:
            HttpPost httpPost = new HttpPost(url);
            httpPost.setEntity(new UrlEncodedFormEntity(data));
            response = httpClient.execute(httpPost);
            break;
        case FILE:
            File input = new File(picFile);

            HttpPost post = new HttpPost(url);
            MultipartEntity multi = new MultipartEntity(HttpMultipartMode.BROWSER_COMPATIBLE);

            multi.addPart("person_id", new StringBody(Integer.toString(personID)));
            multi.addPart("creator_id", new StringBody(creator_id));
            multi.addPart("file", new FileBody(input));
            post.setEntity(multi);

            Log.d("MISSING", "http FILE: " + url + " pic: " + picFile);

            response = httpClient.execute(post);

            break;
        }

        processEntity(response);

    } catch (Exception e) {
        handler.sendMessage(Message.obtain(handler, HttpAdapter.ERROR, e));
    }
    ConnectionManager.getInstance().didComplete(this);
}

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

public static Collection<Object[]> getReferencedUrls(String base)
        throws IOException, XPathException, ParserConfigurationException, SAXException {
    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 + ", " + OSLCConstants.CT_DISC_DESC_XML);

    //If our 'base' is a ServiceDescription we don't need to recurse as this is the only one we can find
    if (resp.getEntity().getContentType().getValue().contains(OSLCConstants.CT_DISC_DESC_XML)) {
        Collection<Object[]> data = new ArrayList<Object[]>();
        data.add(new Object[] { base });
        EntityUtils.consume(resp.getEntity());
        return data;
    }//  www .  j  a va  2 s  .  c o m

    Document baseDoc = OSLCUtils.createXMLDocFromResponseBody(EntityUtils.toString(resp.getEntity()));

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

    //Get all the ServiceDescriptionDocuments from this ServiceProviderCatalog
    NodeList sDescs = (NodeList) OSLCUtils.getXPath().evaluate("//oslc_disc:services/@rdf:resource", baseDoc,
            XPathConstants.NODESET);
    for (int i = 0; i < sDescs.getLength(); i++) {
        String uri = sDescs.item(i).getNodeValue();
        uri = OSLCUtils.absoluteUrlFromRelative(base, uri);
        data.add(new Object[] { uri });
    }

    //Get all ServiceProviderCatalog urls from the base document in order to recursively add all the
    //description documents from them as well.
    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 = getReferencedUrls(uri);
            Iterator<Object[]> iter = subCollection.iterator();
            while (iter.hasNext()) {
                data.add(iter.next());
            }
        }
    }
    return data;
}

From source file:com.fujitsu.dc.client.http.RestAdapter.java

/**
 * This is the parameterized constructor to initialize various fields.
 * @param as Accessor/* ww  w  .  ja v a 2s  .c  o  m*/
 */
public RestAdapter(Accessor as) {
    this.accessor = as;
    DaoConfig config = accessor.getDaoConfig();
    httpClient = config.getHttpClient();
    if (httpClient == null) {
        httpClient = HttpClientFactory.create(DcContext.getPlatform(), config.getConnectionTimeout());
    }
    String proxyHost = config.getProxyHostname();
    int proxyPort = config.getProxyPort();
    if (proxyHost != null) {
        HttpHost proxy = new HttpHost(proxyHost, proxyPort);
        httpClient.getParams().setParameter(ConnRoutePNames.DEFAULT_PROXY, proxy);
        // ID/Pass??null?????Proxy
        String proxyUsername = config.getProxyUsername();
        String proxyPassword = config.getProxyPassword();
        if (httpClient instanceof AbstractHttpClient && proxyUsername != null && proxyPassword != null) {
            ((AbstractHttpClient) httpClient).getCredentialsProvider().setCredentials(
                    new AuthScope(proxyHost, proxyPort),
                    new UsernamePasswordCredentials(proxyUsername, proxyPassword));
        }
    }
}

From source file:com.cloudhopper.httpclient.util.HttpSender.java

static public Response postXml(String url, String username, String password, String requestXml)
        throws Exception {
    ///*w  w w. j a va 2 s  .  c o m*/
    // trust any SSL connection
    //
    TrustManager easyTrustManager = new X509TrustManager() {
        public void checkClientTrusted(java.security.cert.X509Certificate[] arg0, String arg1)
                throws CertificateException {
            // allow all
        }

        public void checkServerTrusted(java.security.cert.X509Certificate[] arg0, String arg1)
                throws CertificateException {
            // allow all
        }

        public java.security.cert.X509Certificate[] getAcceptedIssuers() {
            return null;
        }
    };

    Scheme http = new Scheme("http", PlainSocketFactory.getSocketFactory(), 80);
    SSLContext sslcontext = SSLContext.getInstance("TLS");
    sslcontext.init(null, new TrustManager[] { easyTrustManager }, null);
    SSLSocketFactory sf = new SSLSocketFactory(sslcontext);
    sf.setHostnameVerifier(SSLSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER);
    Scheme https = new Scheme("https", sf, 443);

    //SchemeRegistry sr = new SchemeRegistry();
    //sr.register(http);
    //sr.register(https);

    // create and initialize scheme registry
    //SchemeRegistry schemeRegistry = new SchemeRegistry();
    //schemeRegistry.register(new Scheme("http", PlainSocketFactory.getSocketFactory(), 80));

    // create an HttpClient with the ThreadSafeClientConnManager.
    // This connection manager must be used if more than one thread will
    // be using the HttpClient.
    //ThreadSafeClientConnManager cm = new ThreadSafeClientConnManager(schemeRegistry);
    //cm.setMaxTotalConnections(1);

    DefaultHttpClient client = new DefaultHttpClient();

    client.getConnectionManager().getSchemeRegistry().register(https);

    HttpPost post = new HttpPost(url);

    StringEntity postEntity = new StringEntity(requestXml, "ISO-8859-1");
    postEntity.setContentType("text/xml; charset=\"ISO-8859-1\"");
    post.addHeader("SOAPAction", "\"\"");
    post.setEntity(postEntity);

    long start = System.currentTimeMillis();

    client.getCredentialsProvider().setCredentials(new AuthScope(null, AuthScope.ANY_PORT),
            new UsernamePasswordCredentials(username, password));

    BasicHttpContext localcontext = new BasicHttpContext();

    // Generate BASIC scheme object and stick it to the local
    // execution context
    BasicScheme basicAuth = new BasicScheme();
    localcontext.setAttribute("preemptive-auth", basicAuth);

    // Add as the first request interceptor
    client.addRequestInterceptor(new PreemptiveAuth(), 0);

    HttpResponse httpResponse = client.execute(post, localcontext);
    HttpEntity responseEntity = httpResponse.getEntity();

    Response rsp = new Response();

    // set the status line and reason
    rsp.statusCode = httpResponse.getStatusLine().getStatusCode();
    rsp.statusLine = httpResponse.getStatusLine().getReasonPhrase();

    // get an input stream
    rsp.body = EntityUtils.toString(responseEntity);

    // When HttpClient instance is no longer needed,
    // shut down the connection manager to ensure
    // immediate deallocation of all system resources
    client.getConnectionManager().shutdown();

    return rsp;
}

From source file:io.personium.client.http.RestAdapter.java

/**
 * This is the parameterized constructor to initialize various fields.
 * @param as Accessor//from  w  w  w .ja va 2  s . c o m
 */
public RestAdapter(Accessor as) {
    this.accessor = as;
    DaoConfig config = accessor.getDaoConfig();
    httpClient = config.getHttpClient();
    if (httpClient == null) {
        httpClient = HttpClientFactory.create(PersoniumContext.getPlatform(), config.getConnectionTimeout());
    }
    String proxyHost = config.getProxyHostname();
    int proxyPort = config.getProxyPort();
    if (proxyHost != null) {
        HttpHost proxy = new HttpHost(proxyHost, proxyPort);
        httpClient.getParams().setParameter(ConnRoutePNames.DEFAULT_PROXY, proxy);
        // ID/Pass??null?????Proxy
        String proxyUsername = config.getProxyUsername();
        String proxyPassword = config.getProxyPassword();
        if (httpClient instanceof AbstractHttpClient && proxyUsername != null && proxyPassword != null) {
            ((AbstractHttpClient) httpClient).getCredentialsProvider().setCredentials(
                    new AuthScope(proxyHost, proxyPort),
                    new UsernamePasswordCredentials(proxyUsername, proxyPassword));
        }
    }
}

From source file:org.qucosa.camel.component.fcrepo3.Fcrepo3APIAccess.java

public Fcrepo3APIAccess(String host, String port, String user, String password) {
    CredentialsProvider credentialsProvider = new BasicCredentialsProvider();
    credentialsProvider.setCredentials(AuthScope.ANY, new UsernamePasswordCredentials(user, password));

    this.host = host;
    this.port = port;

    httpClient = HttpClientBuilder.create().setConnectionManager(new PoolingHttpClientConnectionManager())
            .setDefaultCredentialsProvider(credentialsProvider).build();
}