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.betfair.testing.utils.cougar.manager.HttpPageManager.java

public int getPage(HttpPageBean bean) {

    // Get bean properties
    String requestedProtocol = bean.getProtocol();
    String requestedHost = bean.getHost();
    int requestedPort = bean.getPort();
    String requestedLink = bean.getLink();
    String username = bean.getAuthusername();
    String password = bean.getAuthpassword();

    final SSLSocketFactory sf = new SSLSocketFactory(createEasySSLContext(),
            SSLSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER);
    Scheme https = new Scheme("https", 9999, sf);

    // Set up httpClient to use given auth details and protocol
    DefaultHttpClient client = new DefaultHttpClient();
    client.getConnectionManager().getSchemeRegistry().register(https);
    client.getCredentialsProvider().setCredentials(new AuthScope("localhost", AuthScope.ANY_PORT),
            new UsernamePasswordCredentials(username, password));

    int status = -1;

    InputStream inputStream = null;
    // Make the request
    try {//from   w w  w .  j  a  v  a 2  s.co  m
        final HttpGet httpget = new HttpGet(
                URIUtils.createURI(requestedProtocol, requestedHost, requestedPort, requestedLink, null, null));
        final HttpResponse httpResponse = client.execute(httpget);
        inputStream = httpResponse.getEntity().getContent();
        status = httpResponse.getStatusLine().getStatusCode();

        if (status == HttpStatus.SC_OK) {
            bean.setPageLoaded(true);

            byte[] buffer = new byte[(int) httpResponse.getEntity().getContentLength()];
            int read;
            int count = 0;
            while ((read = inputStream.read()) != -1) {
                buffer[count] = (byte) read;
                count++;
            }
            bean.setPageText(new String(buffer, "UTF-8"));
            bean.setBuffer(buffer);
        }
    } catch (IOException e1) {
        return -1;
    } catch (URISyntaxException e) {
        return -1;
    } finally {
        if (inputStream != null) {
            try {
                inputStream.close();
            } catch (IOException e) {
                // ignore
            }
        }
    }

    return status;
}

From source file:io.getlime.push.service.fcm.FcmClient.java

/**
 * Set information about proxy.//w  w w  .  j a  v a 2  s  .  c o  m
 * @param host Proxy host URL.
 * @param port Proxy port.
 * @param username Proxy username, use 'null' for proxy without authentication.
 * @param password Proxy user password, ignored in case username is 'null'
 */
public void setProxy(String host, int port, String username, String password) {

    HttpAsyncClientBuilder clientBuilder = HttpAsyncClientBuilder.create();
    clientBuilder.useSystemProperties();
    clientBuilder.setProxy(new HttpHost(host, port));

    if (username != null) {
        CredentialsProvider credsProvider = new BasicCredentialsProvider();
        UsernamePasswordCredentials user = new UsernamePasswordCredentials(username, password);
        credsProvider.setCredentials(new AuthScope(host, port), user);
        clientBuilder.setDefaultCredentialsProvider(credsProvider);
        clientBuilder.setProxyAuthenticationStrategy(new ProxyAuthenticationStrategy());
    }

    CloseableHttpAsyncClient client = clientBuilder.build();

    HttpComponentsAsyncClientHttpRequestFactory factory = new HttpComponentsAsyncClientHttpRequestFactory();
    factory.setAsyncClient(client);

    restTemplate.setAsyncRequestFactory(factory);
}

From source file:com.vuze.android.remote.rpc.RestJsonClient.java

