Example usage for org.apache.http.impl.client BasicCredentialsProvider BasicCredentialsProvider

List of usage examples for org.apache.http.impl.client BasicCredentialsProvider BasicCredentialsProvider

Introduction

In this page you can find the example usage for org.apache.http.impl.client BasicCredentialsProvider BasicCredentialsProvider.

Prototype

public BasicCredentialsProvider() 

Source Link

Document

Default constructor.

Usage

From source file:com.ibm.twitter.TwitterInsights.java

public TweetList getTweetList(String bookTitle, String bookAuthor) {
    TweetList returnedTweets = new TweetList();

    try {/*from   w  w w.  ja  va 2 s .  c o m*/

        CredentialsProvider credentialsProvider = new BasicCredentialsProvider();
        credentialsProvider.setCredentials(new AuthScope(AuthScope.ANY_HOST, AuthScope.ANY_PORT),
                new UsernamePasswordCredentials(usernameTwitter, passwordTwitter));

        CookieStore cookieStore = new BasicCookieStore();
        CookieSpecProvider csf = new CookieSpecProvider() {
            @Override
            public CookieSpec create(HttpContext context) {
                return new DefaultCookieSpec() {
                    @Override
                    public void validate(Cookie cookie, CookieOrigin origin) throws MalformedCookieException {
                        // Allow all cookies
                    }
                };
            }
        };

        RequestConfig requestConfig = RequestConfig.custom().setCookieSpec("easy").setSocketTimeout(10 * 1000)
                .setConnectTimeout(10 * 1000).build();

        CloseableHttpClient httpClient = HttpClientBuilder.create()
                .setDefaultCredentialsProvider(credentialsProvider).setDefaultCookieStore(cookieStore)
                .setDefaultCookieSpecRegistry(RegistryBuilder.<CookieSpecProvider>create()
                        .register(CookieSpecs.DEFAULT, csf).register("easy", csf).build())
                .setDefaultRequestConfig(requestConfig).build();

        URIBuilder builder = new URIBuilder();
        builder.setScheme("https").setHost(baseURLTwitter).setPath("/api/v1/messages/search")
                .setParameter("q", "\"" + bookTitle + "\"" + " AND " + "\"" + bookAuthor + "\"")
                .setParameter("size", "5");
        URI uri = builder.build();
        HttpGet httpGet = new HttpGet(uri);

        httpGet.setHeader("Content-Type", "text/plain");
        HttpResponse httpResponse = httpClient.execute(httpGet);

        if (httpResponse.getStatusLine().getStatusCode() == 200) {
            BufferedReader rd = new BufferedReader(
                    new InputStreamReader(httpResponse.getEntity().getContent(), "UTF-8"));

            // Read all the books from the best seller list
            ObjectMapper mapper = new ObjectMapper();
            returnedTweets = mapper.readValue(rd, TweetList.class);
        }
    } catch (Exception e) {
        logger.error("Twitter error: {}", e.getMessage());
    }

    return returnedTweets;
}

From source file:com.logsniffer.event.publisher.http.HttpPublisher.java

/**
 * Init method for this publisher.//  w  w w  .  ja va2s .c om
 * 
 * @param velocityRenderer
 *            the velocityRenderer to set
 * @param httpClient
 *            http client
 */
protected void init(final VelocityEventRenderer velocityRenderer, final HttpClient httpClient) {
    this.velocityRenderer = velocityRenderer;
    this.httpClient = httpClient;
    if (getHttpAuthentication() != null) {
        CredentialsProvider credsProvider = new BasicCredentialsProvider();
        credsProvider.setCredentials(new AuthScope(AuthScope.ANY_HOST, AuthScope.ANY_PORT),
                new UsernamePasswordCredentials(getHttpAuthentication().getUsername(),
                        getHttpAuthentication().getPassword()));
        // Add AuthCache to the execution context
        HttpClientContext context = HttpClientContext.create();
        context.setCredentialsProvider(credsProvider);
    }
}

From source file:org.activiti.rest.service.api.runtime.SerializableVariablesDiabledTest.java

public void assertResponseStatus(HttpUriRequest request, int expectedStatusCode) {
    CloseableHttpResponse response = null;
    try {//w ww.  j  a v a  2 s. c  o m

        CredentialsProvider provider = new BasicCredentialsProvider();
        UsernamePasswordCredentials credentials = new UsernamePasswordCredentials("kermit", "kermit");
        provider.setCredentials(AuthScope.ANY, credentials);
        HttpClient client = HttpClientBuilder.create().setDefaultCredentialsProvider(provider).build();

        response = (CloseableHttpResponse) client.execute(request);
        int statusCode = response.getStatusLine().getStatusCode();
        Assert.assertEquals(expectedStatusCode, statusCode);

        if (client instanceof CloseableHttpClient) {
            ((CloseableHttpClient) client).close();
        }

        response.close();

    } catch (ClientProtocolException e) {
        Assert.fail(e.getMessage());
    } catch (IOException e) {
        Assert.fail(e.getMessage());
    }

}

