Example usage for org.apache.http.impl.client DefaultHttpClient getCredentialsProvider

List of usage examples for org.apache.http.impl.client DefaultHttpClient getCredentialsProvider

Introduction

In this page you can find the example usage for org.apache.http.impl.client DefaultHttpClient getCredentialsProvider.

Prototype

public synchronized final CredentialsProvider getCredentialsProvider() 

Source Link

Usage

From source file:org.apache.solr.client.solrj.impl.Krb5HttpClientConfigurer.java

public void configure(DefaultHttpClient httpClient, SolrParams config) {
    super.configure(httpClient, config);

    if (System.getProperty(LOGIN_CONFIG_PROP) != null) {
        String configValue = System.getProperty(LOGIN_CONFIG_PROP);

        if (configValue != null) {
            logger.info("Setting up SPNego auth with config: " + configValue);
            final String useSubjectCredsProp = "javax.security.auth.useSubjectCredsOnly";
            String useSubjectCredsVal = System.getProperty(useSubjectCredsProp);

            // "javax.security.auth.useSubjectCredsOnly" should be false so that the underlying
            // authentication mechanism can load the credentials from the JAAS configuration.
            if (useSubjectCredsVal == null) {
                System.setProperty(useSubjectCredsProp, "false");
            } else if (!useSubjectCredsVal.toLowerCase(Locale.ROOT).equals("false")) {
                // Don't overwrite the prop value if it's already been written to something else,
                // but log because it is likely the Credentials won't be loaded correctly.
                logger.warn("System Property: " + useSubjectCredsProp + " set to: " + useSubjectCredsVal
                        + " not false.  SPNego authentication may not be successful.");
            }/* w w w. ja  v a 2 s. c o m*/

            javax.security.auth.login.Configuration.setConfiguration(jaasConfig);
            //Enable only SPNEGO authentication scheme.
            AuthSchemeRegistry registry = new AuthSchemeRegistry();
            registry.register(AuthSchemes.SPNEGO, new SPNegoSchemeFactory(true, false));
            httpClient.setAuthSchemes(registry);
            // Get the credentials from the JAAS configuration rather than here
            Credentials useJaasCreds = new Credentials() {
                public String getPassword() {
                    return null;
                }

                public Principal getUserPrincipal() {
                    return null;
                }
            };

            SolrPortAwareCookieSpecFactory cookieFactory = new SolrPortAwareCookieSpecFactory();
            httpClient.getCookieSpecs().register(cookieFactory.POLICY_NAME, cookieFactory);
            httpClient.getParams().setParameter(ClientPNames.COOKIE_POLICY, cookieFactory.POLICY_NAME);

            httpClient.getCredentialsProvider().setCredentials(AuthScope.ANY, useJaasCreds);

            httpClient.addRequestInterceptor(bufferedEntityInterceptor);
        } else {
            httpClient.getCredentialsProvider().clear();
        }
    }
}

From source file:com.lgallardo.youtorrentcontroller.JSONParser.java

public JSONObject getJSONFromUrl(String url) throws JSONParserStatusCodeException {

    // if server is publish in a subfolder, fix url
    if (subfolder != null && !subfolder.equals("")) {
        url = subfolder + "/" + url;
    }/* ww w.ja v  a 2 s.c  o  m*/

    HttpResponse httpResponse;
    DefaultHttpClient httpclient;

    HttpParams httpParameters = new BasicHttpParams();

    // Set the timeout in milliseconds until a connection is established.
    // The default value is zero, that means the timeout is not used.
    int timeoutConnection = connection_timeout * 1000;

    // Set the default socket timeout (SO_TIMEOUT)
    // in milliseconds which is the timeout for waiting for data.
    int timeoutSocket = data_timeout * 1000;

    // Set http parameters
    HttpConnectionParams.setConnectionTimeout(httpParameters, timeoutConnection);
    HttpConnectionParams.setSoTimeout(httpParameters, timeoutSocket);
    HttpProtocolParams.setUserAgent(httpParameters, "youTorrent Controller");
    HttpProtocolParams.setVersion(httpParameters, HttpVersion.HTTP_1_1);
    HttpProtocolParams.setContentCharset(httpParameters, HTTP.UTF_8);

    // Making HTTP request
    HttpHost targetHost = new HttpHost(this.hostname, this.port, this.protocol);

    // httpclient = new DefaultHttpClient(httpParameters);
    // httpclient = new DefaultHttpClient();
    httpclient = getNewHttpClient();

    // Set http parameters
    httpclient.setParams(httpParameters);

    try {

        AuthScope authScope = new AuthScope(targetHost.getHostName(), targetHost.getPort());
        UsernamePasswordCredentials credentials = new UsernamePasswordCredentials(this.username, this.password);

        httpclient.getCredentialsProvider().setCredentials(authScope, credentials);

        // set http parameters

        url = protocol + "://" + hostname + ":" + port + "/" + url + token;

        //            Log.d("Debug", "getJSONFromUrl - url: " + url);
        //            Log.d("Debug", "getJSONFromUrl - cookie: " + cookie);

        HttpGet httpget = new HttpGet(url);

        if (this.cookie != null) {
            httpget.setHeader("Cookie", this.cookie);
        }

        httpResponse = httpclient.execute(targetHost, httpget);

        StatusLine statusLine = httpResponse.getStatusLine();

        int mStatusCode = statusLine.getStatusCode();

        if (mStatusCode != 200) {
            httpclient.getConnectionManager().shutdown();
            throw new JSONParserStatusCodeException(mStatusCode);
        }

        HttpEntity httpEntity = httpResponse.getEntity();
        is = httpEntity.getContent();

        // Build JSON
        BufferedReader reader = new BufferedReader(new InputStreamReader(is, "UTF-8"), 8);
        StringBuilder sb = new StringBuilder();
        String line = null;
        while ((line = reader.readLine()) != null) {
            sb.append(line + "\n");
        }
        is.close();
        json = sb.toString();

        // try parse the string to a JSON object
        jObj = new JSONObject(json);

    } catch (JSONException e) {
        Log.e("Debug", "getJSONFromUrl - JSONException - Error parsing data " + e.toString());
    } catch (UnsupportedEncodingException e) {
        Log.e("Debug", "getJSONFromUrl - UnsupportedEncodingException: " + e.toString());

    } catch (ClientProtocolException e) {
        Log.e("Debug", "getJSONFromUrl - ClientProtocolException: " + e.toString());
        e.printStackTrace();
    } catch (IOException e) {
        Log.e("Debug", "getJSONFromUrl - IOException: " + e.toString());
        // e.printStackTrace();
        httpclient.getConnectionManager().shutdown();
        throw new JSONParserStatusCodeException(TIMEOUT_ERROR);
    } catch (JSONParserStatusCodeException e) {
        httpclient.getConnectionManager().shutdown();
        throw new JSONParserStatusCodeException(e.getCode());
    } catch (Exception e) {
        Log.e("Debug", "getJSONFromUrl - Generic: " + e.toString());
    } finally {
        // When HttpClient instance is no longer needed,
        // shut down the connection manager to ensure
        // immediate deallocation of all system resources
        httpclient.getConnectionManager().shutdown();
    }

    // return JSON String
    return jObj;
}