public static Map<?, ?> connect(String id, String url, Map<?, ?> jsonPost, Header[] headers,
        UsernamePasswordCredentials creds, boolean sendGzip) throws RPCException {
    long readTime = 0;
    long connSetupTime = 0;
    long connTime = 0;
    int bytesRead = 0;
    if (DEBUG_DETAILED) {
        Log.d(TAG, id + "] Execute " + url);
    }//www.j a  va2s  .c om
    long now = System.currentTimeMillis();
    long then;

    Map<?, ?> json = Collections.EMPTY_MAP;

    try {

        URI uri = new URI(url);
        int port = uri.getPort();

        BasicHttpParams basicHttpParams = new BasicHttpParams();
        HttpProtocolParams.setUserAgent(basicHttpParams, "Vuze Android Remote");

        DefaultHttpClient httpclient;
        if ("https".equals(uri.getScheme())) {
            httpclient = MySSLSocketFactory.getNewHttpClient(port);
        } else {
            httpclient = new DefaultHttpClient(basicHttpParams);
        }

        //AndroidHttpClient.newInstance("Vuze Android Remote");

        // This doesn't set the "Authorization" header!?
        httpclient.getCredentialsProvider().setCredentials(new AuthScope(null, -1), creds);

        // Prepare a request object
        HttpRequestBase httpRequest = jsonPost == null ? new HttpGet(uri) : new HttpPost(uri); // IllegalArgumentException

        if (creds != null) {
            byte[] toEncode = (creds.getUserName() + ":" + creds.getPassword()).getBytes();
            String encoding = Base64Encode.encodeToString(toEncode, 0, toEncode.length);
            httpRequest.setHeader("Authorization", "Basic " + encoding);
        }

        if (jsonPost != null) {
            HttpPost post = (HttpPost) httpRequest;
            String postString = JSONUtils.encodeToJSON(jsonPost);
            if (AndroidUtils.DEBUG_RPC) {
                Log.d(TAG, id + "]  Post: " + postString);
            }

            AbstractHttpEntity entity = (sendGzip && Build.VERSION.SDK_INT >= Build.VERSION_CODES.FROYO)
                    ? getCompressedEntity(postString)
                    : new StringEntity(postString);
            post.setEntity(entity);

            post.setHeader("Accept", "application/json");
            post.setHeader("Content-type", "application/x-www-form-urlencoded; charset=UTF-8");
        }

        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.FROYO) {
            setupRequestFroyo(httpRequest);
        }

        if (headers != null) {
            for (Header header : headers) {
                httpRequest.setHeader(header);
            }
        }

        // Execute the request
        HttpResponse response;

        then = System.currentTimeMillis();
        if (AndroidUtils.DEBUG_RPC) {
            connSetupTime = (then - now);
            now = then;
        }

        httpclient.setHttpRequestRetryHandler(new HttpRequestRetryHandler() {
            @Override
            public boolean retryRequest(IOException e, int i, HttpContext httpContext) {
                if (i < 2) {
                    return true;
                }
                return false;
            }
        });
        response = httpclient.execute(httpRequest);

        then = System.currentTimeMillis();
        if (AndroidUtils.DEBUG_RPC) {
            connTime = (then - now);
            now = then;
        }

        HttpEntity entity = response.getEntity();

        // XXX STATUSCODE!

        StatusLine statusLine = response.getStatusLine();
        if (AndroidUtils.DEBUG_RPC) {
            Log.d(TAG, "StatusCode: " + statusLine.getStatusCode());
        }

        if (entity != null) {

            long contentLength = entity.getContentLength();
            if (contentLength >= Integer.MAX_VALUE - 2) {
                throw new RPCException("JSON response too large");
            }

            // A Simple JSON Response Read
            InputStream instream = (Build.VERSION.SDK_INT >= Build.VERSION_CODES.FROYO)
                    ? getUngzippedContent(entity)
                    : entity.getContent();
            InputStreamReader isr = new InputStreamReader(instream, "utf8");

            StringBuilder sb = null;
            BufferedReader br = null;
            // JSONReader is 10x slower, plus I get more OOM errors.. :(
            //            final boolean useStringBuffer = contentLength > (4 * 1024 * 1024) ? false
            //                  : DEFAULT_USE_STRINGBUFFER;
            final boolean useStringBuffer = DEFAULT_USE_STRINGBUFFER;

            if (useStringBuffer) {
                // Setting capacity saves StringBuffer from going through many
                // enlargeBuffers, and hopefully allows toString to not make a copy
                sb = new StringBuilder(contentLength > 512 ? (int) contentLength + 2 : 512);
            } else {
                if (AndroidUtils.DEBUG_RPC) {
                    Log.d(TAG, "Using BR. ContentLength = " + contentLength);
                }
                br = new BufferedReader(isr, 8192);
                br.mark(32767);
            }

            try {

                // 9775 files on Nexus 7 (~2,258,731 bytes)
                // fastjson 1.1.46 (String)       :  527- 624ms
                // fastjson 1.1.39 (String)       :  924-1054ms
                // fastjson 1.1.39 (StringBuilder): 1227-1463ms
                // fastjson 1.1.39 (BR)           : 2233-2260ms
                // fastjson 1.1.39 (isr)          :      2312ms
                // GSON 2.2.4 (String)            : 1539-1760ms
                // GSON 2.2.4 (BufferedReader)    : 2646-3060ms
                // JSON-SMART 1.3.1 (String)      :  572- 744ms (OOMs more often than fastjson)

                if (useStringBuffer) {
                    char c[] = new char[8192];
                    while (true) {
                        int read = isr.read(c);
                        if (read < 0) {
                            break;
                        }
                        sb.append(c, 0, read);
                    }

                    if (AndroidUtils.DEBUG_RPC) {
                        then = System.currentTimeMillis();
                        if (DEBUG_DETAILED) {
                            if (sb.length() > 2000) {
                                Log.d(TAG, id + "] " + sb.substring(0, 2000) + "...");
                            } else {
                                Log.d(TAG, id + "] " + sb.toString());
                            }
                        }
                        bytesRead = sb.length();
                        readTime = (then - now);
                        now = then;
                    }

                    json = JSONUtils.decodeJSON(sb.toString());
                    //json = JSONUtilsGSON.decodeJSON(sb.toString());
                } else {

                    //json = JSONUtils.decodeJSON(isr);
                    json = JSONUtils.decodeJSON(br);
                    //json = JSONUtilsGSON.decodeJSON(br);
                }

            } catch (Exception pe) {

                //               StatusLine statusLine = response.getStatusLine();
                if (statusLine != null && statusLine.getStatusCode() == 409) {
                    throw new RPCException(response, "409");
                }

                try {
                    String line;
                    if (useStringBuffer) {
                        line = sb.subSequence(0, Math.min(128, sb.length())).toString();
                    } else {
                        br.reset();
                        line = br.readLine().trim();
                    }

                    isr.close();

                    if (AndroidUtils.DEBUG_RPC) {
                        Log.d(TAG, id + "]line: " + line);
                    }
                    Header contentType = entity.getContentType();
                    if (line.startsWith("<") || line.contains("<html")
                            || (contentType != null && contentType.getValue().startsWith("text/html"))) {
                        // TODO: use android strings.xml
                        throw new RPCException(response,
                                "Could not retrieve remote client location information.  The most common cause is being on a guest wifi that requires login before using the internet.");
                    }
                } catch (IOException ignore) {

                }

                Log.e(TAG, id, pe);
                if (statusLine != null) {
                    String msg = statusLine.getStatusCode() + ": " + statusLine.getReasonPhrase() + "\n"
                            + pe.getMessage();
                    throw new RPCException(msg, pe);
                }
                throw new RPCException(pe);
            } finally {
                closeOnNewThread(useStringBuffer ? isr : br);
            }

            if (AndroidUtils.DEBUG_RPC) {
                //               Log.d(TAG, id + "]JSON Result: " + json);
            }

        }
    } catch (RPCException e) {
        throw e;
    } catch (Throwable e) {
        Log.e(TAG, id, e);
        throw new RPCException(e);
    }

    if (AndroidUtils.DEBUG_RPC) {
        then = System.currentTimeMillis();
        Log.d(TAG, id + "] conn " + connSetupTime + "/" + connTime + "ms. Read " + bytesRead + " in " + readTime
                + "ms, parsed in " + (then - now) + "ms");
    }
    return json;
}

