Example usage for org.apache.http.auth.params AuthPNames PROXY_AUTH_PREF

List of usage examples for org.apache.http.auth.params AuthPNames PROXY_AUTH_PREF

Introduction

In this page you can find the example usage for org.apache.http.auth.params AuthPNames PROXY_AUTH_PREF.

Prototype

String PROXY_AUTH_PREF

To view the source code for org.apache.http.auth.params AuthPNames PROXY_AUTH_PREF.

Click Source Link

Document

Defines the order of preference for supported org.apache.http.auth.AuthScheme s when authenticating with the proxy host.

Usage

From source file:org.xmetdb.rest.protocol.attachments.CallableAttachmentImporter.java

protected HttpClient createHTTPClient(String hostName, int port) {
    DefaultHttpClient cli = new DefaultHttpClient();
    List<String> authpref = new ArrayList<String>();
    authpref.add(AuthPolicy.BASIC);/*ww  w.j a v  a  2  s. co  m*/
    cli.getParams().setParameter(AuthPNames.PROXY_AUTH_PREF, authpref);
    cli.getCredentialsProvider().setCredentials(new AuthScope(hostName, port), creds);
    ((DefaultHttpClient) cli).addRequestInterceptor(new HttpRequestInterceptor() {
        @Override
        public void process(HttpRequest request, HttpContext context) throws HttpException, IOException {
            //if (ssoToken != null)
            //request.addHeader("subjectid",ssoToken.getToken());
        }
    });
    return cli;
}

From source file:com.android.tools.idea.sdk.remote.internal.UrlOpener.java