From source file:com.lgallardo.qbittorrentclient.JSONParser.java

public JSONObject getJSONFromUrl(String url) throws JSONParserStatusCodeException {

    // if server is publish in a subfolder, fix url
    if (subfolder != null && !subfolder.equals("")) {
        url = subfolder + "/" + url;
    }/*w ww  .j a  va 2  s .  c o  m*/

    HttpResponse httpResponse;
    DefaultHttpClient httpclient;

    HttpParams httpParameters = new BasicHttpParams();

    // Set the timeout in milliseconds until a connection is established.
    // The default value is zero, that means the timeout is not used.
    int timeoutConnection = connection_timeout * 1000;

    // Set the default socket timeout (SO_TIMEOUT)
    // in milliseconds which is the timeout for waiting for data.
    int timeoutSocket = data_timeout * 1000;

    // Set http parameters
    HttpConnectionParams.setConnectionTimeout(httpParameters, timeoutConnection);
    HttpConnectionParams.setSoTimeout(httpParameters, timeoutSocket);
    HttpProtocolParams.setUserAgent(httpParameters, "qBittorrent for Android");
    HttpProtocolParams.setVersion(httpParameters, HttpVersion.HTTP_1_1);
    HttpProtocolParams.setContentCharset(httpParameters, HTTP.UTF_8);

    // Making HTTP request
    HttpHost targetHost = new HttpHost(this.hostname, this.port, this.protocol);

    // httpclient = new DefaultHttpClient(httpParameters);
    // httpclient = new DefaultHttpClient();
    httpclient = getNewHttpClient();

    httpclient.setParams(httpParameters);

    try {

        AuthScope authScope = new AuthScope(targetHost.getHostName(), targetHost.getPort());
        UsernamePasswordCredentials credentials = new UsernamePasswordCredentials(this.username, this.password);

        httpclient.getCredentialsProvider().setCredentials(authScope, credentials);

        // set http parameters

        url = protocol + "://" + hostname + ":" + port + "/" + url;

        //            Log.d("Debug", "url:" + url);

        HttpGet httpget = new HttpGet(url);

        if (this.cookie != null) {
            httpget.setHeader("Cookie", this.cookie);
        }

        httpResponse = httpclient.execute(targetHost, httpget);

        StatusLine statusLine = httpResponse.getStatusLine();

        int mStatusCode = statusLine.getStatusCode();

        if (mStatusCode != 200) {
            httpclient.getConnectionManager().shutdown();
            throw new JSONParserStatusCodeException(mStatusCode);
        }

        HttpEntity httpEntity = httpResponse.getEntity();
        is = httpEntity.getContent();

        // Build JSON
        BufferedReader reader = new BufferedReader(new InputStreamReader(is, "UTF-8"), 8);
        StringBuilder sb = new StringBuilder();
        String line = null;
        while ((line = reader.readLine()) != null) {
            sb.append(line + "\n");
        }
        is.close();
        json = sb.toString();

        // try parse the string to a JSON object
        jObj = new JSONObject(json);

    } catch (JSONException e) {
        Log.e("JSON Parser", "Error parsing data " + e.toString());
    } catch (UnsupportedEncodingException e) {
        Log.e("JSON", "UnsupportedEncodingException: " + e.toString());

    } catch (ClientProtocolException e) {
        Log.e("JSON", "ClientProtocolException: " + e.toString());
        e.printStackTrace();
    } catch (SSLPeerUnverifiedException e) {
        Log.e("JSON", "SSLPeerUnverifiedException: " + e.toString());
        throw new JSONParserStatusCodeException(NO_PEER_CERTIFICATE);
    } catch (IOException e) {
        Log.e("JSON", "IOException: " + e.toString());
        // e.printStackTrace();
        httpclient.getConnectionManager().shutdown();
        throw new JSONParserStatusCodeException(TIMEOUT_ERROR);
    } catch (JSONParserStatusCodeException e) {
        httpclient.getConnectionManager().shutdown();
        throw new JSONParserStatusCodeException(e.getCode());
    } catch (Exception e) {
        Log.e("JSON", "Generic: " + e.toString());
    } finally {
        // When HttpClient instance is no longer needed,
        // shut down the connection manager to ensure
        // immediate deallocation of all system resources
        httpclient.getConnectionManager().shutdown();
    }

    // return JSON String
    return jObj;
}

