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.mycontroller.standalone.restclient.RestFactory.java

public T createAPI(URI uri, String userName, String password) {
    CloseableHttpClient httpclient = HttpClientBuilder.create().build();
    HttpHost targetHost = new HttpHost(uri.getHost(), uri.getPort());
    CredentialsProvider credsProvider = new BasicCredentialsProvider();
    credsProvider.setCredentials(new AuthScope(targetHost.getHostName(), targetHost.getPort()),
            new UsernamePasswordCredentials(userName, password));
    // 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 context = HttpClientContext.create();
    context.setCredentialsProvider(credsProvider);
    context.setAuthCache(authCache);//from   w  w  w  . java 2 s  . co  m
    ApacheHttpClient4Engine engine = new ApacheHttpClient4Engine(httpclient, context);

    ResteasyClient client = new ResteasyClientBuilder().httpEngine(engine).build();
    client.register(JacksonJaxbJsonProvider.class);
    client.register(RequestLogger.class);
    client.register(ResponseLogger.class);
    ProxyBuilder<T> proxyBuilder = client.target(uri).proxyBuilder(proxyClazz);
    return proxyBuilder.build();
}

From source file:pl.psnc.synat.wrdz.zmd.download.adapters.HttpDownloadAdapter.java

/**
 * Constructs new HTTP adapter using provided information.
 * /*from   w w w. jav  a2s .c om*/
 * @param connectionInfo
 *            connection information for SFTP protocol.
 * @param cacheHome
 *            cache root folder.
 */
public HttpDownloadAdapter(ConnectionInformation connectionInfo, String cacheHome) {
    super(connectionInfo, cacheHome);
    authScope = new AuthScope(connectionInfo.getHost(),
            connectionInfo.getPort() == null ? -1 : connectionInfo.getPort());
    String password = connectionInfo.getPassword();
    if (password != null && !password.isEmpty()) {
        usernamePasswordCredentials = new UsernamePasswordCredentials(connectionInfo.getUsername(), password);
    } else {
        usernamePasswordCredentials = null;
    }
}

From source file:com.restfiddle.handler.http.auth.BasicAuthHandler.java

/**
 * TODO : Not used anywhere right now.//from  w w  w.  j  a  v a  2  s .  c o  m
 */
public CredentialsProvider prepareBasicAuth(String userName, String password) {
    CredentialsProvider provider = new BasicCredentialsProvider();
    UsernamePasswordCredentials credentials = new UsernamePasswordCredentials(userName, userName);
    provider.setCredentials(new AuthScope(AuthScope.ANY_HOST, AuthScope.ANY_PORT), credentials);

    return provider;
}

From source file:org.altchain.neo4j.bitcoind.BitcoinD.java

private JSONObject invokeRPC(String JSONRequestString) throws BitcoindNotRunningException {
    DefaultHttpClient httpclient = new DefaultHttpClient();

    JSONObject responseJsonObj = null;/*from  ww  w .  j ava2s .  c  o m*/

    try {

        httpclient.getCredentialsProvider().setCredentials(new AuthScope(bitcoindHost, bitcoindPort),
                new UsernamePasswordCredentials("generated_by_armory",
                        "6nkugwdEacEAgqjbCvvVyrgXcZj5Cxr38vTbZ513QJrf"));

        StringEntity myEntity = new StringEntity(JSONRequestString);
        logger.debug("JSON Request Object: " + JSONRequestString);

        HttpPost httppost = new HttpPost("http://" + this.bitcoindHost + ":" + this.bitcoindPort);
        httppost.setEntity(myEntity);

        logger.debug("executing request: " + httppost.getRequestLine());

        HttpEntity entity = null;

        try {

            HttpResponse response = httpclient.execute(httppost);
            entity = response.getEntity();

            logger.debug("HTTP response: " + response.getStatusLine());

        } catch (Exception e) {
            logger.error("CANNOT CONNECT TO BITCOIND.  IS BITCOIN RUNNING?");
            throw new BitcoindNotRunningException();
        }

        if (entity != null) {

            logger.debug("Response content length: " + entity.getContentLength());

        }

        JSONParser parser = new JSONParser();
        responseJsonObj = (JSONObject) parser.parse(EntityUtils.toString(entity));

    } catch (ClientProtocolException e) {
        e.printStackTrace();
    } catch (IOException e) {
        e.printStackTrace();
    } catch (ParseException e) {
        e.printStackTrace();
    } catch (org.json.simple.parser.ParseException e) {
        e.printStackTrace();
    } finally {

        httpclient.getConnectionManager().shutdown();

    }

    return responseJsonObj;

}