@NonNull
private static Pair<InputStream, HttpResponse> openWithHttpClient(@NonNull String url,
        @NonNull ITaskMonitor monitor, Header[] inHeaders) throws IOException, CanceledByUserException {
    UserCredentials result = null;/*from  w w w.  jav a2  s.  c  om*/
    String realm = null;

    HttpParams params = new BasicHttpParams();
    HttpConnectionParams.setConnectionTimeout(params, sConnectionTimeoutMs);
    HttpConnectionParams.setSoTimeout(params, sSocketTimeoutMs);

    // use the simple one
    final DefaultHttpClient httpClient = new DefaultHttpClient(params);

    // create local execution context
    HttpContext localContext = new BasicHttpContext();
    final HttpGet httpGet = new HttpGet(url);
    if (inHeaders != null) {
        for (Header header : inHeaders) {
            httpGet.addHeader(header);
        }
    }

    // retrieve local java configured network in case there is the need to
    // authenticate a proxy
    ProxySelectorRoutePlanner routePlanner = new ProxySelectorRoutePlanner(
            httpClient.getConnectionManager().getSchemeRegistry(), ProxySelector.getDefault());
    httpClient.setRoutePlanner(routePlanner);

    // Set preference order for authentication options.
    // In particular, we don't add AuthPolicy.SPNEGO, which is given preference over NTLM in
    // servers that support both, as it is more secure. However, we don't seem to handle it
    // very well, so we leave it off the list.
    // See http://hc.apache.org/httpcomponents-client-ga/tutorial/html/authentication.html for
    // more info.
    List<String> authpref = new ArrayList<String>();
    authpref.add(AuthPolicy.BASIC);
    authpref.add(AuthPolicy.DIGEST);
    authpref.add(AuthPolicy.NTLM);
    httpClient.getParams().setParameter(AuthPNames.PROXY_AUTH_PREF, authpref);
    httpClient.getParams().setParameter(AuthPNames.TARGET_AUTH_PREF, authpref);

    if (DEBUG) {
        try {
            URI uri = new URI(url);
            ProxySelector sel = routePlanner.getProxySelector();
            if (sel != null && uri.getScheme().startsWith("httP")) { //$NON-NLS-1$
                List<Proxy> list = sel.select(uri);
                System.out.printf("SdkLib.UrlOpener:\n  Connect to: %s\n  Proxy List: %s\n", //$NON-NLS-1$
                        url, list == null ? "(null)" : Arrays.toString(list.toArray()));//$NON-NLS-1$
            }
        } catch (Exception e) {
            System.out.printf("SdkLib.UrlOpener: Failed to get proxy info for %s: %s\n", //$NON-NLS-1$
                    url, e.toString());
        }
    }

    boolean trying = true;
    // loop while the response is being fetched
    while (trying) {
        // connect and get status code
        HttpResponse response = httpClient.execute(httpGet, localContext);
        int statusCode = response.getStatusLine().getStatusCode();

        if (DEBUG) {
            System.out.printf("  Status: %d\n", statusCode); //$NON-NLS-1$
        }

        // check whether any authentication is required
        AuthState authenticationState = null;
        if (statusCode == HttpStatus.SC_UNAUTHORIZED) {
            // Target host authentication required
            authenticationState = (AuthState) localContext.getAttribute(ClientContext.TARGET_AUTH_STATE);
        }
        if (statusCode == HttpStatus.SC_PROXY_AUTHENTICATION_REQUIRED) {
            // Proxy authentication required
            authenticationState = (AuthState) localContext.getAttribute(ClientContext.PROXY_AUTH_STATE);
        }
        if (statusCode == HttpStatus.SC_OK || statusCode == HttpStatus.SC_NOT_MODIFIED) {
            // in case the status is OK and there is a realm and result,
            // cache it
            if (realm != null && result != null) {
                sRealmCache.put(realm, result);
            }
        }

        // there is the need for authentication
        if (authenticationState != null) {

            // get scope and realm
            AuthScope authScope = authenticationState.getAuthScope();

            // If the current realm is different from the last one it means
            // a pass was performed successfully to the last URL, therefore
            // cache the last realm
            if (realm != null && !realm.equals(authScope.getRealm())) {
                sRealmCache.put(realm, result);
            }

            realm = authScope.getRealm();

            // in case there is cache for this Realm, use it to authenticate
            if (sRealmCache.containsKey(realm)) {
                result = sRealmCache.get(realm);
            } else {
                // since there is no cache, request for login and password
                result = monitor.displayLoginCredentialsPrompt("Site Authentication",
                        "Please login to the following domain: " + realm
                                + "\n\nServer requiring authentication:\n" + authScope.getHost());
                if (result == null) {
                    throw new CanceledByUserException("User canceled login dialog.");
                }
            }

            // retrieve authentication data
            String user = result.getUserName();
            String password = result.getPassword();
            String workstation = result.getWorkstation();
            String domain = result.getDomain();

            // proceed in case there is indeed a user
            if (user != null && user.length() > 0) {
                Credentials credentials = new NTCredentials(user, password, workstation, domain);
                httpClient.getCredentialsProvider().setCredentials(authScope, credentials);
                trying = true;
            } else {
                trying = false;
            }
        } else {
            trying = false;
        }

        HttpEntity entity = response.getEntity();

        if (entity != null) {
            if (trying) {
                // in case another pass to the Http Client will be performed, close the entity.
                entity.getContent().close();
            } else {
                // since no pass to the Http Client is needed, retrieve the
                // entity's content.

                // Note: don't use something like a BufferedHttpEntity since it would consume
                // all content and store it in memory, resulting in an OutOfMemory exception
                // on a large download.
                InputStream is = new FilterInputStream(entity.getContent()) {
                    @Override
                    public void close() throws IOException {
                        // Since Http Client is no longer needed, close it.

                        // Bug #21167: we need to tell http client to shutdown
                        // first, otherwise the super.close() would continue
                        // downloading and not return till complete.

                        httpClient.getConnectionManager().shutdown();
                        super.close();
                    }
                };

                HttpResponse outResponse = new BasicHttpResponse(response.getStatusLine());
                outResponse.setHeaders(response.getAllHeaders());
                outResponse.setLocale(response.getLocale());

                return Pair.of(is, outResponse);
            }
        } else if (statusCode == HttpStatus.SC_NOT_MODIFIED) {
            // It's ok to not have an entity (e.g. nothing to download) for a 304
            HttpResponse outResponse = new BasicHttpResponse(response.getStatusLine());
            outResponse.setHeaders(response.getAllHeaders());
            outResponse.setLocale(response.getLocale());

            return Pair.of(null, outResponse);
        }
    }

    // We get here if we did not succeed. Callers do not expect a null result.
    httpClient.getConnectionManager().shutdown();
    throw new FileNotFoundException(url);
}

From source file:org.eclipse.mylyn.commons.http.HttpUtil.java