From source file:org.apache.manifoldcf.crawler.connectors.meridio.meridiowrapper.MeridioWrapper.java

/** The Meridio Wrapper constructor that calls the Meridio login method
*
*@param log                                     a handle to a Log4j logger
*@param meridioDmwsUrl          the URL to the Meridio Document Management Web Service
*@param meridioRmwsUrl          the URL to the Meridio Records Management Web Service
*@param dmwsProxyHost           the proxy for DMWS, or null if none
*@param dmwsProxyPort           the proxy port for DMWS, or -1 if default
*@param rmwsProxyHost           the proxy for RMWS, or null if none
*@param rmwsProxyPort           the proxy port for RMWS, or -1 if default
*@param userName                        the username of the user to log in as, must include the Windows, e.g. domain\\user
*@param password                        the password of the user who is logging in
*@param clientWorkstation       an identifier for the client workstation, could be the IP address, for auditing purposes
*@param protocolFactory         the protocol factory object to use for https communication
*@param engineConfigurationFile the engine configuration object to use to communicate with the web services
*
*@throws RemoteException        if an error is encountered logging into Meridio
*//*from   w  ww.j a v  a  2  s  . co  m*/
public MeridioWrapper(Logger log, URL meridioDmwsUrl, URL meridioRmwsUrl, URL meridioManifoldCFWSUrl,
        String dmwsProxyHost, String dmwsProxyPort, String rmwsProxyHost, String rmwsProxyPort,
        String mcwsProxyHost, String mcwsProxyPort, String userName, String password, String clientWorkstation,
        javax.net.ssl.SSLSocketFactory mySSLFactory, Class resourceClass, String engineConfigurationFile)
        throws RemoteException, NumberFormatException {
    // Initialize local instance variables
    oLog = log;
    this.engineConfiguration = new ResourceProvider(resourceClass, engineConfigurationFile);
    this.clientWorkstation = clientWorkstation;

    // Set up the pool.
    // We have a choice: We can either have one httpclient instance, which gets reinitialized for every service
    // it connects with (because each one has a potentially different proxy setup), OR we can have a different
    // httpclient for each service.  The latter approach is obviously the more efficient, so I've chosen to do it
    // that way.
    PoolingClientConnectionManager localConnectionManager = new PoolingClientConnectionManager();
    localConnectionManager.setMaxTotal(1);
    if (mySSLFactory != null) {
        SSLSocketFactory myFactory = new SSLSocketFactory(mySSLFactory, new BrowserCompatHostnameVerifier());
        Scheme myHttpsProtocol = new Scheme("https", 443, myFactory);
        localConnectionManager.getSchemeRegistry().register(myHttpsProtocol);
    }
    connectionManager = localConnectionManager;

    // Parse the user and password values
    int index = userName.indexOf("\\");
    String domainUser;
    String domain;
    if (index != -1) {
        domainUser = userName.substring(index + 1);
        domain = userName.substring(0, index);
        if (oLog != null && oLog.isDebugEnabled())
            oLog.debug("Meridio: User is '" + domainUser + "', domain is '" + domain + "'");
    } else {
        domain = null;
        domainUser = userName;
        if (oLog != null && oLog.isDebugEnabled())
            oLog.debug("Meridio: User is '" + domainUser + "'; there is no domain specified");
    }

    if (oLog != null && oLog.isDebugEnabled()) {
        if (password != null && password.length() > 0)
            oLog.debug("Meridio: Password exists");
        else
            oLog.debug("Meridio: Password is null");
    }

    // Initialize the three httpclient objects

    // dmws first
    BasicHttpParams dmwsParams = new BasicHttpParams();
    dmwsParams.setBooleanParameter(CoreConnectionPNames.TCP_NODELAY, true);
    dmwsParams.setBooleanParameter(CoreConnectionPNames.STALE_CONNECTION_CHECK, false);
    dmwsParams.setIntParameter(CoreConnectionPNames.CONNECTION_TIMEOUT, 60000);
    dmwsParams.setIntParameter(CoreConnectionPNames.SO_TIMEOUT, 900000);
    dmwsParams.setBooleanParameter(ClientPNames.ALLOW_CIRCULAR_REDIRECTS, true);
    DefaultHttpClient localDmwsHttpClient = new DefaultHttpClient(connectionManager, dmwsParams);
    // No retries
    localDmwsHttpClient.setHttpRequestRetryHandler(new HttpRequestRetryHandler() {
        public boolean retryRequest(IOException exception, int executionCount, HttpContext context) {
            return false;
        }

    });

    localDmwsHttpClient.setRedirectStrategy(new DefaultRedirectStrategy());
    if (domainUser != null) {
        localDmwsHttpClient.getCredentialsProvider().setCredentials(
                new AuthScope(meridioDmwsUrl.getHost(), meridioDmwsUrl.getPort()),
                new NTCredentials(domainUser, password, currentHost, domain));
    }
    // Initialize proxy
    if (dmwsProxyHost != null && dmwsProxyHost.length() > 0) {
        int port = (dmwsProxyPort == null || dmwsProxyPort.length() == 0) ? 8080
                : Integer.parseInt(dmwsProxyPort);
        // Configure proxy authentication
        if (domainUser != null && domainUser.length() > 0) {
            localDmwsHttpClient.getCredentialsProvider().setCredentials(new AuthScope(dmwsProxyHost, port),
                    new NTCredentials(domainUser, password, currentHost, domain));
        }

        HttpHost proxy = new HttpHost(dmwsProxyHost, port);
        localDmwsHttpClient.getParams().setParameter(ConnRoutePNames.DEFAULT_PROXY, proxy);
    }
    dmwsHttpClient = localDmwsHttpClient;

    // rmws
    BasicHttpParams rmwsParams = new BasicHttpParams();
    rmwsParams.setBooleanParameter(CoreConnectionPNames.TCP_NODELAY, true);
    rmwsParams.setBooleanParameter(CoreConnectionPNames.STALE_CONNECTION_CHECK, false);
    rmwsParams.setIntParameter(CoreConnectionPNames.CONNECTION_TIMEOUT, 60000);
    rmwsParams.setIntParameter(CoreConnectionPNames.SO_TIMEOUT, 900000);
    rmwsParams.setBooleanParameter(ClientPNames.ALLOW_CIRCULAR_REDIRECTS, true);
    DefaultHttpClient localRmwsHttpClient = new DefaultHttpClient(connectionManager, rmwsParams);
    // No retries
    localRmwsHttpClient.setHttpRequestRetryHandler(new HttpRequestRetryHandler() {
        public boolean retryRequest(IOException exception, int executionCount, HttpContext context) {
            return false;
        }

    });

    localRmwsHttpClient.setRedirectStrategy(new DefaultRedirectStrategy());
    if (domainUser != null) {
        localRmwsHttpClient.getCredentialsProvider().setCredentials(
                new AuthScope(meridioRmwsUrl.getHost(), meridioRmwsUrl.getPort()),
                new NTCredentials(domainUser, password, currentHost, domain));
    }
    // Initialize proxy
    if (rmwsProxyHost != null && rmwsProxyHost.length() > 0) {
        int port = (rmwsProxyPort == null || rmwsProxyPort.length() == 0) ? 8080
                : Integer.parseInt(rmwsProxyPort);
        // Configure proxy authentication
        if (domainUser != null && domainUser.length() > 0) {
            localRmwsHttpClient.getCredentialsProvider().setCredentials(new AuthScope(rmwsProxyHost, port),
                    new NTCredentials(domainUser, password, currentHost, domain));
        }

        HttpHost proxy = new HttpHost(rmwsProxyHost, port);
        localRmwsHttpClient.getParams().setParameter(ConnRoutePNames.DEFAULT_PROXY, proxy);
    }
    rmwsHttpClient = localRmwsHttpClient;

    // mcws
    if (meridioManifoldCFWSUrl != null) {
        BasicHttpParams mcwsParams = new BasicHttpParams();
        mcwsParams.setBooleanParameter(CoreConnectionPNames.TCP_NODELAY, true);
        mcwsParams.setBooleanParameter(CoreConnectionPNames.STALE_CONNECTION_CHECK, false);
        mcwsParams.setIntParameter(CoreConnectionPNames.CONNECTION_TIMEOUT, 60000);
        mcwsParams.setIntParameter(CoreConnectionPNames.SO_TIMEOUT, 900000);
        mcwsParams.setBooleanParameter(ClientPNames.ALLOW_CIRCULAR_REDIRECTS, true);
        DefaultHttpClient localMcwsHttpClient = new DefaultHttpClient(connectionManager, mcwsParams);
        // No retries
        localMcwsHttpClient.setHttpRequestRetryHandler(new HttpRequestRetryHandler() {
            public boolean retryRequest(IOException exception, int executionCount, HttpContext context) {
                return false;
            }

        });

        localMcwsHttpClient.setRedirectStrategy(new DefaultRedirectStrategy());
        if (domainUser != null) {
            localMcwsHttpClient.getCredentialsProvider().setCredentials(
                    new AuthScope(meridioManifoldCFWSUrl.getHost(), meridioManifoldCFWSUrl.getPort()),
                    new NTCredentials(domainUser, password, currentHost, domain));
        }
        // Initialize proxy
        if (mcwsProxyHost != null && mcwsProxyHost.length() > 0) {
            int port = (mcwsProxyPort == null || mcwsProxyPort.length() == 0) ? 8080
                    : Integer.parseInt(mcwsProxyPort);
            // Configure proxy authentication
            if (domainUser != null && domainUser.length() > 0) {
                localMcwsHttpClient.getCredentialsProvider().setCredentials(new AuthScope(mcwsProxyHost, port),
                        new NTCredentials(domainUser, password, currentHost, domain));
            }

            HttpHost proxy = new HttpHost(mcwsProxyHost, port);
            localMcwsHttpClient.getParams().setParameter(ConnRoutePNames.DEFAULT_PROXY, proxy);
        }
        mcwsHttpClient = localMcwsHttpClient;
    } else
        mcwsHttpClient = null;

    // Set up the stub handles
    /*=================================================================
    * Get a handle to the DMWS
    *================================================================*/
    MeridioDMLocator meridioDMLocator = new MeridioDMLocator(engineConfiguration);
    MeridioDMSoapStub meridioDMWebService = new MeridioDMSoapStub(meridioDmwsUrl, meridioDMLocator);

    meridioDMWebService.setPortName(meridioDMLocator.getMeridioDMSoapWSDDServiceName());
    meridioDMWebService.setUsername(userName);
    meridioDMWebService.setPassword(password);
    meridioDMWebService._setProperty(HTTPCLIENT_PROPERTY, dmwsHttpClient);

    meridioDMWebService_ = meridioDMWebService;

    /*=================================================================
    * Get a handle to the RMWS
    *================================================================*/
    MeridioRMLocator meridioRMLocator = new MeridioRMLocator(engineConfiguration);
    MeridioRMSoapStub meridioRMWebService = new MeridioRMSoapStub(meridioRmwsUrl, meridioRMLocator);

    meridioRMWebService.setPortName(meridioRMLocator.getMeridioRMSoapWSDDServiceName());
    meridioRMWebService.setUsername(userName);
    meridioRMWebService.setPassword(password);
    meridioRMWebService._setProperty(HTTPCLIENT_PROPERTY, rmwsHttpClient);

    meridioRMWebService_ = meridioRMWebService;

    /*=================================================================
    * Get a handle to the MeridioMetaCarta Web Service
    *================================================================*/
    if (meridioManifoldCFWSUrl != null) {
        MetaCartaLocator meridioMCWS = new MetaCartaLocator(engineConfiguration);
        Service McWsService = null;
        MetaCartaSoapStub meridioMetaCartaWebService = new MetaCartaSoapStub(meridioManifoldCFWSUrl,
                McWsService);

        meridioMetaCartaWebService.setPortName(meridioMCWS.getMetaCartaSoapWSDDServiceName());
        meridioMetaCartaWebService.setUsername(userName);
        meridioMetaCartaWebService.setPassword(password);
        meridioMetaCartaWebService._setProperty(HTTPCLIENT_PROPERTY, mcwsHttpClient);

        meridioMCWS_ = meridioMetaCartaWebService;
    }

    this.loginUnified();
}

