Example usage for org.apache.http.client CredentialsProvider setCredentials

List of usage examples for org.apache.http.client CredentialsProvider setCredentials

Introduction

In this page you can find the example usage for org.apache.http.client CredentialsProvider setCredentials.

Prototype

void setCredentials(AuthScope authscope, Credentials credentials);

Source Link

Document

Sets the Credentials credentials for the given authentication scope.

Usage

From source file:com.jaspersoft.studio.server.utils.HttpUtils.java

public static void setupProxy(ClientConfig clientConfig, URI uri) {
    CredentialsProvider cp = (CredentialsProvider) clientConfig
            .getProperty(ApacheClientProperties.CREDENTIALS_PROVIDER);
    for (IProxyData d : net.sf.jasperreports.eclipse.util.HttpUtils.proxyService.select(uri)) {
        Credentials c = net.sf.jasperreports.eclipse.util.HttpUtils.getCredentials(d);
        if (c != null)
            cp.setCredentials(new AuthScope(new HttpHost(d.getHost(), d.getPort())), c);
        clientConfig.property(ClientProperties.PROXY_URI,
                d.getType().toLowerCase() + "://" + d.getHost() + ":" + d.getPort());
        break;/* w ww . j  a v a 2 s. c  om*/
    }
    clientConfigs.put(clientConfig, uri);
}

From source file:com.domuslink.communication.ApiHandler.java

/**
 * Pull the raw text content of the given URL. This call blocks until the
 * operation has completed, and is synchronized because it uses a shared
 * buffer {@link #sBuffer}./* w  w  w .  j  av a 2  s .  c o  m*/
 *
 * @param type The type of either a GET or POST for the request
 * @param commandURI The constructed URI for the path
 * @return The raw content returned by the server.
 * @throws ApiException If any connection or server error occurs.
 */
protected static synchronized String urlContent(int type, URI commandURI, ApiCookieHandler cookieHandler)
        throws ApiException {
    HttpResponse response;
    HttpRequestBase request;

    if (sUserAgent == null) {
        throw new ApiException("User-Agent string must be prepared");
    }

    // Create client and set our specific user-agent string
    DefaultHttpClient client = new DefaultHttpClient();
    UsernamePasswordCredentials creds = new UsernamePasswordCredentials("", sPassword);
    CredentialsProvider credsProvider = new BasicCredentialsProvider();
    credsProvider.setCredentials(new AuthScope(AuthScope.ANY_HOST, AuthScope.ANY_PORT), creds);
    client.setCredentialsProvider(credsProvider);
    CookieStore cookieStore = cookieHandler.getCookieStore();
    if (cookieStore != null) {
        boolean expiredCookies = false;
        Date nowTime = new Date();
        for (Cookie theCookie : cookieStore.getCookies()) {
            if (theCookie.isExpired(nowTime))
                expiredCookies = true;
        }
        if (!expiredCookies)
            client.setCookieStore(cookieStore);
        else {
            cookieHandler.setCookieStore(null);
            cookieStore = null;
        }
    }

    try {
        if (type == POST_TYPE)
            request = new HttpPost(commandURI);
        else
            request = new HttpGet(commandURI);

        request.setHeader("User-Agent", sUserAgent);
        response = client.execute(request);

        // Check if server response is valid
        StatusLine status = response.getStatusLine();
        if (status.getStatusCode() != HTTP_STATUS_OK) {
            Log.e(TAG,
                    "urlContent: Url issue: " + commandURI.toString() + " with status: " + status.toString());
            throw new ApiException("Invalid response from server: " + status.toString());
        }

        // Pull content stream from response
        HttpEntity entity = response.getEntity();
        InputStream inputStream = entity.getContent();

        ByteArrayOutputStream content = new ByteArrayOutputStream();

        // Read response into a buffered stream
        int readBytes = 0;
        while ((readBytes = inputStream.read(sBuffer)) != -1) {
            content.write(sBuffer, 0, readBytes);
        }

        if (cookieStore == null) {
            List<Cookie> realCookies = client.getCookieStore().getCookies();
            if (!realCookies.isEmpty()) {
                BasicCookieStore newCookies = new BasicCookieStore();
                for (int i = 0; i < realCookies.size(); i++) {
                    newCookies.addCookie(realCookies.get(i));
                    //                      Log.d(TAG, "aCookie - " + realCookies.get(i).toString());
                }
                cookieHandler.setCookieStore(newCookies);
            }
        }

        // Return result from buffered stream
        return content.toString();
    } catch (IOException e) {
        Log.e(TAG, "urlContent: client execute: " + commandURI.toString());
        throw new ApiException("Problem communicating with API", e);
    } catch (IllegalArgumentException e) {
        Log.e(TAG, "urlContent: client execute: " + commandURI.toString());
        throw new ApiException("Problem communicating with API", e);
    } finally {
        // When HttpClient instance is no longer needed,
        // shut down the connection manager to ensure
        // immediate deallocation of all system resources
        client.getConnectionManager().shutdown();
    }
}