From source file:org.syncope.client.http.PreemptiveAuthHttpRequestFactory.java

public AuthScope getAuthScope() {
    return new AuthScope(targetHost.getHostName(), targetHost.getPort());
}

From source file:brooklyn.networking.cloudstack.HttpUtil.java

public static HttpClient createHttpClient(URI uri, Optional<Credentials> credentials) {
    final DefaultHttpClient httpClient = new DefaultHttpClient();

    // TODO if supplier returns null, we may wish to defer initialization until url available?
    if (uri != null && "https".equalsIgnoreCase(uri.getScheme())) {
        try {//  w w w.j a  va  2s . c  om
            int port = (uri.getPort() >= 0) ? uri.getPort() : 443;
            SSLSocketFactory socketFactory = new SSLSocketFactory(new TrustAllStrategy(),
                    SSLSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER);
            Scheme sch = new Scheme("https", port, socketFactory);
            httpClient.getConnectionManager().getSchemeRegistry().register(sch);
        } catch (Exception e) {
            LOG.warn("Error in HTTP Feed of {}, setting trust for uri {}", uri);
            throw Exceptions.propagate(e);
        }
    }

    // Set credentials
    if (uri != null && credentials.isPresent()) {
        String hostname = uri.getHost();
        int port = uri.getPort();
        httpClient.getCredentialsProvider().setCredentials(new AuthScope(hostname, port), credentials.get());
    }

    return httpClient;
}

From source file:org.datacleaner.util.http.HttpBasicMonitorHttpClient.java

public HttpBasicMonitorHttpClient(HttpClient httpClient, String hostname, int port, String username,
        String password) {/*from w  w  w. j  av  a  2s.  co m*/
    _httpClient = (DefaultHttpClient) httpClient;

    final CredentialsProvider credentialsProvider = _httpClient.getCredentialsProvider();

    final UsernamePasswordCredentials credentials = new UsernamePasswordCredentials(username, password);

    final List<String> authpref = new ArrayList<String>();
    authpref.add(AuthPolicy.BASIC);
    authpref.add(AuthPolicy.DIGEST);
    _httpClient.getParams().setParameter(AuthPNames.PROXY_AUTH_PREF, authpref);

    credentialsProvider.setCredentials(new AuthScope(hostname, port), credentials);
}

From source file:org.springframework.social.reddit.connect.RedditOAuth2Template.java

private String getAccessToken(String code, String redirectUrl)
        throws UnsupportedEncodingException, IOException {
    DefaultHttpClient httpclient = new DefaultHttpClient();
    try {//from   w  w  w .j a va2  s.  co m

        //Reddit Requires clientId and clientSecret be attached via basic auth
        httpclient.getCredentialsProvider().setCredentials(new AuthScope("ssl.reddit.com", 443),
                new UsernamePasswordCredentials(clientId, clientSecret));

        HttpPost httppost = new HttpPost(RedditPaths.OAUTH_TOKEN_URL);

        List<NameValuePair> nvps = new ArrayList<NameValuePair>(3);
        nvps.add(new BasicNameValuePair("code", code));
        nvps.add(new BasicNameValuePair("grant_type", "authorization_code"));
        nvps.add(new BasicNameValuePair("redirect_uri", redirectUrl));

        httppost.setEntity(new UrlEncodedFormEntity(nvps));
        httppost.addHeader("User-Agent", "a unique user agent");
        httppost.setHeader("Accept", "any;");

        HttpResponse request = httpclient.execute(httppost);
        HttpEntity response = request.getEntity(); // Reddit response containing accessToken

        if (response != null) {
            BufferedReader br = new BufferedReader(new InputStreamReader(response.getContent()));
            StringBuilder content = new StringBuilder();
            String line;
            while (null != (line = br.readLine())) {
                content.append(line);
            }
            System.out.println(content.toString());
            Map json = (Map) JSONValue.parse(content.toString());
            if (json.containsKey("access_token")) {
                return (String) (json.get("access_token"));
            }
        }
        EntityUtils.consume(response);
    } finally {
        httpclient.getConnectionManager().shutdown(); //cleanup
    }
    return null;
}