From source file:com.lgallardo.qbittorrentclient.JSONParser.java

public String getApi() throws JSONParserStatusCodeException {

    String url = "version/api";

    // if server is publish in a subfolder, fix url
    if (subfolder != null && !subfolder.equals("")) {
        url = subfolder + "/" + url;
    }/*from w  ww.j  a  v  a2 s . c  o  m*/

    String APIVersionString = null;

    HttpResponse httpResponse;
    DefaultHttpClient httpclient;

    HttpParams httpParameters = new BasicHttpParams();

    // Set the timeout in milliseconds until a connection is established.
    // The default value is zero, that means the timeout is not used.
    int timeoutConnection = connection_timeout * 1000;

    // Set the default socket timeout (SO_TIMEOUT)
    // in milliseconds which is the timeout for waiting for data.
    int timeoutSocket = data_timeout * 1000;

    //        Log.d("Debug", "API - timeoutConnection:" + timeoutConnection);
    //        Log.d("Debug", "API - timeoutSocket:" + timeoutSocket);

    // Set http parameters
    HttpConnectionParams.setConnectionTimeout(httpParameters, timeoutConnection);
    HttpConnectionParams.setSoTimeout(httpParameters, timeoutSocket);
    HttpProtocolParams.setUserAgent(httpParameters, "qBittorrent for Android");
    HttpProtocolParams.setVersion(httpParameters, HttpVersion.HTTP_1_1);
    HttpProtocolParams.setContentCharset(httpParameters, HTTP.UTF_8);

    // Making HTTP request
    HttpHost targetHost = new HttpHost(hostname, port, protocol);

    // httpclient = new DefaultHttpClient();
    httpclient = getNewHttpClient();

    httpclient.setParams(httpParameters);

    try {

        AuthScope authScope = new AuthScope(targetHost.getHostName(), targetHost.getPort());
        UsernamePasswordCredentials credentials = new UsernamePasswordCredentials(this.username, this.password);

        httpclient.getCredentialsProvider().setCredentials(authScope, credentials);

        // set http parameters

        url = protocol + "://" + hostname + ":" + port + "/" + url;

        //            Log.d("Debug", "API - url:" + url);

        HttpGet httpget = new HttpGet(url);

        //            Log.d("Debug", "API - executing");

        HttpResponse response = httpclient.execute(targetHost, httpget);

        //            Log.d("Debug", "API - getting entity");

        HttpEntity entity = response.getEntity();

        StatusLine statusLine = response.getStatusLine();

        int mStatusCode = statusLine.getStatusCode();

        //            Log.d("Debug", "API - mStatusCode: " + mStatusCode);

        if (mStatusCode == 200) {

            // Save API

            APIVersionString = EntityUtils.toString(response.getEntity());

            //                Log.d("Debug", "API - ApiString: " + APIVersionString);

        }

        //            if (mStatusCode != 200) {
        //                httpclient.getConnectionManager().shutdown();
        //                throw new JSONParserStatusCodeException(mStatusCode);
        //            }

        if (entity != null) {
            entity.consumeContent();
        }

        // When HttpClient instance is no longer needed,
        // shut down the connection manager to ensure
        // immediate deallocation of all system resources
        httpclient.getConnectionManager().shutdown();

    } catch (Exception e) {

        Log.e("Debug", "API - Exception " + e.toString());
    }

    //        if (APIVersionString == null) {
    //            APIVersionString = "";
    //        }
    return APIVersionString;
}

