Example usage for org.apache.http.auth AuthScope ANY_PORT

List of usage examples for org.apache.http.auth AuthScope ANY_PORT

Introduction

In this page you can find the example usage for org.apache.http.auth AuthScope ANY_PORT.

Prototype

int ANY_PORT

To view the source code for org.apache.http.auth AuthScope ANY_PORT.

Click Source Link

Document

The -1 value represents any port.

Usage

From source file:pl.xsolve.verfluchter.rest.RestClient.java

private RestResponse executeRequest(HttpUriRequest request) throws IOException {
    Log.v(TAG, "Final request preperations...");

    HttpParams httpParams = new BasicHttpParams();
    httpParams.setParameter(ConnManagerPNames.MAX_TOTAL_CONNECTIONS, 1);
    httpParams.setParameter(ConnManagerPNames.MAX_CONNECTIONS_PER_ROUTE, new ConnPerRouteBean(1));
    httpParams.setParameter(HttpProtocolParams.USE_EXPECT_CONTINUE, false);
    HttpProtocolParams.setVersion(httpParams, HttpVersion.HTTP_1_1);
    HttpProtocolParams.setContentCharset(httpParams, Charsets.UTF_8.name());

    context = new BasicHttpContext();

    //        if (basicAuthCredentials != null) {
    // ignore that the ssl cert is self signed
    CredentialsProvider credentialsProvider = new BasicCredentialsProvider();
    credentialsProvider.setCredentials(new AuthScope(null, AuthScope.ANY_PORT), // null here means "any host is OK"
            new UsernamePasswordCredentials(basicAuthCredentials.first, basicAuthCredentials.second));
    clientConnectionManager = new ThreadSafeClientConnManager(httpParams, schemeRegistry);

    context.setAttribute("http.auth.credentials-provider", credentialsProvider);
    //        }//from w w  w  . jav a 2  s.  com

    //connection (client has to be created for every new connection)
    httpclient = new DefaultHttpClient(clientConnectionManager, httpParams);

    for (Cookie cookie : cookies) {
        Log.v(TAG, "Using cookie " + cookie.getName() + "=" + cookie.getValue() + "...");
        httpclient.getCookieStore().addCookie(cookie);
    }

    try {
        httpResponse = httpclient.execute(request, context);

        int responseCode = httpResponse.getStatusLine().getStatusCode();
        Header[] headers = httpResponse.getAllHeaders();
        String errorMessage = httpResponse.getStatusLine().getReasonPhrase();

        HttpEntity entity = httpResponse.getEntity();

        Log.v(TAG, "Got cookies:");
        cookies = httpclient.getCookieStore().getCookies();
        if (cookies.isEmpty()) {
            Log.v(TAG, "None");
        } else {
            for (Cookie cookie : cookies) {
                Log.v(TAG, "---- " + cookie.toString());
            }
        }

        String message = null;
        InputStream inStream = entity.getContent();
        message = SoulTools.convertStreamToString(inStream);

        // Closing the input stream will trigger connection release
        entity.consumeContent();
        inStream.close();

        return new RestResponse(responseCode, message, headers, cookies, errorMessage);
    } catch (ClientProtocolException e) {
        Log.v(TAG, "Encountered ClientProtocolException!");
        e.printStackTrace();
    } catch (IOException e) {
        Log.v(TAG, "Encountered IOException!");
        e.printStackTrace();
    } finally {
        //always shutdown the connection manager
        httpclient.getConnectionManager().shutdown();
    }

    Log.v(TAG, "Returning null RestResponse!");
    return null;
}

From source file:org.droidparts.http.worker.HttpURLConnectionWorker.java

private void setupBasicAuth() {
    if (passAuth != null) {
        Authenticator.setDefault(new FixedAuthenticator(passAuth));
        if (!AuthScope.ANY.equals(authScope)) {
            InetAddress host = null;
            if (authScope.getHost() != null) {
                try {
                    host = InetAddress.getByName(authScope.getHost());
                } catch (UnknownHostException e) {
                    L.e("Failed to setup basic auth.");
                    L.d(e);/*from  ww w  . java 2s .  co m*/
                    Authenticator.setDefault(null);
                    return;
                }
            }
            int port = (authScope.getPort() == AuthScope.ANY_PORT) ? 0 : authScope.getPort();
            Authenticator.requestPasswordAuthentication(host, port, null, authScope.getRealm(),
                    authScope.getScheme());
        }
    }
}

From source file:tools.devnull.boteco.client.rest.impl.DefaultRestConfiguration.java

@Override
public RestConfiguration withAuthentication(String user, String password) {
    // Create AuthCache instance
    AuthCache authCache = new BasicAuthCache();
    // Generate BASIC scheme object and add it to the local auth cache
    BasicScheme basicAuth = new BasicScheme();
    CredentialsProvider provider = new BasicCredentialsProvider();

    URI uri = request.getURI();//from   w w w  . j a v  a 2 s .  com
    authCache.put(new HttpHost(uri.getHost(), uri.getPort(), uri.getScheme()), basicAuth);
    provider.setCredentials(new AuthScope(uri.getHost(), AuthScope.ANY_PORT),
            new UsernamePasswordCredentials(user, password));

    this.context.setCredentialsProvider(provider);
    this.context.setAuthCache(authCache);

    return this;
}

