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.sonatype.nexus.error.reporting.NexusPRConnectorTest.java

@Test
public void testProxyAuth() {
    final String host = "host";
    final int port = 1234;

    when(proxySettings.isEnabled()).thenReturn(true);
    when(proxySettings.getHostname()).thenReturn(host);
    when(proxySettings.getPort()).thenReturn(port);

    when(proxySettings.getProxyAuthentication()).thenReturn(proxyAuth);
    when(proxyAuth.getUsername()).thenReturn("user");
    when(proxyAuth.getPassword()).thenReturn("pass");

    final HttpClient client = underTest.client();
    final HttpParams params = client.getParams();

    assertThat(ConnRouteParams.getDefaultProxy(params), notNullValue());
    assertThat(params.getParameter(AuthPNames.PROXY_AUTH_PREF), notNullValue());

    assertThat(((DefaultHttpClient) client).getCredentialsProvider().getCredentials(new AuthScope(host, port)),
            notNullValue());// w ww.j a v  a  2s  . co  m
}

From source file:org.openremote.java.console.controller.connector.SingleThreadHttpConnector.java

@Override
public void setCredentials(Credentials credentials) {
    creds.clear();//  www . j  a  v  a2s .c o m
    if (credentials != null) {
        creds.setCredentials(new AuthScope("localhost", 8080),
                new UsernamePasswordCredentials(credentials.getUsername(), credentials.getPassword()));
    }
}

From source file:cloudfoundry.norouter.f5.client.HttpClientIControlClient.java

private HttpClientIControlClient(HttpHost host, Builder builder) {
    super(URI.create(host.toURI()));
    this.host = host;

    final BasicCredentialsProvider credentialsProvider = new BasicCredentialsProvider();
    final UsernamePasswordCredentials credentials = new UsernamePasswordCredentials(
            Objects.requireNonNull(builder.user, "user is a required argument"),
            Objects.requireNonNull(builder.password, "password is a required argument"));
    credentialsProvider.setCredentials(new AuthScope(host.getHostName(), host.getPort()), credentials);

    final HttpClientBuilder httpClientBuilder = HttpClients.custom().setUserAgent("curl/7.37.1")
            .disableCookieManagement().setDefaultCredentialsProvider(credentialsProvider);
    if (builder.skipVerifyTls) {
        httpClientBuilder.setSSLSocketFactory(NaiveTrustManager.getSocketFactory());
    }/* w  w w .  j  ava  2  s . c o  m*/
    httpClient = httpClientBuilder.build();
}

From source file:org.sdr.webrec.core.WebRec.java