From source file:org.talend.mdm.webapp.browserecords.server.actions.BrowseRecordsAction.java

@Override
public String bulkUpdateItem(String baseUrl, String concept, String xml, String language)
        throws ServiceException {
    try {//from   ww  w.  j a  v a2s .c om
        String url = baseUrl + "services/rest/data/" + getCurrentDataCluster() + "/" + concept + "/bulk";
        DefaultHttpClient httpClient = new DefaultHttpClient();
        httpClient.getCredentialsProvider().setCredentials(AuthScope.ANY, new UsernamePasswordCredentials(
                LocalUser.getLocalUser().getUsername(), LocalUser.getLocalUser().getPassword()));
        HttpPatch httpPatch = new HttpPatch(url);
        httpPatch.setHeader("Content-Type", "text/xml; charset=utf8"); //$NON-NLS-1$ //$NON-NLS-2$
        HttpEntity entity = new StringEntity(xml);
        httpPatch.setEntity(entity);
        HttpResponse response = httpClient.execute(httpPatch);
        return readRestErroMessage(response);
    } catch (Exception e) {
        return e.getCause().getLocalizedMessage();
    }
}

From source file:com.juick.android.JuickMessagesAdapter.java

public static String setupProxyForURL(Context context, String url, DefaultHttpClient httpClient) {
    if (useDirectImageMode(context)) {
        return url;
    }/*ww w.  j a v a2  s  . c o m*/
    String loadURl = url;
    if (imageLoadMode.contains("japroxy")) {
        final int HEIGHT = (int) (((Activity) context).getWindow().getWindowManager().getDefaultDisplay()
                .getHeight() * imageHeightPercent);
        final int WIDTH = (int) (((Activity) context).getWindow().getWindowManager().getDefaultDisplay()
                .getWidth());
        String host = "ja.servebeer.com:8080";
        //String host = "192.168.1.77:8080";
        if (url.startsWith("https://i.juick.com")) {
            url = "http" + url.substring(5);
        }
        loadURl = "http://" + host + "/img?url=" + Uri.encode(url) + "&height=" + HEIGHT + "&width=" + WIDTH;
    }
    if (imageLoadMode.contains("weserv")) {
        final int HEIGHT = (int) (((Activity) context).getWindow().getWindowManager().getDefaultDisplay()
                .getHeight() * imageHeightPercent);
        // WESERV.NL
        if (url.startsWith("https://")) {
            loadURl = "http://images.weserv.nl/?url=ssl:" + Uri.encode(url.substring(8)) + "&h=" + HEIGHT
                    + "&q=0.5";
        } else if (url.startsWith("http://")) {
            loadURl = "http://images.weserv.nl/?url=" + Uri.encode(url.substring(7)) + "&h=" + HEIGHT
                    + "&q=0.5";
        } else {
            // keep url
        }
    }
    if (imageLoadMode.contains("fastun")) {
        if (httpClient != null) {
            SharedPreferences sp = PreferenceManager.getDefaultSharedPreferences(context);
            String proxyLogin = sp.getString("imageproxy.login", "");
            String proxyPassword = sp.getString("imageproxy.password", "");
            if (proxyLogin.length() > 0 && proxyPassword.length() > 0) {
                httpClient.getCredentialsProvider().setCredentials(new AuthScope("fastun.com", 7000),
                        new UsernamePasswordCredentials(proxyLogin, proxyPassword));
                HttpHost proxy = new HttpHost("fastun.com", 7000);
                httpClient.getParams().setParameter(ConnRoutePNames.DEFAULT_PROXY, proxy);
            }
        }
    }
    return loadURl;
}