From source file:org.apache.cxf.fediz.integrationtests.HTTPTestUtils.java

public static String sendHttpGetForSAMLSSO(String url, String user, String password, int returnCodeIDP,
        int returnCodeRP, int idpPort) throws Exception {

    CloseableHttpClient httpClient = null;
    try {//from   www. j  a  va 2  s . co m
        CredentialsProvider credsProvider = new BasicCredentialsProvider();
        credsProvider.setCredentials(new AuthScope("localhost", idpPort),
                new UsernamePasswordCredentials(user, password));

        KeyStore trustStore = KeyStore.getInstance(KeyStore.getDefaultType());
        FileInputStream instream = new FileInputStream(new File("./target/test-classes/client.jks"));
        try {
            trustStore.load(instream, "clientpass".toCharArray());
        } finally {
            try {
                instream.close();
            } catch (Exception ex) {
                ex.printStackTrace();
            }
        }

        SSLContextBuilder sslContextBuilder = new SSLContextBuilder();
        sslContextBuilder.loadTrustMaterial(trustStore, new TrustSelfSignedStrategy());
        sslContextBuilder.loadKeyMaterial(trustStore, "clientpass".toCharArray());

        SSLContext sslContext = sslContextBuilder.build();
        SSLConnectionSocketFactory sslSocketFactory = new SSLConnectionSocketFactory(sslContext);

        HttpClientBuilder httpClientBuilder = HttpClientBuilder.create();
        httpClientBuilder.setDefaultCredentialsProvider(credsProvider);
        httpClientBuilder.setSSLSocketFactory(sslSocketFactory);
        httpClientBuilder.setRedirectStrategy(new LaxRedirectStrategy());

        httpClient = httpClientBuilder.build();

        HttpGet httpget = new HttpGet(url);

        HttpResponse response = httpClient.execute(httpget);
        HttpEntity entity = response.getEntity();

        System.out.println(response.getStatusLine());
        if (entity != null) {
            System.out.println("Response content length: " + entity.getContentLength());
        }
        Assert.assertTrue("RP HTTP Response code: " + response.getStatusLine().getStatusCode() + " [Expected: "
                + returnCodeRP + "]", returnCodeRP == response.getStatusLine().getStatusCode());

        return EntityUtils.toString(entity);
    } finally {
        // When HttpClient instance is no longer needed,
        // shut down the connection manager to ensure
        // immediate deallocation of all system resources
        if (httpClient != null) {
            httpClient.close();
        }
    }
}

From source file:com.github.egonw.rrdf.RJenaHelper.java