From source file:com.jive.myco.seyren.core.util.graphite.GraphiteHttpClient.java

private HttpClient createHttpClient() {
    HttpClientBuilder clientBuilder = HttpClientBuilder.create().setConnectionManager(createConnectionManager())
            .setDefaultRequestConfig(RequestConfig.custom()
                    .setConnectionRequestTimeout(graphiteConnectionRequestTimeout)
                    .setConnectTimeout(graphiteConnectTimeout).setSocketTimeout(graphiteSocketTimeout).build());

    // Set auth header for graphite if username and password are provided
    if (!StringUtils.isEmpty(graphiteUsername) && !StringUtils.isEmpty(graphitePassword)) {
        CredentialsProvider credentialsProvider = new BasicCredentialsProvider();
        credentialsProvider.setCredentials(new AuthScope(AuthScope.ANY_HOST, AuthScope.ANY_PORT),
                new UsernamePasswordCredentials(graphiteUsername, graphitePassword));
        clientBuilder.setDefaultCredentialsProvider(credentialsProvider);
        context.setAttribute("preemptive-auth", new BasicScheme());
        clientBuilder.addInterceptorFirst(new PreemptiveAuth());
    }/*from   www .  j a va 2  s. c  om*/

    return clientBuilder.build();
}

From source file:org.fcrepo.integration.http.api.AbstractResourceIT.java

/**
 * Execute an HTTP request with preemptive basic authentication.
 *
 * @param request the request to execute
 * @param username usename to use/*www  . j  av a 2 s  . c  o m*/
 * @param password password to use
 * @return the open responses
 * @throws IOException in case of IOException
 */
@SuppressWarnings("resource")
protected CloseableHttpResponse executeWithBasicAuth(final HttpUriRequest request, final String username,
        final String password) throws IOException {
    final HttpHost target = new HttpHost(HOSTNAME, SERVER_PORT, PROTOCOL);
    final CredentialsProvider credsProvider = new BasicCredentialsProvider();
    credsProvider.setCredentials(new AuthScope(target.getHostName(), target.getPort()),
            new UsernamePasswordCredentials(username, password));
    final CloseableHttpClient httpclient = HttpClients.custom().setDefaultCredentialsProvider(credsProvider)
            .build();
    final AuthCache authCache = new BasicAuthCache();
    final BasicScheme basicAuth = new BasicScheme();
    authCache.put(target, basicAuth);

    final HttpClientContext localContext = HttpClientContext.create();
    localContext.setAuthCache(authCache);
    return httpclient.execute(request, localContext);
}

From source file:org.springframework.cloud.dataflow.shell.command.ConfigCommands.java

@CliCommand(value = {
        "dataflow config server" }, help = "Configure the Spring Cloud Data Flow REST server to use")
