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.byteengine.client.Client.java

public void setProxySettings(String proxyHost, int proxyPort, String proxyUsername, String proxyPass) {
    HttpHost proxy = new HttpHost(proxyHost, proxyPort);

    proxyConfig = RequestConfig.custom().setProxy(proxy).build();

    CredentialsProvider credsProvider = new BasicCredentialsProvider();
    AuthScope authScope = new AuthScope(proxyHost, proxyPort);
    UsernamePasswordCredentials creds = new UsernamePasswordCredentials(proxyUsername, proxyPass);
    credsProvider.setCredentials(authScope, creds);

    httpClient = HttpClients.custom().setDefaultCredentialsProvider(credsProvider).build();
}

From source file:me.willowcheng.makerthings.util.MjpegStreamer.java

public InputStream httpRequest(String url, String usr, String pwd) {
    HttpResponse res = null;//from   www .j a  v a 2 s.co m
    DefaultHttpClient httpclient = new DefaultHttpClient();
    CredentialsProvider credProvider = new BasicCredentialsProvider();
    credProvider.setCredentials(new AuthScope(AuthScope.ANY_HOST, AuthScope.ANY_PORT),
            new UsernamePasswordCredentials(usr, pwd));
    httpclient.setCredentialsProvider(credProvider);
    Log.d(TAG, "1. Sending http request");
    try {
        res = httpclient.execute(new HttpGet(URI.create(url)));
        Log.d(TAG, "2. Request finished, status = " + res.getStatusLine().getStatusCode());
        if (res.getStatusLine().getStatusCode() == 401) {
            //You must turn off camera User Access Control before this will work
            return null;
        }
        Log.d(TAG, "content-type = " + res.getEntity().getContentType());
        Log.d(TAG, "content-encoding = " + res.getEntity().getContentEncoding());
        return res.getEntity().getContent();
    } catch (ClientProtocolException e) {
        e.printStackTrace();
        Log.d(TAG, "Request failed-ClientProtocolException", e);
        //Error connecting to camera
    } catch (IOException e) {
        e.printStackTrace();
        Log.d(TAG, "Request failed-IOException", e);
        //Error connecting to camera
    }

    return null;

}

From source file:org.dataconservancy.archive.impl.fcrepo.ri.MultiThreadedHttpClient.java

public MultiThreadedHttpClient(HttpClientConfig config) {
    this.config = config;
    if (config.getPreemptiveAuthN()) {
        HttpRequestInterceptor interceptor = new HttpRequestInterceptor() {
            @Override//from   w  w w  . jav  a2  s.  c o  m
            public void process(HttpRequest request, 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 no auth scheme has been initialized yet
                if (authState.getAuthScheme() == null) {
                    AuthScope authScope = new AuthScope(targetHost.getHostName(), targetHost.getPort());
                    // Obtain credentials matching the target host
                    Credentials creds = credsProvider.getCredentials(authScope);
                    // If found, generate BasicScheme preemptively
                    if (creds != null) {
                        authState.setAuthScheme(new BasicScheme());
                        authState.setCredentials(creds);
                    }
                }
            }

        };
        addRequestInterceptor(interceptor, 0);
    }

}

From source file:org.dataconservancy.dcs.integration.main.IngestTest.java

