Example usage for org.apache.http.client.params ClientPNames HANDLE_AUTHENTICATION

List of usage examples for org.apache.http.client.params ClientPNames HANDLE_AUTHENTICATION

Introduction

In this page you can find the example usage for org.apache.http.client.params ClientPNames HANDLE_AUTHENTICATION.

Prototype

String HANDLE_AUTHENTICATION

To view the source code for org.apache.http.client.params ClientPNames HANDLE_AUTHENTICATION.

Click Source Link

Document

Defines whether authentication should be handled automatically.

Usage

From source file:org.onehippo.cms7.brokenlinks.LinkChecker.java

public LinkChecker(CheckExternalBrokenLinksConfig config, Session session) {
    this.session = session;
    ClientConnectionManager connManager = new PoolingClientConnectionManager();
    HttpParams params = new SyncBasicHttpParams();
    params.setIntParameter(CoreConnectionPNames.SO_TIMEOUT, config.getSocketTimeout());
    params.setIntParameter(CoreConnectionPNames.CONNECTION_TIMEOUT, config.getConnectionTimeout());
    params.setBooleanParameter(CoreConnectionPNames.STALE_CONNECTION_CHECK, false);
    params.setBooleanParameter(ClientPNames.HANDLE_AUTHENTICATION, false);

    HttpClient client = null;//from   w ww  . ja va  2 s  .c om
    try {
        final String httpClientClassName = config.getHttpClientClassName();
        Class<? extends HttpClient> clientClass = (Class<? extends HttpClient>) Class
                .forName(httpClientClassName);
        final Constructor<? extends HttpClient> constructor = clientClass
                .getConstructor(ClientConnectionManager.class, HttpParams.class);
        client = constructor.newInstance(connManager, params);
    } catch (ClassNotFoundException e) {
        log.error("Could not find configured http client class", e);
    } catch (NoSuchMethodException e) {
        log.error("Could not find constructor of signature <init>(ClientConnectionmanager, HttpParams)", e);
    } catch (InvocationTargetException e) {
        log.error("Could not invoke constructor of httpClient", e);
    } catch (InstantiationException e) {
        log.error("Could not instantiate http client", e);
    } catch (IllegalAccessException e) {
        log.error("Not allowed to access http client constructor", e);
    }
    if (client == null) {
        client = new DefaultHttpClient(connManager, params);
    }

    httpClient = client;
    nrOfThreads = config.getNrOfHttpThreads();
    // authentication preemptive true
    // allow circular redirects true
}

From source file:com.pangdata.sdk.http.AbstractHttp.java

protected boolean sendData(HttpRequestBase request) {
    logger.debug("Send data to server {}", fullurl);
    HttpResponse response = null;/*from   w w  w . ja v  a  2 s .c om*/
    HttpClient httpClient = httpClients.get(Thread.currentThread().getId());
    try {
        if (httpClient == null) {
            HttpParams myParams = new BasicHttpParams();
            HttpConnectionParams.setSoTimeout(myParams, 100000);
            HttpConnectionParams.setConnectionTimeout(myParams, 100000); // Timeout

            httpClient = SdkUtils.createHttpClient(url, myParams);

            httpClients.put(Thread.currentThread().getId(), httpClient);
            httpClient.getParams().setParameter(ClientPNames.HANDLE_AUTHENTICATION, false);
        }

        if (!url.toLowerCase().startsWith("http")) {
            url = "http://" + url;
        }

        response = httpClient.execute(request);
        String result = EntityUtils.toString(response.getEntity(), "UTF-8");
        if (response.getStatusLine().getStatusCode() != 200) {
            logger.error("HTTP error: {}", result);
            if (response.getStatusLine().getStatusCode() == 401) {
                logger.error("UNAUTHORIZED ERROR. Process will be shutdown. Verify your username and userkey");
                System.exit(1);
            }
            throw new IllegalStateException(String.format("HTTP error code : %s, Error message: %s",
                    response.getStatusLine().getStatusCode(), result));
        }

        logger.debug("Response: {}", result);

        Map<String, Object> responseMap = (Map<String, Object>) JsonUtils.toObject(result, Map.class);
        if (!(Boolean) responseMap.get("Success")) {
            throw new IllegalStateException(String.format("Error message: %s", responseMap.get("Message")));
        }
        return true;
    } catch (Exception e) {
        throw new PangException(e);
    }
}

From source file:org.apache.axis2.transport.http.impl.httpclient4.HTTPProxyConfigurator.java