private static void configureHttpClientProxy(AbstractHttpClient client, HttpContext context,
        AbstractWebLocation location) {//from  ww  w. jav a2s  . c o  m
    String host = getHost(location.getUrl());

    Proxy proxy;
    if (isRepositoryHttps(location.getUrl())) {
        proxy = location.getProxyForHost(host, IProxyData.HTTPS_PROXY_TYPE);
    } else {
        proxy = location.getProxyForHost(host, IProxyData.HTTP_PROXY_TYPE);
    }

    if (proxy != null && !Proxy.NO_PROXY.equals(proxy)) {
        InetSocketAddress address = (InetSocketAddress) proxy.address();

        client.getParams().setParameter(ConnRoutePNames.DEFAULT_PROXY,
                new HttpHost(address.getHostName(), address.getPort()));

        if (proxy instanceof AuthenticatedProxy) {
            AuthenticatedProxy authProxy = (AuthenticatedProxy) proxy;
            Credentials credentials = getCredentials(authProxy.getUserName(), authProxy.getPassword(),
                    address.getAddress());
            if (credentials instanceof NTCredentials) {
                List<String> authpref = new ArrayList<String>();
                authpref.add(AuthPolicy.NTLM);
                authpref.add(AuthPolicy.BASIC);
                authpref.add(AuthPolicy.DIGEST);
                client.getParams().setParameter(AuthPNames.PROXY_AUTH_PREF, authpref);
            } else {
                List<String> authpref = new ArrayList<String>();
                authpref.add(AuthPolicy.BASIC);
                authpref.add(AuthPolicy.DIGEST);
                authpref.add(AuthPolicy.NTLM);
                client.getParams().setParameter(AuthPNames.PROXY_AUTH_PREF, authpref);
            }
            AuthScope proxyAuthScope = new AuthScope(address.getHostName(), address.getPort(),
                    AuthScope.ANY_REALM);
            client.getCredentialsProvider().setCredentials(proxyAuthScope, credentials);
        }
    } else {
        client.getParams().setParameter(ConnRoutePNames.DEFAULT_PROXY, null);
    }
}

From source file:com.marklogic.client.impl.JerseyServices.java

