Example usage for org.apache.http.auth AuthScope AuthScope

List of usage examples for org.apache.http.auth AuthScope AuthScope

Introduction

In this page you can find the example usage for org.apache.http.auth AuthScope AuthScope.

Prototype

public AuthScope(final String host, final int port) 

Source Link

Document

Creates a new credentials scope for the given host, port, any realm name, and any authentication scheme.

Usage

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 w  w w  . java 2s .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.openlmis.UiUtils.HttpClient.java

public ResponseEntity SendJSONWithoutHeaders(String json, String url, String commMethod, String username,
        String password) {//  w ww  . j av  a  2 s .c om
    HttpHost targetHost = new HttpHost(HOST, PORT, PROTOCOL);
    AuthScope localhost = new AuthScope(HOST, PORT);

    UsernamePasswordCredentials credentials = new UsernamePasswordCredentials(username, password);
    httpClient.getCredentialsProvider().setCredentials(localhost, credentials);

    AuthCache authCache = new BasicAuthCache();
    authCache.put(targetHost, new BasicScheme());

    httpContext.setAttribute(AUTH_CACHE, authCache);

    try {
        return handleRequest(commMethod, json, url, false);
    } catch (Exception e) {
        e.printStackTrace();
    }
    return null;
}

From source file:RestApiHttpClient.java

/**
 * Create an new {@link RestApiHttpClient} instance with Endpoint, username and API-Key
 * //  w w w .  j  a  va2  s  .com
 * @param apiEndpoint The Hostname and Api-Endpoint (http://www.example.com/api)
 * @param username Shopware Username
 * @param password Api-Key from User-Administration
 */
public RestApiHttpClient(URL apiEndpoint, String username, String password) {
    this.apiEndpoint = apiEndpoint;

    BasicHttpContext context = new BasicHttpContext();
    this.localContext = HttpClientContext.adapt(context);
    HttpHost target = new HttpHost(this.apiEndpoint.getHost(), -1, this.apiEndpoint.getProtocol());
    this.localContext.setTargetHost(target);

    TargetAuthenticationStrategy authStrat = new TargetAuthenticationStrategy();
    UsernamePasswordCredentials creds = new UsernamePasswordCredentials(username, password);
    BasicCredentialsProvider credsProvider = new BasicCredentialsProvider();
    AuthScope aScope = new AuthScope(target.getHostName(), target.getPort());
    credsProvider.setCredentials(aScope, creds);

    BasicAuthCache authCache = new BasicAuthCache();
    // Digest Authentication
    DigestScheme digestAuth = new DigestScheme(Charset.forName("UTF-8"));
    authCache.put(target, digestAuth);
    this.localContext.setAuthCache(authCache);
    this.localContext.setCredentialsProvider(credsProvider);

    ArrayList<Header> defHeaders = new ArrayList<>();
    defHeaders.add(new BasicHeader(HttpHeaders.ACCEPT, ContentType.APPLICATION_JSON.getMimeType()));
    this.httpclient = HttpClients.custom().useSystemProperties().setTargetAuthenticationStrategy(authStrat)
            .disableRedirectHandling()
            // make Rest-API Endpoint GZIP-Compression enable comment this out
            // Response-Compression is also possible
            .disableContentCompression().setDefaultHeaders(defHeaders)
            .setDefaultCredentialsProvider(credsProvider).build();

}

From source file:org.apache.sling.hapi.client.impl.AbstractHtmlClientImpl.java

public AbstractHtmlClientImpl(String baseUrl, String user, String password) throws URISyntaxException {
    this.baseUrl = new URI(baseUrl);
    HttpHost targetHost = URIUtils.extractHost(this.baseUrl);
    BasicCredentialsProvider credsProvider = new BasicCredentialsProvider();
    credsProvider.setCredentials(new AuthScope(targetHost.getHostName(), targetHost.getPort()),
            new UsernamePasswordCredentials(user, password));
    this.client = HttpClientBuilder.create().setDefaultCredentialsProvider(credsProvider)
            .setRedirectStrategy(new LaxRedirectStrategy()).build();
}

From source file:org.openehealth.ipf.labs.maven.confluence.export.AbstractConfluenceExportMojo.java

protected void configureHttpClientProxy() {
    Proxy activeProxy = this.settings.getActiveProxy();
    HttpHost proxy = new HttpHost(activeProxy.getHost(), activeProxy.getPort());

    String proxyUserName = activeProxy.getUsername();
    if (defined(proxyUserName)) {
        String proxyPassword = activeProxy.getPassword();
        client.getCredentialsProvider().setCredentials(new AuthScope(proxy.getHostName(), proxy.getPort()),
                new UsernamePasswordCredentials(proxyUserName, proxyPassword));
    }//from   ww  w  . j a  va2s .  c  o  m
    getLog().info("Using proxy: " + activeProxy.getHost() + ":" + activeProxy.getPort());
    client.getParams().setParameter(ConnRoutePNames.DEFAULT_PROXY, proxy);
}