From source file:org.eclipse.aether.transport.http.HttpTransporter.java

private static CredentialsProvider toCredentialsProvider(HttpHost server, AuthenticationContext serverAuthCtx,
        HttpHost proxy, AuthenticationContext proxyAuthCtx) {
    CredentialsProvider provider = toCredentialsProvider(server.getHostName(), AuthScope.ANY_PORT,
            serverAuthCtx);//from  ww w.  j  a v a 2s.c o  m
    if (proxy != null) {
        CredentialsProvider p = toCredentialsProvider(proxy.getHostName(), proxy.getPort(), proxyAuthCtx);
        provider = new DemuxCredentialsProvider(provider, p, proxy);
    }
    return provider;
}

From source file:org.megam.api.http.TransportMachinery.java

public static TransportResponse delete(TransportTools nuts) throws ClientProtocolException, IOException {
    DefaultHttpClient httpclient = new DefaultHttpClient();
    HttpDelete httpdel = new HttpDelete(nuts.urlString());

    if (nuts.headers() != null) {
        for (Map.Entry<String, String> headerEntry : nuts.headers().entrySet()) {

            //this if condition is set for twilio Rest API to add credentials to DefaultHTTPClient, conditions met twilio work.
            if (headerEntry.getKey().equalsIgnoreCase("provider")
                    & headerEntry.getValue().equalsIgnoreCase(nuts.headers().get("provider"))) {
                httpclient.getCredentialsProvider().setCredentials(
                        new AuthScope(AuthScope.ANY_HOST, AuthScope.ANY_PORT), new UsernamePasswordCredentials(
                                nuts.headers().get("account_sid"), nuts.headers().get("oauth_token")));
            }/*from  w  ww.  j  a v a 2s.  co  m*/
            //this else part statements for other providers
            else {
                httpdel.addHeader(headerEntry.getKey(), headerEntry.getValue());
            }
        }
    }

    TransportResponse transportResp = null;
    try {
        httpclient.execute(httpdel);
        //transportResp = new TransportResponse(httpResp.getStatusLine(), httpResp.getEntity(), httpResp.getLocale());
    } finally {
        httpdel.releaseConnection();
    }
    return transportResp;

}

From source file:at.general.solutions.android.ical.remote.HttpDownloadThread.java

@Override
public void run() {
    HttpParams params = new BasicHttpParams();
    ConnManagerParams.setMaxTotalConnections(params, 100);
    HttpProtocolParams.setVersion(params, HttpVersion.HTTP_1_1);
    HttpProtocolParams.setUserAgent(params, USER_AGENT);

    SchemeRegistry schemeRegistry = new SchemeRegistry();
    schemeRegistry.register(new Scheme("http", PlainSocketFactory.getSocketFactory(), 80));
    schemeRegistry.register(new Scheme("https", new EasySSLSocketFactory(), 443));

    ClientConnectionManager cm = new ThreadSafeClientConnManager(params, schemeRegistry);
    DefaultHttpClient client = new DefaultHttpClient(cm, params);

    if (useAuthentication) {
        client.getCredentialsProvider().setCredentials(new AuthScope(AuthScope.ANY_HOST, AuthScope.ANY_PORT),
                new UsernamePasswordCredentials(remoteUsername, remotePassword));
    }/*  w ww .ja  va  2  s  . c  o  m*/

    HttpGet get = new HttpGet(remoteUrl);

    try {
        super.sendInitMessage(R.string.downloading);

        HttpResponse response = client.execute(get);
        Log.d(LOG_TAG, response.getStatusLine().getReasonPhrase() + " "
                + isGoodResponse(response.getStatusLine().getStatusCode()));
        if (isGoodResponse(response.getStatusLine().getStatusCode())) {
            HttpEntity entity = response.getEntity();

            InputStream instream = entity.getContent();
            if (instream == null) {
                super.sendErrorMessage(R.string.couldnotConnectToRemoteserver);
                return;
            }
            if (entity.getContentLength() > Integer.MAX_VALUE) {
                super.sendErrorMessage(R.string.remoteFileTooLarge);
                return;
            }
            int i = (int) entity.getContentLength();
            if (i < 0) {
                i = 4096;
            }
            String charset = EntityUtils.getContentCharSet(entity);
            if (charset == null) {
                charset = encoding;
            }
            if (charset == null) {
                charset = HTTP.DEFAULT_CONTENT_CHARSET;
            }
            Reader reader = new InputStreamReader(instream, charset);
            CharArrayBuffer buffer = new CharArrayBuffer(i);

            super.sendMaximumMessage(i);

            try {
                char[] tmp = new char[1024];
                int l;
                while ((l = reader.read(tmp)) != -1) {
                    buffer.append(tmp, 0, l);
                    super.sendProgressMessage(buffer.length());
                }
            } finally {
                reader.close();
            }

            super.sendFinishedMessage(buffer.toString());
        } else {
            int errorMsg = R.string.couldnotConnectToRemoteserver;
            if (isAccessDenied(response.getStatusLine().getStatusCode())) {
                errorMsg = R.string.accessDenied;
            } else if (isFileNotFound(response.getStatusLine().getStatusCode())) {
                errorMsg = R.string.remoteFileNotFound;
            }
            super.sendErrorMessage(errorMsg);
        }
    } catch (UnknownHostException e) {
        super.sendErrorMessage(R.string.unknownHostException, e);
        Log.e(LOG_TAG, "Error occured", e);
    } catch (Throwable e) {
        super.sendErrorMessage(R.string.couldnotConnectToRemoteserver, e);
        Log.e(LOG_TAG, "Error occured", e);
    }

    finally {
        client.getConnectionManager().shutdown();
    }
}