From source file:org.brunocvcunha.taskerbox.core.http.TaskerboxHttpBox.java

/**
 * Build a new HTTP Client for the given parameters
 *
 * @param params/*from  w  w w.  j a  v a  2s .  c  om*/
 * @return
 */
public DefaultHttpClient buildNewHttpClient(HttpParams params) {
    PoolingClientConnectionManager cxMgr = new PoolingClientConnectionManager(
            SchemeRegistryFactory.createDefault());
    cxMgr.setMaxTotal(100);
    cxMgr.setDefaultMaxPerRoute(20);

    DefaultHttpClient httpClient = new DefaultHttpClient(cxMgr, params);
    httpClient.getParams().setParameter(CoreProtocolPNames.USER_AGENT,
            "Mozilla/5.0 (Windows NT 6.1; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/40.0.2214.111 Safari/537.36");
    // httpClient.getParams().setParameter(ClientPNames.COOKIE_POLICY,
    // CookiePolicy.BROWSER_COMPATIBILITY);
    if (this.useNtlm) {
        httpClient.getAuthSchemes().register("NTLM", new NTLMSchemeFactory());
        httpClient.getAuthSchemes().register("BASIC", new BasicSchemeFactory());
        httpClient.getAuthSchemes().register("DIGEST", new DigestSchemeFactory());
        httpClient.getAuthSchemes().register("SPNEGO", new SPNegoSchemeFactory());
        httpClient.getAuthSchemes().register("KERBEROS", new KerberosSchemeFactory());
    }

    try {
        SSLContext sc = SSLContext.getInstance("SSL");
        sc.init(null, getTrustingManager(), new java.security.SecureRandom());
        SSLSocketFactory socketFactory = new SSLSocketFactory(sc);
        Scheme sch = new Scheme("https", 443, socketFactory);
        httpClient.getConnectionManager().getSchemeRegistry().register(sch);
    } catch (NoSuchAlgorithmException e) {
        e.printStackTrace();
    } catch (KeyManagementException e) {
        e.printStackTrace();
    }

    if (this.useProxy) {
        if (this.proxySocks) {

            log.info("Using proxy socks " + this.socksHost + ":" + this.socksPort);

            System.setProperty("socksProxyHost", this.socksHost);
            System.setProperty("socksProxyPort", String.valueOf(this.socksPort));

        } else {
            HttpHost proxy = new HttpHost(this.proxyHost, this.proxyPort);
            httpClient.getParams().setParameter(ConnRoutePNames.DEFAULT_PROXY, proxy);

            if (this.authProxy) {

                List<String> authPreferences = new ArrayList<>();

                if (this.ntlmProxy) {

                    NTCredentials creds = new NTCredentials(this.proxyUser, this.proxyPassword,
                            this.proxyWorkstation, this.proxyDomain);
                    httpClient.getCredentialsProvider()
                            .setCredentials(new AuthScope(this.proxyHost, this.proxyPort), creds);
                    // httpClient.getCredentialsProvider().setCredentials(
                    // AuthScope.ANY, creds);

                    authPreferences.add(AuthPolicy.NTLM);
                } else {
                    UsernamePasswordCredentials creds = new UsernamePasswordCredentials(this.proxyUser,
                            this.proxyPassword);
                    httpClient.getCredentialsProvider().setCredentials(AuthScope.ANY, creds);

                    authPreferences.add(AuthPolicy.BASIC);
                }

                httpClient.getParams().setParameter(AuthPNames.TARGET_AUTH_PREF, authPreferences);
            }
        }

    }

    return httpClient;
}