From source file:org.jboss.jdf.stacks.StacksFactory.java

private static void configureProxy(final DefaultHttpClient client, final StacksConfiguration stacksConfig) {
    if (stacksConfig.getProxyHost() != null) {
        final String proxyHost = stacksConfig.getProxyHost();
        final int proxyPort = stacksConfig.getProxyPort();
        final HttpHost proxy = new HttpHost(proxyHost, proxyPort);
        client.getParams().setParameter(ConnRoutePNames.DEFAULT_PROXY, proxy);
        final String proxyUsername = stacksConfig.getProxyUser();
        if (proxyUsername != null && !proxyUsername.isEmpty()) {
            final String proxyPassword = stacksConfig.getProxyPassword();
            final AuthScope authScope = new AuthScope(proxyHost, proxyPort);
            final UsernamePasswordCredentials credentials = new UsernamePasswordCredentials(proxyUsername,
                    proxyPassword);/*from  w  ww . ja  v  a2s .  c om*/
            client.getCredentialsProvider().setCredentials(authScope, credentials);
        }
    }
}

From source file:com.marklogic.client.functionaltest.ConnectedRESTQA.java

public static void createDB(String dbName) {
    try {/* w w  w.j  ava  2 s  .co  m*/

        DefaultHttpClient client = new DefaultHttpClient();
        client.getCredentialsProvider().setCredentials(new AuthScope("localhost", 8002),
                new UsernamePasswordCredentials("admin", "admin"));

        HttpPost post = new HttpPost("http://localhost:8002" + "/manage/v2/databases?format=json");
        String JSONString = "[{\"database-name\":\"" + dbName + "\"}]";

        post.addHeader("Content-type", "application/json");
        post.setEntity(new StringEntity(JSONString));

        HttpResponse response = client.execute(post);
        HttpEntity respEntity = response.getEntity();

        if (respEntity != null) {
            // EntityUtils to get the response content
            String content = EntityUtils.toString(respEntity);
            System.out.println(content);
        }
    } catch (Exception e) {
        // writing error to Log
        e.printStackTrace();
    }
}

From source file:com.ibm.ecod.watson.RetrieveAndRankSolrJExample.java

private static HttpClient createHttpClient(String uri, String username, String password) {
    final URI scopeUri = URI.create(uri);

    final BasicCredentialsProvider credentialsProvider = new BasicCredentialsProvider();
    credentialsProvider.setCredentials(new AuthScope(scopeUri.getHost(), scopeUri.getPort()),
            new UsernamePasswordCredentials(username, password));

    final HttpClientBuilder builder = HttpClientBuilder.create().setMaxConnTotal(128).setMaxConnPerRoute(32)
            .setDefaultRequestConfig(/*from   w  w w. j a  va2  s .  co m*/
                    RequestConfig.copy(RequestConfig.DEFAULT).setRedirectsEnabled(true).build());
    builder.setDefaultCredentialsProvider(credentialsProvider);

    return builder.build();
}

From source file:org.miloss.fgsms.presentation.StatusHelper.java

/**
 * determines if an fgsms service is currently accessible. not for use
 * with other services.//from ww w  .j  av a2 s  .co m
 *
 * @param endpoint
 * @return
 */
public String sendGetRequest(String endpoint) {
    //   String result = null;
    if (endpoint.startsWith("http")) {
        // Send a GET request to the servlet
        try {

            URL url = new URL(endpoint);
            int port = url.getPort();
            if (port <= 0) {
                if (endpoint.startsWith("https:")) {
                    port = 443;
                } else {
                    port = 80;
                }
            }

            HttpClientBuilder create = HttpClients.custom();

            if (mode == org.miloss.fgsms.common.Constants.AuthMode.UsernamePassword) {
                CredentialsProvider credsProvider = new BasicCredentialsProvider();
                credsProvider.setCredentials(new AuthScope(url.getHost(), port),
                        new UsernamePasswordCredentials(username, Utility.DE(password)));
                create.setDefaultCredentialsProvider(credsProvider);
                ;

            }
            CloseableHttpClient c = create.build();

            CloseableHttpResponse response = c.execute(new HttpHost(url.getHost(), port),
                    new HttpGet(endpoint));

            c.close();
            int status = response.getStatusLine().getStatusCode();
            if (status == 200) {
                return "OK";
            }
            return String.valueOf(status);

        } catch (Exception ex) {
            Logger.getLogger(Helper.class).log(Level.WARN,
                    "error fetching http doc from " + endpoint + ex.getLocalizedMessage());
            return "offline";
        }
    } else {
        return "undeterminable";
    }
}