public String target(@CliOption(mandatory = false, key = { "",
        "uri" }, help = "the location of the Spring Cloud Data Flow REST endpoint", unspecifiedDefaultValue = Target.DEFAULT_TARGET) String targetUriString,
        @CliOption(mandatory = false, key = {
                "username" }, help = "the username for authenticated access to the Admin REST endpoint", unspecifiedDefaultValue = Target.DEFAULT_USERNAME) String targetUsername,
        @CliOption(mandatory = false, key = {
                "password" }, help = "the password for authenticated access to the Admin REST endpoint (valid only with a username)", specifiedDefaultValue = Target.DEFAULT_SPECIFIED_PASSWORD, unspecifiedDefaultValue = Target.DEFAULT_UNSPECIFIED_PASSWORD) String targetPassword) {

    if (!StringUtils.isEmpty(targetPassword) && StringUtils.isEmpty(targetUsername)) {
        return "A password may be specified only together with a username";
    }//from w  w w  .  ja  va2 s .c  om
    if (StringUtils.isEmpty(targetPassword) && !StringUtils.isEmpty(targetUsername)) {
        // read password from the command line
        targetPassword = userInput.prompt("Password", "", false);
    }

    try {
        this.targetHolder.setTarget(new Target(targetUriString, targetUsername, targetPassword));

        if (StringUtils.hasText(targetUsername) && StringUtils.hasText(targetPassword)) {
            final BasicCredentialsProvider credentialsProvider = new BasicCredentialsProvider();
            credentialsProvider.setCredentials(AuthScope.ANY,
                    new UsernamePasswordCredentials(
                            targetHolder.getTarget().getTargetCredentials().getUsername(),
                            targetHolder.getTarget().getTargetCredentials().getPassword()));
            final CloseableHttpClient httpClient = HttpClientBuilder.create()
                    .setDefaultCredentialsProvider(credentialsProvider).build();
            final HttpComponentsClientHttpRequestFactory requestFactory = new HttpComponentsClientHttpRequestFactory(
                    httpClient);

            this.restTemplate.setRequestFactory(requestFactory);
        }

        this.shell.setDataFlowOperations(
                new DataFlowTemplate(targetHolder.getTarget().getTargetUri(), this.restTemplate));
        return (String.format("Successfully targeted %s", targetUriString));
    } catch (Exception e) {
        this.targetHolder.getTarget().setTargetException(e);
        this.shell.setDataFlowOperations(null);
        if (e instanceof DataFlowServerException) {
            String message = String.format("Unable to parse server response: %s - at URI '%s'.", e.getMessage(),
                    targetUriString);
            if (logger.isDebugEnabled()) {
                logger.debug(message, e);
            } else {
                logger.warn(message);
            }
            return message;
        } else {
            return (String.format("Unable to contact Data Flow Server at '%s': '%s'.", targetUriString,
                    e.toString()));
        }
    }
}

From source file:fr.univsavoie.ltp.client.map.Session.java

/**
 * Procdure qui s'authentifie sur le serveur REST avec les donnes utilisateurs de faon scuris (protocole HTTPS).
 * Appeler secureAuth() avant chaque nouvelles requtes HTTP (get, post, ...)
 *//*from  www  .j a  va  2  s . c  o  m*/
private void secureAuth() {
    try {
        // Instance de SharedPreferences pour lire les donnes dans un fichier
        SharedPreferences myPrefs = activity.getSharedPreferences("UserPrefs", activity.MODE_WORLD_READABLE);
        String login = myPrefs.getString("Login", null);
        String password = myPrefs.getString("Password", null);

        HttpRequestInterceptor preemptiveAuth = new HttpRequestInterceptor() {
            public void process(final HttpRequest request, final HttpContext context)
                    throws HttpException, IOException {
                AuthState authState = (AuthState) context.getAttribute(ClientContext.TARGET_AUTH_STATE);
                CredentialsProvider credsProvider = (CredentialsProvider) context
                        .getAttribute(ClientContext.CREDS_PROVIDER);
                HttpHost targetHost = (HttpHost) context.getAttribute(ExecutionContext.HTTP_TARGET_HOST);

                if (authState.getAuthScheme() == null) {
                    AuthScope authScope = new AuthScope(targetHost.getHostName(), targetHost.getPort());
                    Credentials creds = credsProvider.getCredentials(authScope);
                    if (creds != null) {
                        authState.setAuthScheme(new BasicScheme());
                        authState.setCredentials(creds);
                    }
                }
            }
        };

        // Setup a custom SSL Factory object which simply ignore the certificates validation and accept all type of self signed certificates
        SSLSocketFactory sslFactory = new SimpleSSLSocketFactory(null);
        sslFactory.setHostnameVerifier(SSLSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER);

        // Enable HTTP parameters
        HttpParams params = new BasicHttpParams();
        HttpProtocolParams.setVersion(params, HttpVersion.HTTP_1_1);
        HttpProtocolParams.setContentCharset(params, HTTP.UTF_8);

        // Register the HTTP and HTTPS Protocols. For HTTPS, register our custom SSL Factory object.
        SchemeRegistry registry = new SchemeRegistry();
        // registry.register(new Scheme("http", PlainSocketFactory.getSocketFactory(), 80));
        registry.register(new Scheme("https", sslFactory, 443));

        // Create a new connection manager using the newly created registry and then create a new HTTP client using this connection manager
        ClientConnectionManager ccm = new ThreadSafeClientConnManager(params, registry);

        httpClient = new DefaultHttpClient(ccm, params);

        CredentialsProvider authCred = new BasicCredentialsProvider();
        Credentials creds = new UsernamePasswordCredentials(login, password);
        authCred.setCredentials(AuthScope.ANY, creds);

        httpClient.addRequestInterceptor(preemptiveAuth, 0);
        httpClient.setCredentialsProvider(authCred);
    } catch (KeyManagementException e) {
        e.printStackTrace();
    } catch (UnrecoverableKeyException e) {
        e.printStackTrace();
    } catch (NoSuchAlgorithmException e) {
        e.printStackTrace();
    } catch (KeyStoreException e) {
        e.printStackTrace();
    }
}