private void connect(String host, int port, String database, String user, String password,
        Authentication authenType, SSLContext context, X509HostnameVerifier verifier) {
    if (logger.isDebugEnabled())
        logger.debug("Connecting to {} at {} as {}", new Object[] { host, port, user });

    if (host == null)
        throw new IllegalArgumentException("No host provided");

    if (authenType == null) {
        if (context != null) {
            authenType = Authentication.BASIC;
        }//from  w ww.ja v a2s.  c  o m
    }

    if (authenType != null) {
        if (user == null)
            throw new IllegalArgumentException("No user provided");
        if (password == null)
            throw new IllegalArgumentException("No password provided");
    }

    if (connection != null)
        connection = null;
    if (client != null) {
        client.destroy();
        client = null;
    }

    this.database = database;

    String baseUri = ((context == null) ? "http" : "https") + "://" + host + ":" + port + "/v1/";

    Properties props = System.getProperties();

    if (props.containsKey(MAX_DELAY_PROP)) {
        String maxDelayStr = props.getProperty(MAX_DELAY_PROP);
        if (maxDelayStr != null && maxDelayStr.length() > 0) {
            int max = Integer.parseInt(maxDelayStr);
            if (max > 0) {
                maxDelay = max * 1000;
            }
        }
    }
    if (props.containsKey(MIN_RETRY_PROP)) {
        String minRetryStr = props.getProperty(MIN_RETRY_PROP);
        if (minRetryStr != null && minRetryStr.length() > 0) {
            int min = Integer.parseInt(minRetryStr);
            if (min > 0) {
                minRetry = min;
            }
        }
    }

    // TODO: integrated control of HTTP Client and Jersey Client logging
    if (!props.containsKey("org.apache.commons.logging.Log")) {
        System.setProperty("org.apache.commons.logging.Log", "org.apache.commons.logging.impl.SimpleLog");
    }
    if (!props.containsKey("org.apache.commons.logging.simplelog.log.org.apache.http")) {
        System.setProperty("org.apache.commons.logging.simplelog.log.org.apache.http", "warn");
    }
    if (!props.containsKey("org.apache.commons.logging.simplelog.log.org.apache.http.wire")) {
        System.setProperty("org.apache.commons.logging.simplelog.log.org.apache.http.wire", "warn");
    }

    Scheme scheme = null;
    if (context == null) {
        SchemeSocketFactory socketFactory = PlainSocketFactory.getSocketFactory();
        scheme = new Scheme("http", port, socketFactory);
    } else {
        SSLSocketFactory socketFactory = new SSLSocketFactory(context, verifier);
        scheme = new Scheme("https", port, socketFactory);
    }
    SchemeRegistry schemeRegistry = new SchemeRegistry();
    schemeRegistry.register(scheme);

    int maxRouteConnections = 100;
    int maxTotalConnections = 2 * maxRouteConnections;

    /*
     * 4.2 PoolingClientConnectionManager connMgr = new
     * PoolingClientConnectionManager(schemeRegistry);
     * connMgr.setMaxTotal(maxTotalConnections);
     * connMgr.setDefaultMaxPerRoute(maxRouteConnections);
     * connMgr.setMaxPerRoute( new HttpRoute(new HttpHost(baseUri)),
     *     maxRouteConnections);
     */
    // start 4.1
    ThreadSafeClientConnManager connMgr = new ThreadSafeClientConnManager(schemeRegistry);
    connMgr.setMaxTotal(maxTotalConnections);
    connMgr.setDefaultMaxPerRoute(maxRouteConnections);
    connMgr.setMaxForRoute(new HttpRoute(new HttpHost(baseUri)), maxRouteConnections);
    // end 4.1

    // CredentialsProvider credentialsProvider = new
    // BasicCredentialsProvider();
    // credentialsProvider.setCredentials(new AuthScope(host, port),
    // new UsernamePasswordCredentials(user, password));

    HttpParams httpParams = new BasicHttpParams();

    if (authenType != null) {
        List<String> authpref = new ArrayList<String>();

        if (authenType == Authentication.BASIC)
            authpref.add(AuthPolicy.BASIC);
        else if (authenType == Authentication.DIGEST)
            authpref.add(AuthPolicy.DIGEST);
        else
            throw new MarkLogicInternalException(
                    "Internal error - unknown authentication type: " + authenType.name());

        httpParams.setParameter(AuthPNames.PROXY_AUTH_PREF, authpref);
    }

    httpParams.setBooleanParameter(ClientPNames.HANDLE_REDIRECTS, false);

    HttpProtocolParams.setVersion(httpParams, HttpVersion.HTTP_1_1);

    // HttpConnectionParams.setStaleCheckingEnabled(httpParams, false);

    // long-term alternative to isFirstRequest alive
    // HttpProtocolParams.setUseExpectContinue(httpParams, false);
    // httpParams.setIntParameter(CoreProtocolPNames.WAIT_FOR_CONTINUE, 1000);

    DefaultApacheHttpClient4Config config = new DefaultApacheHttpClient4Config();
    Map<String, Object> configProps = config.getProperties();
    configProps.put(ApacheHttpClient4Config.PROPERTY_PREEMPTIVE_BASIC_AUTHENTICATION, false);
    configProps.put(ApacheHttpClient4Config.PROPERTY_DISABLE_COOKIES, true);
    configProps.put(ApacheHttpClient4Config.PROPERTY_CONNECTION_MANAGER, connMgr);
    // ignored?
    configProps.put(ApacheHttpClient4Config.PROPERTY_FOLLOW_REDIRECTS, false);
    // configProps.put(ApacheHttpClient4Config.PROPERTY_CREDENTIALS_PROVIDER,
    // credentialsProvider);
    configProps.put(ApacheHttpClient4Config.PROPERTY_HTTP_PARAMS, httpParams);
    // switches from buffered to streamed in Jersey Client
    configProps.put(ApacheHttpClient4Config.PROPERTY_CHUNKED_ENCODING_SIZE, 32 * 1024);

    client = ApacheHttpClient4.create(config);

    // System.setProperty("javax.net.debug", "all"); // all or ssl

    if (authenType == null) {
        checkFirstRequest = false;
    } else if (authenType == Authentication.BASIC) {
        checkFirstRequest = false;

        client.addFilter(new HTTPBasicAuthFilter(user, password));
    } else if (authenType == Authentication.DIGEST) {
        checkFirstRequest = true;

        // workaround for JerseyClient bug 1445
        client.addFilter(new DigestChallengeFilter());

        client.addFilter(new HTTPDigestAuthFilter(user, password));
    } else {
        throw new MarkLogicInternalException(
                "Internal error - unknown authentication type: " + authenType.name());
    }

    // client.addFilter(new LoggingFilter(System.err));

    connection = client.resource(baseUri);
}