@Test
public void sipIngest_db_authentication() throws Exception {
    client.getCredentialsProvider().setCredentials(new AuthScope(AuthScope.ANY_HOST, AuthScope.ANY_PORT),
            new UsernamePasswordCredentials("seadva@gmail.com", hashPassword("password")));
    String agentId = "agent:" + UUID.randomUUID().toString();
    Agent agent = new Agent();
    agent.setFirstName("Kavitha");
    agent.setLastName("Chandrasekar");
    agent.setId(agentId);/*  w ww  .  ja  v a  2s . c  om*/
    agent.setEntityName(agent.getLastName());
    agent.setEntityCreatedTime(new Date());
    agent.setEntityLastUpdatedTime(new Date());

    new RegistryClient(registryUrl).postAgent(agent, "Curator");

    File sipFile = new File(IngestTest.class.getResource("/" + "sampleSip_2.xml").getPath());

    ResearchObject sip = new SeadXstreamStaxModelBuilder()
            .buildSip(new FileInputStream(sipFile.getAbsolutePath()));

    Collection<DcsDeliverableUnit> dus = sip.getDeliverableUnits();
    for (DcsDeliverableUnit du : dus) {
        if (du.getParents() == null || du.getParents().size() == 0) {
            SeadPerson submitter = new SeadPerson();
            submitter.setName(agent.getFirstName() + " " + agent.getLastName());
            submitter.setId(agentId);
            submitter.setIdType("registryId");
            ((SeadDeliverableUnit) du).setSubmitter(submitter);
        }
    }
    sip.setDeliverableUnits(dus);

    new SeadXstreamStaxModelBuilder().buildSip(sip, new FileOutputStream(sipFile.getAbsolutePath()));

    int code = doDeposit(sipFile);
    assertEquals(code, 202);
}

From source file:org.jasig.ssp.security.BasicAuthenticationRestTemplate.java

private HttpClient addAuthentication(DefaultHttpClient clientd, String username, String password) {
    clientd.getCredentialsProvider().setCredentials(new AuthScope(null, -1),
            new UsernamePasswordCredentials(username, password));
    return clientd;
}

From source file:it.larusba.neo4j.jdbc.http.driver.CypherExecutor.java

/**
 * Default constructor./*from   w  w w . ja va  2s . co m*/
 *
 * @param host       Hostname of the Neo4j instance.
 * @param port       HTTP port of the Neo4j instance.
 * @param properties Properties of the url connection.
 * @throws SQLException
 */
public CypherExecutor(String host, Integer port, Properties properties) throws SQLException {
    // Create the http client builder
    HttpClientBuilder builder = HttpClients.custom();
    // Adding authentication to the http client if needed
    if (properties.containsKey("user") && properties.containsKey("password")) {
        CredentialsProvider credsProvider = new BasicCredentialsProvider();
        credsProvider.setCredentials(new AuthScope(host, port), new UsernamePasswordCredentials(
                properties.get("user").toString(), properties.get("password").toString()));
        builder.setDefaultCredentialsProvider(credsProvider);
    }
    // Setting user-agent
    StringBuilder sb = new StringBuilder();
    sb.append("Neo4j JDBC Driver");
    if (properties.containsKey("userAgent")) {
        sb.append(" via ");
        sb.append(properties.getProperty("userAgent"));
    }
    builder.setUserAgent(sb.toString());
    // Create the http client
    this.http = builder.build();

    // Create the url endpoint
    StringBuffer sbEndpoint = new StringBuffer();
    sbEndpoint.append("http://").append(host).append(":").append(port).append("/db/data/transaction");
    this.transactionUrl = sbEndpoint.toString();

    // Setting autocommit
    this.setAutoCommit(Boolean.valueOf(properties.getProperty("autoCommit", "true")));
}

From source file:hu.dolphio.tprttapi.service.TrackingFlushServiceTpImpl.java

public TrackingFlushServiceTpImpl(String dateFrom, String dateTo) {
    this.dateFrom = dateFrom;
    this.dateTo = dateTo;

    targetHost = new HttpHost(propertyReader.getTpHost(), 80, "http");
    credsProvider = new BasicCredentialsProvider();
    Credentials credentials = new UsernamePasswordCredentials(propertyReader.getTpUserName(),
            propertyReader.getTpPassword());
    credsProvider.setCredentials(new AuthScope(targetHost.getHostName(), targetHost.getPort()), credentials);
    config = RequestConfig.custom().setSocketTimeout(propertyReader.getConnectionTimeout())
            .setConnectTimeout(propertyReader.getConnectionTimeout()).build();

    AuthCache authCache = new BasicAuthCache();

    BasicScheme basicAuth = new BasicScheme();
    authCache.put(targetHost, basicAuth);

    clientContext.setAuthCache(authCache);
}