From source file:org.alfresco.maven.plugin.AbstractRefreshWebappMojo.java

/**
 * Helper method to make a POST request to the Alfresco Webapp
 *
 * @param alfrescoTomcatUrl the URL for the webapp we want to post to
 * @param postData the POST data that should be sent
 * @param operation information about the operation we are performing
 *///from ww w  .j  a v a  2 s .  c  o m
private void makePostCall(URL alfrescoTomcatUrl, List<NameValuePair> postData, String operation) {
    CloseableHttpClient client = null;
    CloseableHttpResponse response = null;
    try {
        // Set up a HTTP POST request to the Alfresco Webapp we are targeting
        HttpHost targetHost = new HttpHost(alfrescoTomcatUrl.getHost(), alfrescoTomcatUrl.getPort(),
                alfrescoTomcatUrl.getProtocol());

        // Set up authentication parameters
        CredentialsProvider credsProvider = new BasicCredentialsProvider();
        credsProvider.setCredentials(new AuthScope(targetHost.getHostName(), targetHost.getPort()),
                new UsernamePasswordCredentials(refreshUsername, refreshPassword));

        // Create the HTTP Client we will use to make the call
        client = HttpClients.custom().setDefaultCredentialsProvider(credsProvider).build();

        // Create AuthCache instance
        AuthCache authCache = new BasicAuthCache();

        // Generate BASIC scheme object and add it to the local auth cache
        BasicScheme basicAuth = new BasicScheme();
        authCache.put(targetHost, basicAuth);

        // Add AuthCache to the execution context
        HttpClientContext localContext = HttpClientContext.create();
        localContext.setAuthCache(authCache);

        // Make the call to Refresh the Alfresco Webapp
        HttpPost httpPost = new HttpPost(alfrescoTomcatUrl.toURI());
        response = client.execute(httpPost);
        if (postData != null) {
            UrlEncodedFormEntity entity = new UrlEncodedFormEntity(postData, "UTF-8");
            httpPost.setEntity(entity);
        }
        httpPost.setHeader("Accept-Charset", "iso-8859-1,utf-8");
        httpPost.setHeader("Accept-Language", "en-us");
        response = client.execute(httpPost);

        // If no response, no method has been passed
        if (response == null) {
            getLog().error("POST request failed to " + alfrescoTomcatUrl.toString() + ", " + getAbortedMsg());
            return;
        }

        // Check if we got a successful response or not
        int statusCode = response.getStatusLine().getStatusCode();
        if (statusCode == HttpStatus.SC_OK) {
            getLog().info("Successfull " + operation + " for " + refreshWebappName);
        } else {
            String reasonPhrase = response.getStatusLine().getReasonPhrase();
            getLog().warn("Failed to " + operation + " for " + refreshWebappName + ". Response status: "
                    + statusCode + ", message: " + reasonPhrase);
        }
    } catch (Exception ex) {
        getLog().error("POST request failed to " + alfrescoTomcatUrl.toString() + ", " + getAbortedMsg());
        getLog().error("Exception Msg: " + ex.getMessage());
    } finally {
        closeQuietly(response);
        closeQuietly(client);
    }
}

From source file:com.jkoolcloud.tnt4j.streams.inputs.RestStream.java

private static String executeRequest(HttpClient client, HttpUriRequest req, String username, String password)
        throws IOException {
    HttpResponse response;/* w  ww . j  av  a  2  s. co m*/

    if (StringUtils.isNotEmpty(username)) {
        CredentialsProvider credentialsProvider = new BasicCredentialsProvider();
        credentialsProvider.setCredentials(new AuthScope(req.getURI().getAuthority(), DEFAULT_AUTH_PORT),
                new UsernamePasswordCredentials(username, password));

        HttpClientContext context = HttpClientContext.create();
        context.setCredentialsProvider(credentialsProvider);
        // context.setAuthSchemeRegistry(authRegistry);
        // context.setAuthCache(authCache);

        response = client.execute(req, context);
    } else {
        response = client.execute(req);
    }

    int responseCode = response.getStatusLine().getStatusCode();
    if (responseCode >= HttpStatus.SC_MULTIPLE_CHOICES) {
        throw new HttpResponseException(responseCode, response.getStatusLine().getReasonPhrase());
    }

    String respStr = EntityUtils.toString(response.getEntity(), Utils.UTF8);

    return respStr;
}