/**
 * Configure HTTP Proxy settings of commons-httpclient HostConfiguration.
 * Proxy settings can be get from axis2.xml, Java proxy settings or can be
 * override through property in message context.
 * <p/>//from   w w  w. j  av a 2 s.  com
 * HTTP Proxy setting element format: <parameter name="Proxy">
 * <Configuration> <ProxyHost>example.org</ProxyHost>
 * <ProxyPort>3128</ProxyPort> <ProxyUser>EXAMPLE/John</ProxyUser>
 * <ProxyPassword>password</ProxyPassword> <Configuration> <parameter>
 *
 * @param messageContext
 *            in message context for
 * @param httpClient
 *            instance
 * @throws org.apache.axis2.AxisFault
 *             if Proxy settings are invalid
 */
public static void configure(MessageContext messageContext, AbstractHttpClient httpClient) throws AxisFault {

    Credentials proxyCredentials = null;
    String proxyHost = null;
    String nonProxyHosts = null;
    Integer proxyPort = -1;
    String proxyUser = null;
    String proxyPassword = null;

    // Getting configuration values from Axis2.xml
    Parameter proxySettingsFromAxisConfig = messageContext.getConfigurationContext().getAxisConfiguration()
            .getParameter(HTTPTransportConstants.ATTR_PROXY);
    if (proxySettingsFromAxisConfig != null) {
        OMElement proxyConfiguration = getProxyConfigurationElement(proxySettingsFromAxisConfig);
        proxyHost = getProxyHost(proxyConfiguration);
        proxyPort = getProxyPort(proxyConfiguration);
        proxyUser = getProxyUser(proxyConfiguration);
        proxyPassword = getProxyPassword(proxyConfiguration);
        if (proxyUser != null) {
            if (proxyPassword == null) {
                proxyPassword = "";
            }

            proxyCredentials = new UsernamePasswordCredentials(proxyUser, proxyPassword);

            int proxyUserDomainIndex = proxyUser.indexOf("\\");
            if (proxyUserDomainIndex > 0) {
                String domain = proxyUser.substring(0, proxyUserDomainIndex);
                if (proxyUser.length() > proxyUserDomainIndex + 1) {
                    String user = proxyUser.substring(proxyUserDomainIndex + 1);
                    proxyCredentials = new NTCredentials(user, proxyPassword, proxyHost, domain);
                }
            }
        }
    }

    // If there is runtime proxy settings, these settings will override
    // settings from axis2.xml
    HttpTransportProperties.ProxyProperties proxyProperties = (HttpTransportProperties.ProxyProperties) messageContext
            .getProperty(HTTPConstants.PROXY);
    if (proxyProperties != null) {
        String proxyHostProp = proxyProperties.getProxyHostName();
        if (proxyHostProp == null || proxyHostProp.length() <= 0) {
            throw new AxisFault("HTTP Proxy host is not available. Host is a MUST parameter");
        } else {
            proxyHost = proxyHostProp;
        }
        proxyPort = proxyProperties.getProxyPort();

        // Overriding credentials
        String userName = proxyProperties.getUserName();
        String password = proxyProperties.getPassWord();
        String domain = proxyProperties.getDomain();

        if (userName != null && password != null && domain != null) {
            proxyCredentials = new NTCredentials(userName, password, proxyHost, domain);
        } else if (userName != null && domain == null) {
            proxyCredentials = new UsernamePasswordCredentials(userName, password);
        }

    }

    // Overriding proxy settings if proxy is available from JVM settings
    String host = System.getProperty(HTTPTransportConstants.HTTP_PROXY_HOST);
    if (host != null) {
        proxyHost = host;
    }

    String port = System.getProperty(HTTPTransportConstants.HTTP_PROXY_PORT);
    if (port != null) {
        proxyPort = Integer.parseInt(port);
    }

    if (proxyCredentials != null) {
        // TODO : Set preemptive authentication, but its not recommended in HC 4
        httpClient.getParams().setParameter(ClientPNames.HANDLE_AUTHENTICATION, true);

        httpClient.getCredentialsProvider().setCredentials(AuthScope.ANY, proxyCredentials);
        HttpHost proxy = new HttpHost(proxyHost, proxyPort);
        httpClient.getParams().setParameter(ConnRoutePNames.DEFAULT_PROXY, proxy);

    }
}

From source file:edu.harvard.liblab.ecru.SolrClient.java