public static StringMatrix sparqlRemoteNoJena(String endpoint, String queryString, String user, String password)
        throws Exception {
    StringMatrix table = null;//from   w  w w.  ja  va  2 s  .  c o m

    // use Apache for doing the SPARQL query
    DefaultHttpClient httpclient = new DefaultHttpClient();

    // Set credentials on the client
    if (user != null) {
        URL endpointURL = new URL(endpoint);
        CredentialsProvider credsProvider = new BasicCredentialsProvider();
        credsProvider.setCredentials(new AuthScope(endpointURL.getHost(), AuthScope.ANY_PORT),
                new UsernamePasswordCredentials(user, password));
        httpclient.setCredentialsProvider(credsProvider);
    }

    List<NameValuePair> formparams = new ArrayList<NameValuePair>();
    formparams.add(new BasicNameValuePair("query", queryString));
    UrlEncodedFormEntity entity = new UrlEncodedFormEntity(formparams, "UTF-8");
    HttpPost httppost = new HttpPost(endpoint);
    httppost.setEntity(entity);
    HttpResponse response = httpclient.execute(httppost);
    StatusLine statusLine = response.getStatusLine();
    int statusCode = statusLine.getStatusCode();
    if (statusCode != 200)
        throw new HttpException(
                "Expected HTTP 200, but got a " + statusCode + ": " + statusLine.getReasonPhrase());

    HttpEntity responseEntity = response.getEntity();
    InputStream in = responseEntity.getContent();

    // now the Jena part
    ResultSet results = ResultSetFactory.fromXML(in);
    // also use Jena for getting the prefixes...
    Query query = QueryFactory.create(queryString);
    PrefixMapping prefixMap = query.getPrefixMapping();
    table = convertIntoTable(prefixMap, results);

    in.close();
    return table;
}

From source file:com.microsoft.alm.plugin.context.ServerContext.java

protected static ClientConfig getClientConfig(final Type type, final AuthenticationInfo authenticationInfo,
        final boolean includeProxySettings) {
    final Credentials credentials = AuthHelper.getCredentials(type, authenticationInfo);

    final CredentialsProvider credentialsProvider = new BasicCredentialsProvider();
    credentialsProvider.setCredentials(AuthScope.ANY, credentials);

    final ConnectorProvider connectorProvider = new ApacheConnectorProvider();

    final ClientConfig clientConfig = new ClientConfig().connectorProvider(connectorProvider);
    clientConfig.property(ApacheClientProperties.CREDENTIALS_PROVIDER, credentialsProvider);

    clientConfig.property(ApacheClientProperties.PREEMPTIVE_BASIC_AUTHENTICATION, true);
    clientConfig.property(ClientProperties.REQUEST_ENTITY_PROCESSING, RequestEntityProcessing.BUFFERED);

    //Define a local HTTP proxy
    if (includeProxySettings) {
        final String proxyHost;
        if (System.getProperty("proxyHost") != null) {
            proxyHost = System.getProperty("proxyHost");
        } else {/*from w  ww .  j  av a 2 s  .c  om*/
            proxyHost = "127.0.0.1";
        }

        final String proxyPort;
        if (System.getProperty("proxyPort") != null) {
            proxyPort = System.getProperty("proxyPort");
        } else {
            proxyPort = "8888";
        }

        final String proxyUrl = String.format("http://%s:%s", proxyHost, proxyPort);

        clientConfig.property(ClientProperties.PROXY_URI, proxyUrl);
    }

    // if this is a onPrem server and the uri starts with https, we need to setup ssl
    if (isSSLEnabledOnPrem(type, authenticationInfo.getServerUri())) {
        clientConfig.property(ApacheClientProperties.SSL_CONFIG, getSslConfigurator());
    }

    return clientConfig;
}

From source file:org.apache.cxf.fediz.integrationtests.HTTPTestUtils.java

/**
 * Same as sendHttpGet above, except that we return the HttpClient so that it can
 * subsequently be re-used (for e.g. logout)
 *//*  w  w w . j a va2 s.co  m*/