From source file:nl.nn.adapterframework.http.WebServiceNtlmSender.java

public void configure() throws ConfigurationException {
    super.configure();

    HttpParams httpParameters = new BasicHttpParams();
    HttpConnectionParams.setConnectionTimeout(httpParameters, getTimeout());
    HttpConnectionParams.setSoTimeout(httpParameters, getTimeout());
    httpClient = new DefaultHttpClient(connectionManager, httpParameters);
    httpClient.getAuthSchemes().register("NTLM", new NTLMSchemeFactory());
    CredentialFactory cf = new CredentialFactory(getAuthAlias(), getUserName(), getPassword());
    httpClient.getCredentialsProvider().setCredentials(new AuthScope(AuthScope.ANY_HOST, AuthScope.ANY_PORT),
            new NTCredentials(cf.getUsername(), cf.getPassword(), Misc.getHostname(), getAuthDomain()));
    if (StringUtils.isNotEmpty(getProxyHost())) {
        HttpHost proxy = new HttpHost(getProxyHost(), getProxyPort());
        httpClient.getParams().setParameter(ConnRoutePNames.DEFAULT_PROXY, proxy);
    }//from   ww  w .j  a v a 2 s.c o m
}

From source file:eu.diacron.crawlservice.app.Util.java

public static JSONArray getwarcsByCrawlid(String crawlid) {

    JSONArray warcsArray = null;/*from   ww  w  .  ja  v a  2s  . c  o  m*/
    System.out.println("get crawlid");

    CredentialsProvider credsProvider = new BasicCredentialsProvider();
    /*        credsProvider.setCredentials(
     new AuthScope(AuthScope.ANY_HOST, AuthScope.ANY_PORT),
     new UsernamePasswordCredentials("diachron", "7nD9dNGshTtficn"));
     */

    credsProvider.setCredentials(new AuthScope(AuthScope.ANY_HOST, AuthScope.ANY_PORT),
            new UsernamePasswordCredentials(Configuration.REMOTE_CRAWLER_USERNAME,
                    Configuration.REMOTE_CRAWLER_PASS));
    CloseableHttpClient httpclient = HttpClients.custom().setDefaultCredentialsProvider(credsProvider).build();
    try {

        //HttpGet httpget = new HttpGet("http://diachron.hanzoarchives.com/warcs/" + crawlid);
        HttpGet httpget = new HttpGet(Configuration.REMOTE_CRAWLER_URL + crawlid);

        System.out.println("Executing request " + httpget.getRequestLine());
        CloseableHttpResponse response = httpclient.execute(httpget);
        try {
            System.out.println("----------------------------------------");
            System.out.println(response.getStatusLine());
            System.out.println("----------------------------------------");

            String result = "";

            BufferedReader in = new BufferedReader(new InputStreamReader(response.getEntity().getContent()));
            String inputLine;
            while ((inputLine = in.readLine()) != null) {
                System.out.println(inputLine);
                result += inputLine;
            }
            in.close();

            result = result.replace("u'", "'");
            result = result.replace("'", "\"");

            warcsArray = new JSONArray(result);

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

                System.out.println("url to download: " + warcsArray.getString(i));

            }

            EntityUtils.consume(response.getEntity());
        } catch (JSONException ex) {
            Logger.getLogger(Util.class.getName()).log(Level.SEVERE, null, ex);
        } finally {
            response.close();
        }
    } catch (IOException ex) {
        Logger.getLogger(Util.class.getName()).log(Level.SEVERE, null, ex);
    } finally {
        try {
            httpclient.close();
        } catch (IOException ex) {
            Logger.getLogger(Util.class.getName()).log(Level.SEVERE, null, ex);
        }
    }

    return warcsArray;
}

From source file:ca.sqlpower.wabit.enterprise.client.WabitClientSession.java

public static HttpClient createHttpClient(SPServerInfo serviceInfo) {
    HttpParams params = new BasicHttpParams();
    HttpConnectionParams.setConnectionTimeout(params, 2000);
    DefaultHttpClient httpClient = new DefaultHttpClient(params);
    httpClient.setCookieStore(cookieStore);
    httpClient.getCredentialsProvider().setCredentials(
            new AuthScope(serviceInfo.getServerAddress(), AuthScope.ANY_PORT),
            new UsernamePasswordCredentials(serviceInfo.getUsername(), serviceInfo.getPassword()));
    return httpClient;
}