/**
 * Creates a new HttpClient. If keyStorePath and/or trustStorePath are set, a secure client will
 * be created by reading in the keyStore and/or trustStore. In addition, system keys will also be 
 * included (i.e. those specified in the JRE).
 * //w  ww.  j av  a2s  . c  o m
 * Most of the code below is "borrowed" from edu.harvard.hul.ois.drs2.callservice.ServiceClient
 * 
 * @return  an HttpClient ready to roll!
 */
protected HttpClient createHttpClient() throws SolrClientException {
    // turn on SSL logging, according to Log4j settings

    DefaultHttpClient httpClient = new DefaultHttpClient();

    // set parameters
    httpClient.getParams().setParameter(CoreConnectionPNames.CONNECTION_TIMEOUT, connectionTimeout);
    httpClient.getParams().setParameter(CoreConnectionPNames.SO_TIMEOUT, socketTimeout);
    httpClient.getParams().setParameter(CoreProtocolPNames.HTTP_CONTENT_CHARSET, "UTF-8");
    httpClient.getParams().setParameter(ClientPNames.HANDLE_AUTHENTICATION, true);

    return httpClient;
}

From source file:com.anaplan.client.transport.ApacheHttpProvider.java

protected ApacheHttpProvider() {
    super();//w ww.java2  s .  c  om
    httpClient = new DefaultHttpClient();
    httpClient.getParams().setParameter(ClientPNames.HANDLE_AUTHENTICATION, Boolean.TRUE);
    httpClient.setCredentialsProvider(new ApacheCredentialsProvider());
    try {
        Class<?> engineClass = Class.forName("com.anaplan.client.transport.JCIFSEngine");
        final NTLMEngine ntlmEngine = (NTLMEngine) engineClass.newInstance();

        httpClient.getAuthSchemes().register("ntlm", new AuthSchemeFactory() {
            public AuthScheme newInstance(final HttpParams params) {
                return new NTLMScheme(ntlmEngine);
            }
        });
    } catch (InstantiationException instantiationException) {
        // Normal - the jcifs jar file is not present in the lib folder.
    } catch (Throwable thrown) {
        // Abnormal
        thrown.printStackTrace();
    }
    routePlanner = new ProxySelectorRoutePlanner(httpClient.getConnectionManager().getSchemeRegistry(),
            getProxySelector()) {
        private boolean suppressed;

        @Override
        public HttpRoute determineRoute(HttpHost target, HttpRequest request, HttpContext context)
                throws HttpException {
            HttpRoute httpRoute = super.determineRoute(target, request, context);
            if (getDebugLevel() >= 1 && !suppressed) {
                System.err.println(
                        httpRoute.toString() + " (" + getProxySelector().getClass().getSimpleName() + ")");
                if (getDebugLevel() == 1)
                    suppressed = true;
            }
            return httpRoute;
        }
    };
    httpClient.setRoutePlanner(routePlanner);
}

From source file:org.obiba.opal.rest.client.magma.OpalJavaClient.java

private void createClient() {
    log.info("Connecting to Opal: {}", opalURI);
    DefaultHttpClient httpClient = new DefaultHttpClient();
    if (keyStore == null)
        httpClient.getCredentialsProvider().setCredentials(AuthScope.ANY, credentials);
    httpClient.getParams().setParameter(ClientPNames.HANDLE_AUTHENTICATION, Boolean.TRUE);
    httpClient.getParams().setParameter(AuthPNames.TARGET_AUTH_PREF,
            Collections.singletonList(OpalAuth.CREDENTIALS_HEADER));
    httpClient.getParams().setParameter(ClientPNames.CONNECTION_MANAGER_FACTORY_CLASS_NAME,
            OpalClientConnectionManagerFactory.class.getName());
    httpClient.getParams().setParameter(CoreConnectionPNames.CONNECTION_TIMEOUT, connectionTimeout);
    httpClient.getParams().setParameter(CoreConnectionPNames.SO_TIMEOUT, soTimeout);
    httpClient.setHttpRequestRetryHandler(new DefaultHttpRequestRetryHandler(DEFAULT_MAX_ATTEMPT, false));
    httpClient.getAuthSchemes().register(OpalAuth.CREDENTIALS_HEADER, new OpalAuthScheme.Factory());

    try {//from  w  ww.  j  a v a2 s. c  o m
        httpClient.getConnectionManager().getSchemeRegistry()
                .register(new Scheme("https", HTTPS_PORT, getSocketFactory()));
    } catch (NoSuchAlgorithmException | KeyManagementException e) {
        throw new RuntimeException(e);
    }
    client = enableCaching(httpClient);

    ctx = new BasicHttpContext();
    ctx.setAttribute(ClientContext.COOKIE_STORE, new BasicCookieStore());
}