public static CloseableHttpClient sendHttpGetForSignIn(String url, String user, String password,
        int returnCodeIDP, int returnCodeRP, int idpPort) throws Exception {

    CloseableHttpClient httpClient = null;
    CredentialsProvider credsProvider = new BasicCredentialsProvider();
    credsProvider.setCredentials(new AuthScope("localhost", idpPort),
            new UsernamePasswordCredentials(user, password));

    KeyStore trustStore = KeyStore.getInstance(KeyStore.getDefaultType());
    FileInputStream instream = new FileInputStream(new File("./target/test-classes/client.jks"));
    try {
        trustStore.load(instream, "clientpass".toCharArray());
    } finally {
        try {
            instream.close();
        } catch (Exception ex) {
            ex.printStackTrace();
        }
    }

    SSLContextBuilder sslContextBuilder = new SSLContextBuilder();
    sslContextBuilder.loadTrustMaterial(trustStore, new TrustSelfSignedStrategy());
    sslContextBuilder.loadKeyMaterial(trustStore, "clientpass".toCharArray());

    SSLContext sslContext = sslContextBuilder.build();
    SSLConnectionSocketFactory sslSocketFactory = new SSLConnectionSocketFactory(sslContext);

    HttpClientBuilder httpClientBuilder = HttpClientBuilder.create();
    httpClientBuilder.setDefaultCredentialsProvider(credsProvider);
    httpClientBuilder.setSSLSocketFactory(sslSocketFactory);
    httpClientBuilder.setRedirectStrategy(new LaxRedirectStrategy());

    httpClient = httpClientBuilder.build();

    HttpGet httpget = new HttpGet(url);

    HttpResponse response = httpClient.execute(httpget);
    HttpEntity entity = response.getEntity();

    Assert.assertTrue("IDP HTTP Response code: " + response.getStatusLine().getStatusCode() + " [Expected: "
            + returnCodeIDP + "]", returnCodeIDP == response.getStatusLine().getStatusCode());

    if (response.getStatusLine().getStatusCode() != 200) {
        return null;
    }

    //            Redirect to a POST is not supported without user interaction
    //            http://www.ietf.org/rfc/rfc2616.txt
    //            If the 301 status code is received in response to a request other
    //            than GET or HEAD, the user agent MUST NOT automatically redirect the
    //            request unless it can be confirmed by the user, since this might
    //            change the conditions under which the request was issued.

    Source source = new Source(EntityUtils.toString(entity));
    List<NameValuePair> nvps = new ArrayList<NameValuePair>();
    FormFields formFields = source.getFormFields();

    List<Element> forms = source.getAllElements(HTMLElementName.FORM);
    Assert.assertEquals("Only one form expected but got " + forms.size(), 1, forms.size());
    String postUrl = forms.get(0).getAttributeValue("action");

    Assert.assertNotNull("Form field 'wa' not found", formFields.get("wa"));
    Assert.assertNotNull("Form field 'wresult' not found", formFields.get("wresult"));

    for (FormField formField : formFields) {
        if (formField.getUserValueCount() != 0) {
            nvps.add(new BasicNameValuePair(formField.getName(), formField.getValues().get(0)));
        }
    }
    HttpPost httppost = new HttpPost(postUrl);
    httppost.setEntity(new UrlEncodedFormEntity(nvps, Consts.UTF_8));

    response = httpClient.execute(httppost);

    entity = response.getEntity();
    Assert.assertTrue("RP HTTP Response code: " + response.getStatusLine().getStatusCode() + " [Expected: "
            + returnCodeRP + "]", returnCodeRP == response.getStatusLine().getStatusCode());

    String responseStr = EntityUtils.toString(entity);
    Assert.assertTrue("Principal not " + user, responseStr.indexOf("userPrincipal=" + user) > 0);

    return httpClient;
}

From source file:lucee.commons.net.http.httpclient4.HTTPEngine4Impl.java