From source file:org.jfrog.build.client.PreemptiveHttpClient.java

public void setProxyConfiguration(String host, int port, String username, String password) {
    HttpHost proxy = new HttpHost(host, port);
    httpClient.getParams().setParameter(ConnRoutePNames.DEFAULT_PROXY, proxy);
    if (username != null) {
        httpClient.getCredentialsProvider().setCredentials(new AuthScope(host, port),
                new UsernamePasswordCredentials(username, password));
    }//  w  ww.  ja va 2s .c  o  m
}

From source file:org.dasein.security.joyent.AuthClientFactory.java

@Override
public @Nonnull HttpClient getClient(String endpoint) throws CloudException, InternalException {

    if (endpoint == null) {
        throw new CloudException("No cloud endpoint was defined");
    }/*from www. j a v  a 2 s . co  m*/

    boolean ssl = endpoint.startsWith("https");
    int targetPort;
    URI uri;

    try {
        uri = new URI(endpoint);
        targetPort = uri.getPort();
        if (targetPort < 1) {
            targetPort = (ssl ? 443 : 80);
        }
    } catch (URISyntaxException e) {
        throw new CloudException(e);
    }
    HttpHost targetHost = new HttpHost(uri.getHost(), targetPort, uri.getScheme());

    DefaultHttpClient client = (DefaultHttpClient) super.getClient(endpoint);

    try {
        String userName = new String(getProviderContext().getAccessPublic(), "utf-8");
        String password = new String(getProviderContext().getAccessPrivate(), "utf-8");

        client.getCredentialsProvider().setCredentials(
                new AuthScope(targetHost.getHostName(), targetHost.getPort()),
                new UsernamePasswordCredentials(userName, password));
    } catch (UnsupportedEncodingException e) {
        throw new InternalException(e);
    }
    return client;
}