From source file:com.github.koraktor.steamcondenser.community.WebApi.java

/**
 * Fetches data from Steam Web API using the specified interface, method
 * and version. Additional parameters are supplied via HTTP GET. Data is
 * returned as a String in the given format.
 *
 * @param apiInterface The Web API interface to call, e.g.
 *                     <code>ISteamUser</code>
 * @param format The format to load from the API ("json", "vdf", or "xml")
 * @param method The Web API method to call, e.g.
 *               <code>GetPlayerSummaries</code>
 * @param params Additional parameters to supply via HTTP GET
 * @param version The API method version to use
 * @return Data is returned as a String in the given format (which may be
 *        "json", "vdf", or "xml")./*from   w w w  .  ja va 2  s  .com*/
 * @throws WebApiException In case of any request failure
 */
public static String load(String format, String apiInterface, String method, int version,
        Map<String, Object> params) throws WebApiException {
    String protocol = secure ? "https" : "http";
    String url = String.format("%s://api.steampowered.com/%s/%s/v%04d/?", protocol, apiInterface, method,
            version);

    if (params == null) {
        params = new HashMap<String, Object>();
    }
    params.put("format", format);
    if (apiKey != null) {
        params.put("key", apiKey);
    }

    boolean first = true;
    for (Map.Entry<String, Object> param : params.entrySet()) {
        if (first) {
            first = false;
        } else {
            url += '&';
        }

        url += String.format("%s=%s", param.getKey(), param.getValue());
    }

    if (LOG.isInfoEnabled()) {
        String debugUrl = (apiKey == null) ? url : url.replace(apiKey, "SECRET");
        LOG.info("Querying Steam Web API: " + debugUrl);
    }

    String data;
    try {
        DefaultHttpClient httpClient = new DefaultHttpClient();
        httpClient.getParams().setBooleanParameter(ClientPNames.HANDLE_AUTHENTICATION, false);
        HttpGet request = new HttpGet(url);
        HttpResponse response = httpClient.execute(request);

        Integer statusCode = response.getStatusLine().getStatusCode();
        if (!statusCode.toString().startsWith("20")) {
            if (statusCode == 401) {
                throw new WebApiException(WebApiException.Cause.UNAUTHORIZED);
            }

            throw new WebApiException(WebApiException.Cause.HTTP_ERROR, statusCode,
                    response.getStatusLine().getReasonPhrase());
        }

        data = EntityUtils.toString(response.getEntity());
    } catch (WebApiException e) {
        throw e;
    } catch (Exception e) {
        throw new WebApiException("Could not communicate with the Web API.", e);
    }

    return data;
}

From source file:com.github.koraktor.steamcondenser.steam.community.WebApi.java

/**
 * Fetches data from Steam Web API using the specified interface, method
 * and version. Additional parameters are supplied via HTTP GET. Data is
 * returned as a String in the given format.
 *
 * @param apiInterface The Web API interface to call, e.g.
 *                     <code>ISteamUser</code>
 * @param format The format to load from the API ("json", "vdf", or "xml")
 * @param method The Web API method to call, e.g.
 *               <code>GetPlayerSummaries</code>
 * @param params Additional parameters to supply via HTTP GET
 * @param version The API method version to use
 * @return Data is returned as a String in the given format (which may be
 *        "json", "vdf", or "xml")./* w  w  w. ja va  2  s  . co  m*/
 * @throws WebApiException In case of any request failure
 */
