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:org.apache.nifi.processors.standard.util.HTTPUtils.java

public static void setProxy(final ProcessContext context, final HttpClientBuilder clientBuilder,
        final CredentialsProvider credentialsProvider) {
    // Set the proxy if specified
    final ProxyConfiguration proxyConfig = ProxyConfiguration.getConfiguration(context, () -> {
        if (context.getProperty(PROXY_HOST).isSet() && context.getProperty(PROXY_PORT).isSet()) {
            final ProxyConfiguration componentProxyConfig = new ProxyConfiguration();
            final String host = context.getProperty(PROXY_HOST).getValue();
            final int port = context.getProperty(PROXY_PORT).asInteger();
            componentProxyConfig.setProxyType(Proxy.Type.HTTP);
            componentProxyConfig.setProxyServerHost(host);
            componentProxyConfig.setProxyServerPort(port);
            return componentProxyConfig;
        }/*from   w  w w  .  java 2s.  c  om*/
        return ProxyConfiguration.DIRECT_CONFIGURATION;
    });

    if (Proxy.Type.HTTP.equals(proxyConfig.getProxyType())) {
        final String host = proxyConfig.getProxyServerHost();
        final int port = proxyConfig.getProxyServerPort();
        clientBuilder.setProxy(new HttpHost(host, port));

        if (proxyConfig.hasCredential()) {
            final AuthScope proxyAuthScope = new AuthScope(host, port);
            final UsernamePasswordCredentials proxyCredential = new UsernamePasswordCredentials(
                    proxyConfig.getProxyUserName(), proxyConfig.getProxyUserPassword());
            credentialsProvider.setCredentials(proxyAuthScope, proxyCredential);
        }
    }
}

From source file:com.google.code.maven.plugin.http.client.Proxy.java

/**
 * prepares the httpclient for using this proxy configuration when opening http connection
 * //from w  w  w .  ja va  2 s  .c  o m
 * @param httpclient
 */
public void prepare(DefaultHttpClient httpclient) {
    HttpHost proxyHost = new HttpHost(host, port);
    httpclient.getParams().setParameter(ConnRoutePNames.DEFAULT_PROXY, proxyHost);
    if (credentials != null) {
        httpclient.getCredentialsProvider().setCredentials(//
                new AuthScope(host, port), //
                credentials.toUsernamePasswordCredentials());
    }
}

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);
    }//from w  ww  .  j a  v a  2 s  . c  o m
}

From source file:de.tsystems.mms.apm.performancesignature.viewer.rest.model.CustomJenkinsHttpClient.java

private static HttpClientBuilder createHttpClientBuilder(final boolean verifyCertificate,
        final CustomProxy customProxy) {

    HttpClientBuilder httpClientBuilder = HttpClients.custom();
    httpClientBuilder.useSystemProperties();
    if (!verifyCertificate) {
        SSLContextBuilder builder = new SSLContextBuilder();
        try {/*w  w w.  j  av  a  2 s .  c o  m*/
            builder.loadTrustMaterial(null, new TrustStrategy() {
                public boolean isTrusted(X509Certificate[] chain, String authType) throws CertificateException {
                    return true;
                }
            });
            httpClientBuilder.setSSLSocketFactory(new SSLConnectionSocketFactory(builder.build()));
        } catch (NoSuchAlgorithmException | KeyStoreException | KeyManagementException e) {
            LOGGER.severe(ExceptionUtils.getFullStackTrace(e));
        }

    }
    if (customProxy != null) {
        Jenkins jenkins = PerfSigUIUtils.getInstance();
        if (customProxy.isUseJenkinsProxy() && jenkins.proxy != null) {
            final ProxyConfiguration proxyConfiguration = jenkins.proxy;
            if (StringUtils.isNotBlank(proxyConfiguration.name) && proxyConfiguration.port > 0) {
                httpClientBuilder.setProxy(new HttpHost(proxyConfiguration.name, proxyConfiguration.port));
                if (StringUtils.isNotBlank(proxyConfiguration.getUserName())) {
                    CredentialsProvider credsProvider = new BasicCredentialsProvider();
                    UsernamePasswordCredentials usernamePasswordCredentials = new UsernamePasswordCredentials(
                            proxyConfiguration.getUserName(), proxyConfiguration.getUserName());
                    credsProvider.setCredentials(
                            new AuthScope(proxyConfiguration.name, proxyConfiguration.port),
                            usernamePasswordCredentials);
                    httpClientBuilder.setDefaultCredentialsProvider(credsProvider);
                    httpClientBuilder.setProxyAuthenticationStrategy(new ProxyAuthenticationStrategy());
                }
            }
        } else {
            httpClientBuilder.setProxy(new HttpHost(customProxy.getProxyServer(), customProxy.getProxyPort()));
            if (StringUtils.isNotBlank(customProxy.getProxyUser())
                    && StringUtils.isNotBlank(customProxy.getProxyPassword())) {
                CredentialsProvider credsProvider = new BasicCredentialsProvider();
                UsernamePasswordCredentials usernamePasswordCredentials = new UsernamePasswordCredentials(
                        customProxy.getProxyUser(), customProxy.getProxyPassword());
                credsProvider.setCredentials(
                        new AuthScope(customProxy.getProxyServer(), customProxy.getProxyPort()),
                        usernamePasswordCredentials);
                httpClientBuilder.setDefaultCredentialsProvider(credsProvider);
                httpClientBuilder.setProxyAuthenticationStrategy(new ProxyAuthenticationStrategy());
            }
        }
    }
    return httpClientBuilder;
}

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();/* w  ww.j a  va 2 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 {/*from   w  w  w. j ava 2s .  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:com.fujitsu.dc.client.http.RestAdapter.java

/**
 * This is the parameterized constructor to initialize various fields.
 * @param as Accessor//from   w  ww . j  a v  a2  s. c om
 */
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:net.oauth.client.httpclient4.OAuthSchemeTest.java

@Override
public void setUp() throws Exception {
    { // Get an ephemeral local port number:
        Socket s = new Socket();
        s.bind(null);/*www  . j a  v a  2  s  .c o m*/
        port = s.getLocalPort();
        s.close();
    }
    server = new Server(port);
    Context servletContext = new Context(server, "/", Context.SESSIONS);
    servletContext.addServlet(new ServletHolder(new ProtectedResource()), "/Resource/*");
    server.start();
    context = new BasicHttpContext();
    context.setAttribute(ClientContext.AUTH_SCHEME_PREF, Arrays.asList(OAuthSchemeFactory.SCHEME_NAME));
    client = new DefaultHttpClient();
    client.getAuthSchemes().register(OAuthSchemeFactory.SCHEME_NAME, new OAuthSchemeFactory());
    client.getCredentialsProvider().setCredentials(new AuthScope("localhost", port),
            new OAuthCredentials(ProtectedResource.ACCESSOR));
}

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

static public Response postXml(String url, String username, String password, String requestXml)
        throws Exception {
    ////from  w ww  .j a  v  a  2 s . c om
    // 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// ww w .jav  a 2s .com
 */
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));
        }
    }
}