public static void setNTCredentials(DefaultHttpClient client, String username, String password,
        String workStation, String domain) {
    // set Username and Password
    if (!StringUtil.isEmpty(username, true)) {
        if (password == null)
            password = "";
        CredentialsProvider cp = client.getCredentialsProvider();
        cp.setCredentials(new AuthScope(AuthScope.ANY_HOST, AuthScope.ANY_PORT),
                new NTCredentials(username, password, workStation, domain));
        //httpMethod.setDoAuthentication( true );
    }//from  w  ww  . ja v  a  2s. c o m
}

From source file:lucee.commons.net.http.httpclient4.HTTPEngine4Impl.java

public static BasicHttpContext setCredentials(DefaultHttpClient client, HttpHost httpHost, String username,
        String password, boolean preAuth) {
    // set Username and Password
    if (!StringUtil.isEmpty(username, true)) {
        if (password == null)
            password = "";
        CredentialsProvider cp = client.getCredentialsProvider();
        cp.setCredentials(new AuthScope(AuthScope.ANY_HOST, AuthScope.ANY_PORT),
                new UsernamePasswordCredentials(username, password));

        BasicHttpContext httpContext = new BasicHttpContext();
        if (preAuth) {
            AuthCache authCache = new BasicAuthCache();
            authCache.put(httpHost, new BasicScheme());
            httpContext.setAttribute(ClientContext.AUTH_CACHE, authCache);
        }//from ww w  .j a  v  a  2s .  com
        return httpContext;
    }
    return null;
}

From source file:org.apache.cxf.fediz.integrationtests.HTTPTestUtils.java

public static String sendHttpGet(String url, String user, String password, int returnCodeIDP, int returnCodeRP,
        int idpPort) throws Exception {

    CloseableHttpClient httpClient = null;
    try {//ww  w  .  j a va 2  s.  c o m
        CredentialsProvider credsProvider = new BasicCredentialsProvider();
        credsProvider.setCredentials(new AuthScope("localhost", idpPort),
                new UsernamePasswordCredentials(user, password));

        KeyStore trustStore = KeyStore.getInstance(KeyStore.getDefaultType());
        FileInputStream instream = new FileInputStream(new File("./target/test-classes/client.jks"));
        try {
            trustStore.load(instream, "clientpass".toCharArray());
        } finally {
            try {
                instream.close();
            } catch (Exception ex) {
                ex.printStackTrace();
            }
        }

        SSLContextBuilder sslContextBuilder = new SSLContextBuilder();
        sslContextBuilder.loadTrustMaterial(trustStore, new TrustSelfSignedStrategy());
        sslContextBuilder.loadKeyMaterial(trustStore, "clientpass".toCharArray());

        SSLContext sslContext = sslContextBuilder.build();
        SSLConnectionSocketFactory sslSocketFactory = new SSLConnectionSocketFactory(sslContext);

        HttpClientBuilder httpClientBuilder = HttpClientBuilder.create();
        httpClientBuilder.setDefaultCredentialsProvider(credsProvider);
        httpClientBuilder.setSSLSocketFactory(sslSocketFactory);
        httpClientBuilder.setRedirectStrategy(new LaxRedirectStrategy());

        httpClient = httpClientBuilder.build();

        HttpGet httpget = new HttpGet(url);

        HttpResponse response = httpClient.execute(httpget);
        HttpEntity entity = response.getEntity();

        System.out.println(response.getStatusLine());
        if (entity != null) {
            System.out.println("Response content length: " + entity.getContentLength());
        }
        Assert.assertTrue("IDP HTTP Response code: " + response.getStatusLine().getStatusCode() + " [Expected: "
                + returnCodeIDP + "]", returnCodeIDP == response.getStatusLine().getStatusCode());

        if (response.getStatusLine().getStatusCode() != 200) {
            return null;
        }

        //            Redirect to a POST is not supported without user interaction
        //            http://www.ietf.org/rfc/rfc2616.txt
        //            If the 301 status code is received in response to a request other
        //            than GET or HEAD, the user agent MUST NOT automatically redirect the
        //            request unless it can be confirmed by the user, since this might
        //            change the conditions under which the request was issued.

        Source source = new Source(EntityUtils.toString(entity));
        List<NameValuePair> nvps = new ArrayList<NameValuePair>();
        FormFields formFields = source.getFormFields();

        List<Element> forms = source.getAllElements(HTMLElementName.FORM);
        Assert.assertEquals("Only one form expected but got " + forms.size(), 1, forms.size());
        String postUrl = forms.get(0).getAttributeValue("action");

        Assert.assertNotNull("Form field 'wa' not found", formFields.get("wa"));
        Assert.assertNotNull("Form field 'wresult' not found", formFields.get("wresult"));

        for (FormField formField : formFields) {
            if (formField.getUserValueCount() != 0) {
                nvps.add(new BasicNameValuePair(formField.getName(), formField.getValues().get(0)));
            }
        }
        HttpPost httppost = new HttpPost(postUrl);
        httppost.setEntity(new UrlEncodedFormEntity(nvps, Consts.UTF_8));

        response = httpClient.execute(httppost);

        entity = response.getEntity();
        System.out.println(response.getStatusLine());
        Assert.assertTrue("RP HTTP Response code: " + response.getStatusLine().getStatusCode() + " [Expected: "
                + returnCodeRP + "]", returnCodeRP == response.getStatusLine().getStatusCode());

        if (entity != null) {
            System.out.println("Response content length: " + entity.getContentLength());
        }

        return EntityUtils.toString(entity);
    } finally {
        // When HttpClient instance is no longer needed,
        // shut down the connection manager to ensure
        // immediate deallocation of all system resources
        if (httpClient != null) {
            httpClient.close();
        }
    }
}