public void run() {

    initParameters();//from w  ww  .  j ava 2s. co m

    String transactionName = "";
    HttpResponse response = null;

    DecimalFormat formatter = new DecimalFormat("#####0.00");
    DecimalFormatSymbols dfs = formatter.getDecimalFormatSymbols();
    formatter.setMinimumFractionDigits(3);
    formatter.setMaximumFractionDigits(3);

    // make sure delimeter is a '.' instead of locale default ','
    dfs.setDecimalSeparator('.');
    formatter.setDecimalFormatSymbols(dfs);

    do {
        t1 = System.currentTimeMillis();
        URL siteURL = null;
        try {

            for (int i = 0; i < url.length; i++) {

                LOGGER.debug("url:" + ((Transaction) url[i]).getUrl());

                Transaction transaction = (Transaction) url[i];
                siteURL = new URL(transaction.getUrl());
                transactionName = transaction.getName();

                //if transaction requires server authentication
                if (transaction.isAutenticate())
                    httpclient.getCredentialsProvider().setCredentials(
                            new AuthScope(siteURL.getHost(), siteURL.getPort()),
                            new UsernamePasswordCredentials(transaction.getWorkload().getUsername(),
                                    transaction.getWorkload().getPassword()));

                // Get HTTP GET method
                httpget = new HttpGet(((Transaction) url[i]).getUrl());

                double startTime = System.nanoTime();

                double endTime = 0.00d;

                response = null;

                // Execute HTTP GET
                try {
                    response = httpclient.execute(httpget);
                    endTime = System.nanoTime();

                } catch (Exception e) {
                    httpget.abort();
                    LOGGER.error("ERROR in receiving response:" + e.getLocalizedMessage());
                    e.printStackTrace();
                }

                double timeLapse = 0;

                if (response != null) {
                    if (response.getStatusLine().getStatusCode() == HttpURLConnection.HTTP_OK) {

                        timeLapse = endTime - startTime;

                        LOGGER.debug("starttime:" + (new Double(startTime)).toString());
                        LOGGER.debug("timeLapse:" + endTime);
                        LOGGER.debug("timeLapse:" + timeLapse);

                        //move nanos to millis
                        timeLapse = timeLapse / 1000000L;
                        LOGGER.debug("response time:" + formatter.format(timeLapse) + "ms.");
                        out.write(System.currentTimeMillis() / 1000 + ":");
                        out.write(
                                threadName + '.' + transactionName + ":" + formatter.format(timeLapse) + "\n");

                        //content must be consumed just because 
                        //otherwice apache httpconnectionmanager does not release connection back to pool
                        HttpEntity entity = response.getEntity();
                        if (entity != null) {
                            EntityUtils.toByteArray(entity);
                        }

                    } else {
                        LOGGER.error("Status code of transaction:" + transactionName + " was not "
                                + HttpURLConnection.HTTP_OK + " but "
                                + response.getStatusLine().getStatusCode());
                    }

                }
                int sleepTime = delay;
                try {
                    LOGGER.debug("Sleeping " + delay / 1000 + "s...");
                    sleep(sleepTime);
                } catch (InterruptedException ie) {
                    LOGGER.error("ERROR:" + ie);
                    ie.printStackTrace();
                }
            }
        } catch (Exception e) {
            LOGGER.error("Error in thread " + threadName + " with url:" + siteURL + " " + e.getMessage());
            e.printStackTrace();
        }
        try {
            out.flush();
            t2 = System.currentTimeMillis();
            tTask = t2 - t1;

            LOGGER.debug("Total time consumed:" + tTask / 1000 + "s.");

            if (tTask <= interval) {
                //when task takes less than preset time
                LOGGER.debug("Sleeping interval:" + (interval - tTask) / 1000 + "s.");
                sleep(interval - tTask);
            }

            cm.closeExpiredConnections();
        } catch (InterruptedException ie) {
            LOGGER.error("Error:" + ie);
            ie.printStackTrace();
        } catch (Exception e) {
            LOGGER.error("Error:" + e);
            e.printStackTrace();
        }
    } while (true);
}

From source file:org.yamj.api.common.http.SimpleHttpClientBuilder.java

/**
 * Create the CloseableHttpClient//  w w  w .  ja v  a  2s .c  om
 *
 * @return
 */
public CloseableHttpClient build() {
    // create proxy
    HttpHost proxy = null;
    CredentialsProvider credentialsProvider = null;

    if (isNotBlank(proxyHost) && proxyPort > 0) {
        proxy = new HttpHost(proxyHost, proxyPort);

        if (isNotBlank(proxyUsername) && isNotBlank(proxyPassword)) {
            if (systemProperties) {
                credentialsProvider = new SystemDefaultCredentialsProvider();
            } else {
                credentialsProvider = new BasicCredentialsProvider();
            }
            credentialsProvider.setCredentials(new AuthScope(proxyHost, proxyPort),
                    new UsernamePasswordCredentials(proxyUsername, proxyPassword));
        }
    }

    HttpClientBuilder builder = HttpClientBuilder.create().setMaxConnTotal(maxConnTotal)
            .setMaxConnPerRoute(maxConnPerRoute).setProxy(proxy)
            .setDefaultCredentialsProvider(credentialsProvider)
            .setDefaultRequestConfig(RequestConfig.custom()
                    .setConnectionRequestTimeout(connectionRequestTimeout).setConnectTimeout(connectTimeout)
                    .setSocketTimeout(socketTimeout).setProxy(proxy).build());

    // use system properties
    if (systemProperties) {
        builder.useSystemProperties();
    }

    // build the http client
    return builder.build();
}

From source file:org.mariotaku.twidere.util.httpclient.HttpClientImpl.java