From source file:com.kms.core.io.HttpUtil_In.java

public static CloseableHttpClient getHttpClient(final String SoeID, final String Password, final int type) {
    CloseableHttpClient httpclient;//ww  w. j  a  v  a 2s. co  m

    // Auth Scheme 
    final Registry<AuthSchemeProvider> authSchemeRegistry = RegistryBuilder.<AuthSchemeProvider>create()
            .register(AuthSchemes.NTLM, new NTLMSchemeFactory())
            .register(AuthSchemes.BASIC, new BasicSchemeFactory())
            .register(AuthSchemes.DIGEST, new DigestSchemeFactory())
            .register(AuthSchemes.SPNEGO, new SPNegoSchemeFactory())
            .register(AuthSchemes.KERBEROS, new KerberosSchemeFactory()).build();

    // NTLM  
    final CredentialsProvider credsProvider = new BasicCredentialsProvider();
    credsProvider.setCredentials(new AuthScope(AuthScope.ANY_HOST, AuthScope.ANY_PORT), //AuthScope("localhost", 8080),
            new NTCredentials(SoeID, Password, "dummy", "APAC"));
    //new NTCredentials( SoeID, Password,"APACKR081WV058", "APAC" ));

    // ------------- cookie start ------------------------
    // Auction   
    // Create a local instance of cookie store
    final CookieStore cookieStore = new BasicCookieStore();

    //       Cookie  .
    final BasicClientCookie cookie = new BasicClientCookie("songdal_view", "YES");
    cookie.setVersion(0);
    cookie.setDomain(".scourt.go.kr");
    cookie.setPath("/");
    cookieStore.addCookie(cookie);

    // ------------- cookie end ------------------------

    if (type == 0) // TYPE.AuctionInput
    {
        // HTTP Client 
        httpclient = HttpClients.custom().setDefaultAuthSchemeRegistry(authSchemeRegistry)
                .setDefaultCredentialsProvider(credsProvider).build();
    } else // SagunInput
    {
        // HTTP Client 
        httpclient = HttpClients.custom().setDefaultAuthSchemeRegistry(authSchemeRegistry)
                .setDefaultCredentialsProvider(credsProvider).setDefaultCookieStore(cookieStore).build();
    }

    return httpclient;
}

From source file:com.coroptis.coidi.rp.services.impl.HttpServiceImpl.java

public HttpServiceImpl(final RpConfigurationService configurationService) {
    httpClient = new DefaultHttpClient();
    String proxyServer = configurationService.getProxyServer();
    if (!Strings.isNullOrEmpty(proxyServer)) {
        Integer proxyPort = configurationService.getProxyPort();
        if (proxyPort != null && proxyPort > 0) {
            HttpHost proxy = new HttpHost(proxyServer, proxyPort);
            httpClient.getParams().setParameter(ConnRoutePNames.DEFAULT_PROXY, proxy);

            String userName = configurationService.getProxyUsername();
            String password = configurationService.getProxyPassword();
            if (userName != null) {
                httpClient.getCredentialsProvider().setCredentials(new AuthScope(proxyServer, proxyPort),
                        new UsernamePasswordCredentials(userName, password));
            }//  w w w .ja v  a  2s. co  m
        }
    }
    Preconditions.checkNotNull(httpClient, "httpClient");
}