From source file:org.dspace.identifier.ezid.EZIDRequest.java

/**
 * Prepare a context for requests concerning a specific identifier or
 * authority prefix./*w  w  w . j ava2  s . c o  m*/
 *
 * @param scheme URL scheme for access to the EZID service.
 * @param host Host name for access to the EZID service.
 * @param authority DOI authority prefix, e.g. "10.5072/FK2".
 * @param username an EZID user identity.
 * @param password user's password, or {@code null} for none.
 * @throws URISyntaxException if host or authority is bad.
 */
EZIDRequest(String scheme, String host, String authority, String username, String password)
        throws URISyntaxException {
    this.scheme = scheme;

    this.host = host;

    if (authority.charAt(authority.length() - 1) == '/') {
        this.authority = authority.substring(0, authority.length() - 1);
    } else {
        this.authority = authority;
    }

    client = new DefaultHttpClient();
    if (null != username) {
        URI uri = new URI(scheme, host, null, null);
        client.getCredentialsProvider().setCredentials(new AuthScope(uri.getHost(), uri.getPort()),
                new UsernamePasswordCredentials(username, password));
    }
}

From source file:org.jboss.as.test.integration.web.security.WebSecurityBASICTestCase.java

protected void makeCall(String user, String pass, int expectedStatusCode) throws Exception {
    DefaultHttpClient httpclient = new DefaultHttpClient();
    try {/*  w ww  .  ja va 2  s.c o  m*/
        httpclient.getCredentialsProvider().setCredentials(new AuthScope("localhost", 8080),
                new UsernamePasswordCredentials(user, pass));

        HttpGet httpget = new HttpGet(URL);

        System.out.println("executing request" + httpget.getRequestLine());
        HttpResponse response = httpclient.execute(httpget);
        HttpEntity entity = response.getEntity();

        System.out.println("----------------------------------------");
        StatusLine statusLine = response.getStatusLine();
        System.out.println(statusLine);
        if (entity != null) {
            System.out.println("Response content length: " + entity.getContentLength());
        }
        assertEquals(expectedStatusCode, statusLine.getStatusCode());
        EntityUtils.consume(entity);
    } finally {
        // When HttpClient instance is no longer needed,
        // shut down the connection manager to ensure
        // immediate deallocation of all system resources
        httpclient.getConnectionManager().shutdown();
    }
}