From source file:org.apache.solr.client.solrj.impl.HttpClientUtil.java

private static HttpClientBuilder setupBuilder(HttpClientBuilder builder, SolrParams config) {

    Builder requestConfigBuilder = RequestConfig.custom()
            .setRedirectsEnabled(config.getBool(HttpClientUtil.PROP_FOLLOW_REDIRECTS, false))
            .setDecompressionEnabled(false)
            .setConnectTimeout(config.getInt(HttpClientUtil.PROP_CONNECTION_TIMEOUT, DEFAULT_CONNECT_TIMEOUT))
            .setSocketTimeout(config.getInt(HttpClientUtil.PROP_SO_TIMEOUT, DEFAULT_SO_TIMEOUT));

    String cpolicy = cookiePolicy;
    if (cpolicy != null) {
        requestConfigBuilder.setCookieSpec(cpolicy);
    }/*from  w  ww  .  ja  va2s .c  o m*/

    RequestConfig requestConfig = requestConfigBuilder.build();

    HttpClientBuilder retBuilder = builder.setDefaultRequestConfig(requestConfig);

    if (config.getBool(HttpClientUtil.PROP_USE_RETRY, true)) {
        retBuilder = retBuilder.setRetryHandler(new SolrHttpRequestRetryHandler(3));

    } else {
        retBuilder = retBuilder.setRetryHandler(NO_RETRY);
    }

    final String basicAuthUser = config.get(HttpClientUtil.PROP_BASIC_AUTH_USER);
    final String basicAuthPass = config.get(HttpClientUtil.PROP_BASIC_AUTH_PASS);

    if (basicAuthUser != null && basicAuthPass != null) {
        CredentialsProvider credsProvider = new BasicCredentialsProvider();
        credsProvider.setCredentials(AuthScope.ANY,
                new UsernamePasswordCredentials(basicAuthUser, basicAuthPass));
        retBuilder.setDefaultCredentialsProvider(credsProvider);
    }

    if (config.getBool(HttpClientUtil.PROP_ALLOW_COMPRESSION, false)) {
        retBuilder.addInterceptorFirst(new UseCompressionRequestInterceptor());
        retBuilder.addInterceptorFirst(new UseCompressionResponseInterceptor());
    } else {
        retBuilder.disableContentCompression();
    }

    return retBuilder;
}