public HttpClientImpl(final HttpClientConfiguration conf) {
    this.conf = conf;
    final SchemeRegistry registry = new SchemeRegistry();
    final SSLSocketFactory factory = conf.isSSLErrorIgnored() ? TRUST_ALL_SSL_SOCKET_FACTORY
            : SSLSocketFactory.getSocketFactory();
    registry.register(new Scheme("http", PlainSocketFactory.getSocketFactory(), 80));
    registry.register(new Scheme("https", factory, 443));
    final HttpParams params = new BasicHttpParams();
    final ThreadSafeClientConnManager cm = new ThreadSafeClientConnManager(params, registry);
    final DefaultHttpClient client = new DefaultHttpClient(cm, params);
    final HttpParams client_params = client.getParams();
    HttpConnectionParams.setConnectionTimeout(client_params, conf.getHttpConnectionTimeout());
    HttpConnectionParams.setSoTimeout(client_params, conf.getHttpReadTimeout());

    if (conf.getHttpProxyHost() != null && !conf.getHttpProxyHost().equals("")) {
        final HttpHost proxy = new HttpHost(conf.getHttpProxyHost(), conf.getHttpProxyPort());
        client.getParams().setParameter(ConnRoutePNames.DEFAULT_PROXY, proxy);

        if (conf.getHttpProxyUser() != null && !conf.getHttpProxyUser().equals("")) {
            if (logger.isDebugEnabled()) {
                logger.debug("Proxy AuthUser: " + conf.getHttpProxyUser());
                logger.debug(// w w  w.  j a va 2s . c o m
                        "Proxy AuthPassword: " + InternalStringUtil.maskString(conf.getHttpProxyPassword()));
            }
            client.getCredentialsProvider().setCredentials(
                    new AuthScope(conf.getHttpProxyHost(), conf.getHttpProxyPort()),
                    new UsernamePasswordCredentials(conf.getHttpProxyUser(), conf.getHttpProxyPassword()));
        }
    }
    this.client = client;
}

From source file:org.whispersystems.mmsmonster.mms.MmsConnection.java

protected CloseableHttpClient constructHttpClient() throws IOException {
    RequestConfig config = RequestConfig.custom().setConnectTimeout(20 * 1000)
            .setConnectionRequestTimeout(20 * 1000).setSocketTimeout(20 * 1000).setMaxRedirects(20).build();

    URL mmsc = new URL(apn.getMmsc());
    CredentialsProvider credsProvider = new BasicCredentialsProvider();

    if (apn.hasAuthentication()) {
        credsProvider.setCredentials(/* ww  w  .  j  av a  2s .c om*/
                new AuthScope(mmsc.getHost(), mmsc.getPort() > -1 ? mmsc.getPort() : mmsc.getDefaultPort()),
                new UsernamePasswordCredentials(apn.getUsername(), apn.getPassword()));
    }

    return HttpClients.custom().setConnectionReuseStrategy(new NoConnectionReuseStrategyHC4())
            .setRedirectStrategy(new LaxRedirectStrategy()).setUserAgent("Android-Mms/2.0")
            .setConnectionManager(new BasicHttpClientConnectionManager()).setDefaultRequestConfig(config)
            .setDefaultCredentialsProvider(credsProvider).build();
}

From source file:fr.mael.jiwigo.transverse.session.impl.SessionManagerImpl.java

/**
 * Connection method/* w w w  .  j  ava2  s  . c o  m*/
 *
 * @return 0 if Ok, 1 if not Ok (reason not specified), 2 if proxy error
 * @throws JiwigoException 
 *
 *
 */