From source file:org.xmetdb.rest.protocol.CallableProtocolUpload.java

/**
 * /compound/{id} PUT/*ww  w  .  j  a  v a  2 s  .  c  om*/
 * @param compoundURI
 * @param name
 * @return
 * @throws Exception
 */
protected String updateName(String compoundURI, Object name) throws Exception {
    if ((name == null) || "".equals(name.toString().trim()))
        return null;
    final Reference uri = new Reference(queryService);
    OTClient cli = null;
    //PUT
    try {
        cli = new OTClient() {
            protected HttpClient createHTTPClient() {
                DefaultHttpClient cli = new DefaultHttpClient();
                List<String> authpref = new ArrayList<String>();
                authpref.add(AuthPolicy.BASIC);
                cli.getParams().setParameter(AuthPNames.PROXY_AUTH_PREF, authpref);
                cli.getCredentialsProvider()
                        .setCredentials(new AuthScope(uri.getHostDomain(), uri.getHostPort()), creds);
                return cli;
            };
        };
        SubstanceClient scli = cli.getSubstanceClient();
        Substance substance = new Substance();
        substance.setResourceIdentifier(new URL(compoundURI));
        substance.setName(name.toString().toLowerCase());
        RemoteTask task = scli.setSubstancePropertyAsync(new URL(compoundURI), substance, null, null);
        task.waitUntilCompleted(500);
        if (task.getError() != null)
            throw task.getError();
        return task.getResult().toExternalForm();
    } catch (Exception x) {
        //do smth
        throw x;
    } finally {
        try {
            cli.close();
        } catch (Exception x) {
        }
    }

}

From source file:org.eclipse.ecf.provider.filetransfer.httpclient4.HttpClientRetrieveFileTransfer.java

private void registerSchemes(ISocketEventSource source, ISocketListener socketListener) {
    SchemeRegistry schemeRegistry = this.httpClient.getConnectionManager().getSchemeRegistry();

    Scheme http = new Scheme(HttpClientRetrieveFileTransfer.HTTP, HTTP_PORT,
            new ECFHttpClientProtocolSocketFactory(SocketFactory.getDefault(), source, socketListener));

    Trace.trace(Activator.PLUGIN_ID, "registering http scheme"); //$NON-NLS-1$
    schemeRegistry.register(http);/*  w  ww.  j  ava 2 s  .c  o  m*/

    ISSLSocketFactoryModifier sslSocketFactoryModifier = Activator.getDefault().getSSLSocketFactoryModifier();

    if (sslSocketFactoryModifier == null) {
        sslSocketFactoryModifier = new HttpClientDefaultSSLSocketFactoryModifier();
    }

    SSLSocketFactory sslSocketFactory = null;
    try {
        sslSocketFactory = sslSocketFactoryModifier.getSSLSocketFactory();
    } catch (IOException e) {
        Trace.catching(Activator.PLUGIN_ID, DebugOptions.EXCEPTIONS_CATCHING, ISSLSocketFactoryModifier.class,
                "getSSLSocketFactory()", e); //$NON-NLS-1$
        Trace.throwing(Activator.PLUGIN_ID, DebugOptions.EXCEPTIONS_THROWING,
                HttpClientRetrieveFileTransfer.class, "registerSchemes()", e); //$NON-NLS-1$
        throw new ECFRuntimeException("Unable to instantiate schemes for HttpClient.", e); //$NON-NLS-1$
    }

    Scheme https = new Scheme(HttpClientRetrieveFileTransfer.HTTPS, HTTPS_PORT,
            new ECFHttpClientSecureProtocolSocketFactory(sslSocketFactory, source, socketListener));
    Trace.trace(Activator.PLUGIN_ID, "registering https scheme; modifier=" + sslSocketFactoryModifier); //$NON-NLS-1$
    schemeRegistry.register(https);

    // SPNEGO is not supported, so remove it from the list
    List authpref = new ArrayList(3);
    authpref.add(AuthPolicy.NTLM);
    authpref.add(AuthPolicy.DIGEST);
    authpref.add(AuthPolicy.BASIC);

    httpClient.getParams().setParameter(AuthPNames.PROXY_AUTH_PREF, authpref);
    httpClient.getParams().setParameter(AuthPNames.TARGET_AUTH_PREF, authpref);
}