From source file:com.mockey.ClientExecuteProxy.java

/**
 * //from w  ww. j  a  v  a 2 s .  c o  m
 * @param twistInfo
 * @param proxyServer
 * @param realServiceUrl
 * @param httpMethod
 * @param request
 * @return
 * @throws ClientExecuteProxyException
 */
public ResponseFromService execute(TwistInfo twistInfo, ProxyServerModel proxyServer, Url realServiceUrl,
        boolean allowRedirectFollow, RequestFromClient request) throws ClientExecuteProxyException {
    log.info("Request: " + String.valueOf(realServiceUrl));

    // general setup
    SchemeRegistry supportedSchemes = new SchemeRegistry();

    // Register the "http" and "https" protocol schemes, they are
    // required by the default operator to look up socket factories.
    supportedSchemes.register(new Scheme("http", 80, PlainSocketFactory.getSocketFactory()));
    supportedSchemes.register(new Scheme("https", 443, SSLSocketFactory.getSocketFactory()));

    // prepare parameters
    HttpParams params = new BasicHttpParams();
    HttpProtocolParams.setVersion(params, HttpVersion.HTTP_1_1);
    HttpProtocolParams.setContentCharset(params, HTTP.ISO_8859_1);
    HttpProtocolParams.setUseExpectContinue(params, false);

    ClientConnectionManager ccm = new ThreadSafeClientConnManager(supportedSchemes);
    DefaultHttpClient httpclient = new DefaultHttpClient(ccm, params);

    if (!allowRedirectFollow) {
        // Do NOT allow for 302 REDIRECT
        httpclient.setRedirectStrategy(new DefaultRedirectStrategy() {
            public boolean isRedirected(HttpRequest request, HttpResponse response, HttpContext context) {
                boolean isRedirect = false;
                try {
                    isRedirect = super.isRedirected(request, response, context);
                } catch (ProtocolException e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                }
                if (!isRedirect) {
                    int responseCode = response.getStatusLine().getStatusCode();
                    if (responseCode == 301 || responseCode == 302) {
                        return true;
                    }
                }
                return isRedirect;
            }
        });
    } else {
        // Yes, allow for 302 REDIRECT
        // Nothing needed here.
    }

    // Prevent CACHE, 304 not modified
    //      httpclient.addRequestInterceptor(new HttpRequestInterceptor() {
    //         public void process(final HttpRequest request, final HttpContext context) throws HttpException, IOException {
    //            
    //            request.setHeader("If-modified-Since", "Fri, 13 May 2006 23:54:18 GMT");
    //
    //         }
    //      });

    CookieStore cookieStore = httpclient.getCookieStore();
    for (Cookie httpClientCookie : request.getHttpClientCookies()) {
        // HACK:
        // httpClientCookie.getValue();
        cookieStore.addCookie(httpClientCookie);
    }
    // httpclient.setCookieStore(cookieStore);

    if (ClientExecuteProxy.cookieStore == null) {
        ClientExecuteProxy.cookieStore = httpclient.getCookieStore();

    } else {
        httpclient.setCookieStore(ClientExecuteProxy.cookieStore);
    }

    StringBuffer requestCookieInfo = new StringBuffer();
    // Show what cookies are in the store .
    for (Cookie cookie : ClientExecuteProxy.cookieStore.getCookies()) {
        log.debug("Cookie in the cookie STORE: " + cookie.toString());
        requestCookieInfo.append(cookie.toString() + "\n\n\n");

    }

    if (proxyServer.isProxyEnabled()) {
        // make sure to use a proxy that supports CONNECT
        httpclient.getCredentialsProvider().setCredentials(proxyServer.getAuthScope(),
                proxyServer.getCredentials());
        httpclient.getParams().setParameter(ConnRoutePNames.DEFAULT_PROXY, proxyServer.getHttpHost());
    }

    // TWISTING
    Url originalRequestUrlBeforeTwisting = null;
    if (twistInfo != null) {
        String fullurl = realServiceUrl.getFullUrl();
        String twistedUrl = twistInfo.getTwistedValue(fullurl);
        if (twistedUrl != null) {
            originalRequestUrlBeforeTwisting = realServiceUrl;
            realServiceUrl = new Url(twistedUrl);
        }
    }

    ResponseFromService responseMessage = null;
    try {
        HttpHost htttphost = new HttpHost(realServiceUrl.getHost(), realServiceUrl.getPort(),
                realServiceUrl.getScheme());

        HttpResponse response = httpclient.execute(htttphost, request.postToRealServer(realServiceUrl));
        if (response.getStatusLine().getStatusCode() == 302) {
            log.debug("FYI: 302 redirect occuring from " + realServiceUrl.getFullUrl());
        }
        responseMessage = new ResponseFromService(response);
        responseMessage.setOriginalRequestUrlBeforeTwisting(originalRequestUrlBeforeTwisting);
        responseMessage.setRequestUrl(realServiceUrl);
    } catch (Exception e) {
        log.error(e);
        throw new ClientExecuteProxyException("Unable to retrieve a response. ", realServiceUrl, e);
    } finally {
        // When HttpClient instance is no longer needed,
        // shut down the connection manager to ensure
        // immediate deallocation of all system resources
        httpclient.getConnectionManager().shutdown();
    }

    // Parse out the response information we're looking for
    // StringBuffer responseCookieInfo = new StringBuffer();
    // // Show what cookies are in the store .
    // for (Cookie cookie : ClientExecuteProxy.cookieStore.getCookies()) {
    // log.info("Cookie in the cookie STORE: " + cookie.toString());
    // responseCookieInfo.append(cookie.toString() + "\n\n\n");
    //
    // }
    // responseMessage.setRequestCookies(requestCookieInfo.toString());
    // responseMessage.setResponseCookies(responseCookieInfo.toString());
    return responseMessage;
}