public int processLogin() throws JiwigoException {
    Document doc;
    //configures the proxy
    if (usesProxy) {
        //       HostConfiguration config = client.getHostConfiguration();
        //       config.setProxy(urlProxy, portProxy);
        if (!StringUtils.isEmpty(loginProxy) && !StringUtils.isEmpty(passProxy)) {
            //      Credentials credentials = new UsernamePasswordCredentials(loginProxy, passProxy);
            //      AuthScope authScope = new AuthScope(urlProxy, portProxy);
            //      client.getState().setProxyCredentials(authScope, credentials);
            HttpHost proxy = new HttpHost(urlProxy, portProxy);
            client.getParams().setParameter(ConnRoutePNames.DEFAULT_PROXY, proxy);
            client.getCredentialsProvider().setCredentials(new AuthScope(urlProxy, portProxy),
                    new UsernamePasswordCredentials(loginProxy, passProxy));

        }
    }
    doc = executeReturnDocument(MethodsEnum.LOGIN.getLabel(), "username", login, "password", password);
    if (LOG.isDebugEnabled()) {
        LOG.debug("XML connection : " + Tools.documentToString(doc));
    }
    try {
        return (Tools.checkOk(doc) ? 0 : 1);
    } catch (FileAlreadyExistsException e) {
        LOG.error(Tools.getStackTrace(e));
        throw new JiwigoException(e);
    }

}

From source file:org.opensuse.android.HttpCoreRestClient.java

private HttpClient connect() {
    DefaultHttpClient client = new DefaultHttpClient();
    client.getCredentialsProvider().setCredentials(new AuthScope(host, 80),
            new UsernamePasswordCredentials(username, password));
    return client;
}

From source file:com.amazon.s3.http.HttpClientFactory.java

/**
  * Creates a new HttpClient object using the specified AWS
  * ClientConfiguration to configure the client.
  *//  ww w .j  ava 2  s .c  o m
  * @param config
  *            Client configuration options (ex: proxy settings, connection
  *            limits, etc).
  *
  * @return The new, configured HttpClient.
  */
public HttpClient createHttpClient(ClientConfiguration config) {
    /* Form User-Agent information */
    String userAgent = config.getUserAgent();
    if (!(userAgent.equals(ClientConfiguration.DEFAULT_USER_AGENT))) {
        userAgent += ", " + ClientConfiguration.DEFAULT_USER_AGENT;
    }

    /* Set HTTP client parameters */
    HttpParams httpClientParams = new BasicHttpParams();
    HttpClientParams.setRedirecting(httpClientParams, false);
    HttpProtocolParams.setUserAgent(httpClientParams, userAgent);
    HttpConnectionParams.setConnectionTimeout(httpClientParams, config.getConnectionTimeout());
    HttpConnectionParams.setSoTimeout(httpClientParams, config.getSocketTimeout());
    HttpConnectionParams.setStaleCheckingEnabled(httpClientParams, false);
    HttpConnectionParams.setTcpNoDelay(httpClientParams, true);

    int socketSendBufferSizeHint = config.getSocketBufferSizeHints()[0];
    int socketReceiveBufferSizeHint = config.getSocketBufferSizeHints()[1];
    if (socketSendBufferSizeHint > 0 || socketReceiveBufferSizeHint > 0) {
        HttpConnectionParams.setSocketBufferSize(httpClientParams,
                Math.max(socketSendBufferSizeHint, socketReceiveBufferSizeHint));
    }

    /* Set connection manager */
    ThreadSafeClientConnManager connectionManager = ConnectionManagerFactory
            .createThreadSafeClientConnManager(config, httpClientParams);
    DefaultHttpClient httpClient = new DefaultHttpClient(connectionManager, httpClientParams);

    /* Set proxy if configured */
    String proxyHost = config.getProxyHost();
    int proxyPort = config.getProxyPort();
    if (proxyHost != null && proxyPort > 0) {
        Log.i(TAG, "Configuring Proxy. Proxy Host: " + proxyHost + " " + "Proxy Port: " + proxyPort);
        HttpHost proxyHttpHost = new HttpHost(proxyHost, proxyPort);
        httpClient.getParams().setParameter(ConnRoutePNames.DEFAULT_PROXY, proxyHttpHost);

        String proxyUsername = config.getProxyUsername();
        String proxyPassword = config.getProxyPassword();
        String proxyDomain = config.getProxyDomain();
        String proxyWorkstation = config.getProxyWorkstation();

        if (proxyUsername != null && proxyPassword != null) {
            httpClient.getCredentialsProvider().setCredentials(new AuthScope(proxyHost, proxyPort),
                    new NTCredentials(proxyUsername, proxyPassword, proxyWorkstation, proxyDomain));
        }
    }

    return httpClient;
}