From source file:com.ksc.http.apache.utils.ApacheUtils.java

/**
 * Returns a new instance of AuthScope used for proxy authentication.
 *//* w ww.j  av  a  2 s  .  c  o m*/
private static AuthScope newAuthScope(HttpClientSettings settings) {
    return new AuthScope(settings.getProxyHost(), settings.getProxyPort());
}

From source file:org.opennms.minion.core.impl.ScvEnabledRestClientImpl.java

@Override
public void ping() throws Exception {
    // Setup a client with pre-emptive authentication
    HttpHost target = new HttpHost(url.getHost(), url.getPort(), url.getProtocol());
    CredentialsProvider credsProvider = new BasicCredentialsProvider();
    credsProvider.setCredentials(new AuthScope(target.getHostName(), target.getPort()),
            new UsernamePasswordCredentials(username, password));
    CloseableHttpClient httpclient = HttpClients.custom().setDefaultCredentialsProvider(credsProvider).build();
    try {//from   www  .jav a  2  s  . co  m
        AuthCache authCache = new BasicAuthCache();
        BasicScheme basicAuth = new BasicScheme();
        authCache.put(target, basicAuth);

        HttpClientContext localContext = HttpClientContext.create();
        localContext.setAuthCache(authCache);

        // Issue a simple GET against the Info endpoint
        HttpGet httpget = new HttpGet(url.toExternalForm() + "/rest/info");
        CloseableHttpResponse response = httpclient.execute(target, httpget, localContext);
        response.close();
    } finally {
        httpclient.close();
    }
}

From source file:com.emc.storageos.driver.dellsc.scapi.rest.RestClient.java

/**
 * Instantiates a new Rest client.//from   w w  w. j  av a2  s  .  c  om
 *
 * @param host Host name or IP address of the Dell Storage Manager server.
 * @param port Port the DSM data collector is listening on.
 * @param user The DSM user name to use.
 * @param password The DSM password.
 */
public RestClient(String host, int port, String user, String password) {
    this.baseUrl = String.format("https://%s:%d/api/rest", host, port);

    try {
        // Set up auth handling
        CredentialsProvider credsProvider = new BasicCredentialsProvider();
        credsProvider.setCredentials(new AuthScope(host, port),
                new UsernamePasswordCredentials(user, password));
        AuthCache authCache = new BasicAuthCache();
        BasicScheme basicAuth = new BasicScheme();
        HttpHost target = new HttpHost(host, port, "https");
        authCache.put(target, basicAuth);

        // Set up our context
        httpContext = HttpClientContext.create();
        httpContext.setCookieStore(new BasicCookieStore());
        httpContext.setAuthCache(authCache);

        // Create our HTTPS client
        SSLContext sslContext = SSLContexts.custom().loadTrustMaterial(null, new TrustStrategy() {
            @Override
            public boolean isTrusted(X509Certificate[] arg0, String arg1) throws CertificateException {
                return true;
            }
        }).build();

        SSLConnectionSocketFactory sslSocketFactory = new SSLConnectionSocketFactory(sslContext,
                SSLConnectionSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER);

        this.httpClient = HttpClients.custom().setHostnameVerifier(new AllowAllHostnameVerifier())
                .setDefaultCredentialsProvider(credsProvider).setSSLSocketFactory(sslSocketFactory).build();
    } catch (NoSuchAlgorithmException | KeyStoreException | KeyManagementException e) {
        // Hopefully default SSL handling is set up
        LOG.warn("Failed to configure HTTP handling, falling back to default handler.");
        LOG.debug("Config error: {}", e);
        this.httpClient = HttpClients.createDefault();
    }
}