From source file:de.dal33t.powerfolder.clientserver.ServerClient.java

/**
 * Prepare login information for shibboleth environment.
 *
 * @param username//from   w ww .j  a  v a  2s . co m
 * @param thePassword
 * @param userChanged
 * @return True if the user should login as external user, false if
 *         shibboleth is used.
 */
private boolean prepareShibbolethLogin(String username, char[] thePassword, boolean userChanged) {
    String idpURLString = ConfigurationEntry.SERVER_IDP_LAST_CONNECTED_ECP.getValue(getController());

    if (StringUtils.isBlank(idpURLString)) {
        shibUsername = null;
        shibToken = null;
        throw new SecurityException("Your organization is unreachable");
    } else if (userChanged) {
        shibUsername = null;
        shibToken = null;
    } else if ("ext".equals(idpURLString)) {
        return true;
    }

    boolean tokenIsValid = false;
    try {
        tokenIsValid = shibToken != null && shibToken.contains(":") && System.currentTimeMillis() <= Long
                .valueOf(shibToken.substring(shibToken.indexOf(':') + 1, shibToken.length()));
    } catch (Exception e) {
        logFine("Unusable Shibboleth Token: " + shibToken + " valid ? " + tokenIsValid);
        shibUsername = null;
        shibToken = null;
    }
    if (StringUtils.isBlank(shibUsername) || StringUtils.isBlank(shibToken) || !tokenIsValid) {
        String spURL = getWebURL(
                Constants.LOGIN_SHIBBOLETH_CLIENT_URI + '/' + getController().getMySelf().getId(), false);
        URI spURI;
        try {
            spURI = new URI(spURL);
        } catch (URISyntaxException e) {
            shibUsername = null;
            shibToken = null;
            // Should not happen
            throw new RuntimeException("Unable to resolve service provider URL: " + spURL + ". " + e);
        }

        URI idpURI = null;
        try {
            idpURI = new URI(idpURLString);
        } catch (Exception e) {
            shibUsername = null;
            shibToken = null;
            // Should not happen
            throw new RuntimeException("Unable to resolve identity provider URL: "
                    + ConfigurationEntry.SERVER_IDP_LAST_CONNECTED_ECP.getValue(getController()) + ". " + e);
        }

        // PFC-2496: Start
        DefaultHttpClient dhc = new DefaultHttpClient();

        // Set Proxy credentials, if configured
        if (ConfigurationEntry.HTTP_PROXY_HOST.hasValue(getController())) {
            String proxyUsername = "";
            String proxyPassword = "";

            if (ConfigurationEntry.HTTP_PROXY_USERNAME.hasValue(getController())) {
                proxyUsername = ConfigurationEntry.HTTP_PROXY_USERNAME.getValue(getController());

                if (ConfigurationEntry.HTTP_PROXY_PASSWORD.hasValue(getController())) {
                    proxyPassword = ConfigurationEntry.HTTP_PROXY_PASSWORD.getValue(getController());
                }
            }

            dhc.getCredentialsProvider().setCredentials(
                    new AuthScope(ConfigurationEntry.HTTP_PROXY_HOST.getValue(getController()),
                            ConfigurationEntry.HTTP_PROXY_PORT.getValueInt(getController())),
                    new UsernamePasswordCredentials(proxyUsername, proxyPassword));

            HttpHost proxy = new HttpHost(ConfigurationEntry.HTTP_PROXY_HOST.getValue(getController()),
                    ConfigurationEntry.HTTP_PROXY_PORT.getValueInt(getController()));
            dhc.getParams().setParameter(ConnRoutePNames.DEFAULT_PROXY, proxy);
        }
        // PFC-2496: End

        ECPAuthenticator auth = new ECPAuthenticator(dhc, username, new String(thePassword), idpURI, spURI);
        String[] result;
        try {
            result = auth.authenticate();
            shibUsername = result[0];
            shibToken = result[1];
        } catch (ECPUnauthorizedException e) {
            shibbolethUnauthRetriesSkip = ConfigurationEntry.SERVER_LOGIN_SKIP_RETRY
                    .getValueInt(getController());
            shibUsername = null;
            shibToken = null;
            throw new SecurityException(e);
        } catch (ECPAuthenticationException e) {
            shibUsername = null;
            shibToken = null;
            throw new SecurityException(e);
        }
    }

    return false;
}