public static String load(String format, String apiInterface, String method, int version,
        Map<String, Object> params) throws WebApiException {
    String protocol = secure ? "https" : "http";
    String url = String.format("%s://api.steampowered.com/%s/%s/v%04d/?", protocol, apiInterface, method,
            version);

    if (params == null) {
        params = new HashMap<String, Object>();
    }
    params.put("format", format);
    if (apiKey != null) {
        params.put("key", apiKey);
    }

    boolean first = true;
    for (Map.Entry<String, Object> param : params.entrySet()) {
        if (first) {
            first = false;
        } else {
            url += '&';
        }

        url += String.format("%s=%s", param.getKey(), param.getValue());
    }

    if (LOG.isLoggable(Level.INFO)) {
        String debugUrl = (apiKey == null) ? url : url.replace(apiKey, "SECRET");
        LOG.info("Querying Steam Web API: " + debugUrl);
    }

    String data;
    try {
        DefaultHttpClient httpClient = new DefaultHttpClient();
        httpClient.getParams().setBooleanParameter(ClientPNames.HANDLE_AUTHENTICATION, false);
        HttpGet request = new HttpGet(url);
        HttpResponse response = httpClient.execute(request);

        Integer statusCode = response.getStatusLine().getStatusCode();
        if (!statusCode.toString().startsWith("20")) {
            if (statusCode == 401) {
                throw new WebApiException(WebApiException.Cause.UNAUTHORIZED);
            }

            throw new WebApiException(WebApiException.Cause.HTTP_ERROR, statusCode,
                    response.getStatusLine().getReasonPhrase());
        }

        data = EntityUtils.toString(response.getEntity());
    } catch (WebApiException e) {
        throw e;
    } catch (Exception e) {
        throw new WebApiException("Could not communicate with the Web API.", e);
    }

    return data;
}

From source file:fr.natoine.html.HTMLPage.java

@SuppressWarnings("finally")
public String extractFullContentResource(String _url, int _time_to_respond) {
    String response_content = null;
    HttpClient httpclient = new DefaultHttpClient();
    //httpclient.getParams().setParameter(CoreProtocolPNames.HTTP_ELEMENT_CHARSET , "UTF-8");
    //httpclient.getParams().setParameter(CoreProtocolPNames.HTTP_CONTENT_CHARSET, "UTF-16");
    //httpclient.getParams().setParameter(CoreProtocolPNames.HTTP_CONTENT_CHARSET, "ISO-8859-1");
    //US-ASCII// w  w  w  . j ava  2 s  .  co  m
    //httpclient.getParams().setParameter(CoreProtocolPNames.HTTP_CONTENT_CHARSET, "US-ASCII");
    httpclient.getParams().setBooleanParameter(ClientPNames.HANDLE_REDIRECTS, true);
    httpclient.getParams().setBooleanParameter(ClientPNames.HANDLE_AUTHENTICATION, true);
    httpclient.getParams().setIntParameter(CoreConnectionPNames.SO_TIMEOUT, 3000);
    //HttpParams params = 
    //HttpClient httpclient = new DefaultHttpClient(params);
    HttpGet httpget = new HttpGet(_url);
    try {
        //Timer pour mettre un dlai sur le temps d'excution de la requte
        //Timer timer = new Timer();
        //timer.schedule(new TimerTaskTooLong(httpget , _url) , _time_to_respond);
        //HttpResponse response = httpclient.execute(httpget);
        ResponseHandler<String> responseHandler = new BasicResponseHandler();
        String responseBody = httpclient.execute(httpget, responseHandler);
        if (responseBody != null) {
            response_content = responseBody;
            //      valid = true ;
        }
    } catch (ClientProtocolException e) {
        //   valid = false ;
        System.out.println(
                "[HTMLPage.extractFullContentCssLink] url : " + _url + " doesn't support GET requests !!! ");
        e.printStackTrace();
    } catch (IOException e) {
        //   valid = false ;
        System.out.println(
                "[HTMLPage.extractFullContentCssLink] url : " + _url + " send no data !!! Not responding ... ");
        e.printStackTrace();
    } finally {
        httpclient.getConnectionManager().shutdown();
        return response_content;
    }
}

From source file:org.openrdf.http.client.SparqlSession.java

protected void setUsernameAndPasswordForUrl(String username, String password, String url) {

    if (username != null && password != null) {
        logger.debug("Setting username '{}' and password for server at {}.", username, url);
        java.net.URI requestURI = java.net.URI.create(url);
        String host = requestURI.getHost();
        int port = requestURI.getPort();
        AuthScope scope = new AuthScope(host, port);
        UsernamePasswordCredentials cred = new UsernamePasswordCredentials(username, password);
        CredentialsProvider credsProvider = new BasicCredentialsProvider();
        credsProvider.setCredentials(scope, cred);
        httpContext.setAttribute(ClientContext.CREDS_PROVIDER, credsProvider);
        params.setBooleanParameter(ClientPNames.HANDLE_AUTHENTICATION, true);
    } else {//  w ww .  j av  a2 s .c  om
        httpContext.removeAttribute(ClientContext.CREDS_PROVIDER);
    }
}