From source file:br.cefetrj.sagitarii.teapot.comm.WebClient.java

public String doGet(String action, String parameter) throws Exception {
    String resposta = "SEM_RESPOSTA";
    String mhpHost = gf.getHostURL();
    String url = mhpHost + "/" + action + "?" + parameter;

    DefaultHttpClient httpClient = new DefaultHttpClient();

    if (gf.useProxy()) {
        if (gf.getProxyInfo() != null) {
            HttpHost httpproxy = new HttpHost(gf.getProxyInfo().getHost(), gf.getProxyInfo().getPort());
            httpClient.getCredentialsProvider().setCredentials(
                    new AuthScope(gf.getProxyInfo().getHost(), gf.getProxyInfo().getPort()),
                    new UsernamePasswordCredentials(gf.getProxyInfo().getUser(),
                            gf.getProxyInfo().getPassword()));
            httpClient.getParams().setParameter(ConnRoutePNames.DEFAULT_PROXY, httpproxy);
        }// w w w  . j  ava2  s  .  c om
    }

    httpClient.getParams().setParameter(CoreProtocolPNames.HTTP_CONTENT_CHARSET, "UTF-8");

    HttpGet getRequest = new HttpGet(url);
    getRequest.addHeader("accept", "application/json");
    getRequest.addHeader("Content-Type", "plain/text; charset=utf-8");

    HttpResponse response = httpClient.execute(getRequest);
    response.setHeader("Content-Type", "plain/text; charset=UTF-8");

    int stCode = response.getStatusLine().getStatusCode();
    if (stCode != 200) {
        System.out.println("Sagitarii nao recebeu meu anuncio. Codigo de erro " + stCode);
        System.out.println(url);
    } else {
        HttpEntity entity = response.getEntity();
        InputStreamReader isr = new InputStreamReader(entity.getContent(), "UTF-8");
        resposta = convertStreamToString(isr);
        Charset.forName("UTF-8").encode(resposta);
        httpClient.getConnectionManager().shutdown();
        isr.close();
    }

    return resposta;
}

From source file:com.sulacosoft.bitcoindconnector4j.BitcoindApiHandler.java

public BitcoindApiHandler(String host, int port, String protocol, String uri, String username,
        String password) {/*w  ww  .  j a  va 2s. c o  m*/
    this.uri = uri;

    httpClient = HttpClients.createDefault();
    targetHost = new HttpHost(host, port, protocol);
    CredentialsProvider credsProvider = new BasicCredentialsProvider();
    credsProvider.setCredentials(new AuthScope(targetHost.getHostName(), targetHost.getPort()),
            new UsernamePasswordCredentials(username, password));

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

    context = HttpClientContext.create();
    context.setCredentialsProvider(credsProvider);
    context.setAuthCache(authCache);
}

From source file:io.n7.calendar.caldav.BaseTestCase.java

public HttpClient createHttpClient() {
    HttpClient http = new HttpClient();

    Credentials credentials = new UsernamePasswordCredentials(caldavCredential.user, caldavCredential.password);
    http.getState().setCredentials(new AuthScope(this.getCalDAVServerHost(), this.getCalDAVServerPort()),
            credentials);//from   ww w .j a  v  a  2s  . c  o  m
    http.getParams().setAuthenticationPreemptive(true);
    return http;
}