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:io.fabric8.itests.paxexam.basic.FabricMavenProxyTest.java

@Test
public void testUpload() throws Exception {
    String featureLocation = System.getProperty("feature.location");
    System.out.println("Testing with feature from:" + featureLocation);
    System.out.println(executeCommand("fabric:create -n --wait-for-provisioning"));
    //System.out.println(executeCommand("shell:info"));
    //System.out.println(executeCommand("fabric:info"));
    //System.out.println(executeCommand("fabric:profile-list"));

    ServiceProxy<FabricService> fabricProxy = ServiceProxy.createServiceProxy(bundleContext,
            FabricService.class);
    try {//  ww  w  .j  a v  a  2s  .  co m
        Set<ContainerProxy> containers = ContainerBuilder.create(fabricProxy, 2).withName("maven")
                .withProfiles("fabric").assertProvisioningResult().build();
        try {
            List<String> uploadUrls = new ArrayList<String>();
            ServiceProxy<CuratorFramework> curatorProxy = ServiceProxy.createServiceProxy(bundleContext,
                    CuratorFramework.class);
            try {
                CuratorFramework curator = curatorProxy.getService();
                List<String> children = ZooKeeperUtils.getChildren(curator,
                        ZkPath.MAVEN_PROXY.getPath("upload"));
                for (String child : children) {
                    String uploadeUrl = ZooKeeperUtils.getSubstitutedPath(curator,
                            ZkPath.MAVEN_PROXY.getPath("upload") + "/" + child);
                    uploadUrls.add(uploadeUrl);
                }
            } finally {
                curatorProxy.close();
            }
            //Pick a random maven proxy from the list.
            Random random = new Random();
            int index = random.nextInt(uploadUrls.size());
            String targetUrl = uploadUrls.get(index);

            String uploadUrl = targetUrl + "itest/itest/1.0/itest-1.0-features.xml";
            System.out.println("Using URI: " + uploadUrl);
            DefaultHttpClient client = new DefaultHttpClient();
            HttpPut put = new HttpPut(uploadUrl);
            client.getCredentialsProvider().setCredentials(AuthScope.ANY,
                    new UsernamePasswordCredentials("admin", "admin"));

            FileNIOEntity entity = new FileNIOEntity(new File(featureLocation), "text/xml");
            put.setEntity(entity);
            HttpResponse response = client.execute(put);
            System.out.println("Response:" + response.getStatusLine());
            Assert.assertTrue(response.getStatusLine().getStatusCode() == 200
                    || response.getStatusLine().getStatusCode() == 202);

            System.out.println(executeCommand(
                    "fabric:profile-edit --repositories mvn:itest/itest/1.0/xml/features default"));
            System.out.println(executeCommand("fabric:profile-edit --features example-cbr default"));
            Provision.containerStatus(containers, PROVISION_TIMEOUT);
        } finally {
            ContainerBuilder.destroy(containers);
        }
    } finally {
        fabricProxy.close();
    }
}

From source file:com.rackspace.api.clients.veracode.DefaultVeracodeApiClient.java

private HttpClient initiateClient(UsernamePasswordCredentials credentials) {
    DefaultHttpClient client = new DefaultHttpClient();

    AuthScope scope = new AuthScope(baseUri.getHost(), baseUri.getPort());

    client.getCredentialsProvider().setCredentials(scope, credentials);

    return client;
}

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

private DefaultHttpClient createHttpClient(String userName, String password, int timeout) {
    BasicHttpParams params = new BasicHttpParams();
    int timeoutMilliSeconds = timeout * 1000;
    HttpConnectionParams.setConnectionTimeout(params, timeoutMilliSeconds);
    HttpConnectionParams.setSoTimeout(params, timeoutMilliSeconds);
    DefaultHttpClient client = new DefaultHttpClient(params);

    if (userName != null && !"".equals(userName)) {
        client.getCredentialsProvider().setCredentials(new AuthScope(AuthScope.ANY_HOST, AuthScope.ANY_PORT),
                new UsernamePasswordCredentials(userName, password));
        localContext = new BasicHttpContext();

        // Generate BASIC scheme object and stick it to the local execution context
        BasicScheme basicAuth = new BasicScheme();
        localContext.setAttribute("preemptive-auth", basicAuth);

        // Add as the first request interceptor
        client.addRequestInterceptor(new PreemptiveAuth(), 0);
    }//  ww w  .  j  a v  a 2  s . com
    boolean requestSentRetryEnabled = Boolean.parseBoolean(System.getProperty("requestSentRetryEnabled"));
    if (requestSentRetryEnabled) {
        client.setHttpRequestRetryHandler(new DefaultHttpRequestRetryHandler(3, requestSentRetryEnabled));
    }
    // set the following user agent with each request
    String userAgent = "ArtifactoryBuildClient/" + CLIENT_VERSION;
    HttpProtocolParams.setUserAgent(client.getParams(), userAgent);
    return client;
}

From source file:com.networkmanagerapp.JSONBackgroundDownloaderService.java

/**
 * Delegate method to run the specified intent in another thread.
 * @param arg0 The intent to run in the background
 */// w w  w  .  j  a v  a 2 s . c  o m
@Override
protected void onHandleIntent(Intent arg0) {
    mNM = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);
    showNotification();
    String filename = arg0.getStringExtra("FILENAME");
    String jsonFile = arg0.getStringExtra("JSONFILE");
    try {
        String password = PreferenceManager.getDefaultSharedPreferences(this).getString("password_preference",
                "");
        Log.d("password", password);
        String ip = PreferenceManager.getDefaultSharedPreferences(this).getString("ip_preference",
                "192.168.1.1");
        String enc = URLEncoder.encode(ip, "UTF-8");
        String scriptUrl = "http://" + enc + ":1080" + filename;

        HttpParams params = new BasicHttpParams();
        HttpProtocolParams.setVersion(params, HttpVersion.HTTP_1_1);
        HttpProtocolParams.setContentCharset(params, "utf-8");

        // Set the timeout in milliseconds until a connection is established.
        int timeoutConnection = 3000;
        HttpConnectionParams.setConnectionTimeout(params, timeoutConnection);
        // Set the default socket timeout (SO_TIMEOUT) 
        // in milliseconds which is the timeout for waiting for data.
        int timeoutSocket = 20000;
        HttpConnectionParams.setSoTimeout(params, timeoutSocket);
        HttpHost targetHost = new HttpHost(enc, 1080, "http");

        DefaultHttpClient client = new DefaultHttpClient(params);
        client.getCredentialsProvider().setCredentials(
                new AuthScope(targetHost.getHostName(), targetHost.getPort()),
                new UsernamePasswordCredentials("root", password));
        HttpGet request = new HttpGet(scriptUrl);
        HttpResponse response = client.execute(targetHost, request);
        Log.d("JBDS", response.getStatusLine().toString());
        InputStream in = response.getEntity().getContent();
        BufferedReader reader = new BufferedReader(new InputStreamReader(in));
        StringBuilder str = new StringBuilder();
        String line = null;
        while ((line = reader.readLine()) != null) {
            str.append(line + "\n");
        }
        in.close();

        if (str.toString().equals("Success\n")) {
            String xmlUrl = "http://" + enc + ":1080/json" + jsonFile;
            request = new HttpGet(xmlUrl);
            HttpResponse jsonData = client.execute(targetHost, request);
            in = jsonData.getEntity().getContent();
            reader = new BufferedReader(new InputStreamReader(in));
            str = new StringBuilder();
            line = null;
            while ((line = reader.readLine()) != null) {
                str.append(line + "\n");
            }
            in.close();

            FileOutputStream fos = openFileOutput(jsonFile.substring(1), Context.MODE_PRIVATE);
            fos.write(str.toString().getBytes());
            fos.close();
        }
    } catch (MalformedURLException ex) {
        Log.e("NETWORKMANAGER_XBD_MUE", ex.getMessage());
    } catch (IOException e) {
        try {
            Log.e("NETWORK_MANAGER_XBD_IOE", e.getMessage());
            StackTraceElement[] st = e.getStackTrace();
            for (int i = 0; i < st.length; i++) {
                Log.e("NETWORK_MANAGER_XBD_IOE", st[i].toString());
            }
        } catch (NullPointerException ex) {
            Log.e("Network_manager_xbd_npe", ex.getLocalizedMessage());
        }

    } finally {
        mNM.cancel(R.string.download_service_started);
        Intent bci = new Intent(NEW_DATA_AVAILABLE);
        sendBroadcast(bci);
        stopSelf();
    }
}

From source file:eu.comvantage.dataintegration.SPARQLConnector.java

@Override
public QueryResultSet update(eu.comvantage.dataintegration.data.Query q) {
    QueryResultSet result = new QueryResultSet();

    //try to execute the SPARUL update command
    try {/*from  w  ww . j a  v a 2 s. c o  m*/
        //set authentication header
        UsernamePasswordCredentials userpasscred = new UsernamePasswordCredentials(
                this.credentials.getUsername(), this.credentials.getPassword());

        DefaultHttpClient httpclient = new DefaultHttpClient();
        httpclient.getCredentialsProvider().setCredentials(AuthScope.ANY, userpasscred);

        HttpPost httpPost = new HttpPost(this.sparqlEndpoint.getEndpointURL());

        //set up HTTP Post Request (look at http://virtuoso.openlinksw.com/dataspace/doc/dav/wiki/Main/VOSSparqlProtocol for Protocol)
        List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(1);
        //nameValuePairs.add(new BasicNameValuePair("format",format));
        nameValuePairs.add(new BasicNameValuePair("update", q.getQueryString()));
        httpPost.setEntity(new UrlEncodedFormEntity(nameValuePairs));

        //set proxy if defined
        if (System.getProperty("http.proxyHost") != null) {
            HttpHost proxy = new HttpHost(System.getProperty("http.proxyHost"),
                    Integer.valueOf(System.getProperty("http.proxyPort")), "http");
            httpclient.getParams().setParameter(ConnRoutePNames.DEFAULT_PROXY, proxy);
        }

        try {
            //execute the HTTP post
            HttpResponse response = httpclient.execute(httpPost);

            System.out.println("SPARQLConnector, Update command: " + q.getQueryString() + ";");
            System.out.println("SPARQLConnector, Update executed on endpoint: "
                    + sparqlEndpoint.getEndpointURL() + "; user credentials: " + this.credentials.getUsername()
                    + ":" + this.credentials.getPassword());

            //handle different server responses and failures
            int responseCode = response.getStatusLine().getStatusCode();
            String responseMessage = response.getStatusLine().getReasonPhrase();
            System.out.println("SPARQLConnector update response: " + responseCode + ", " + responseMessage);

        } catch (IOException ex) {
            throw new UpdateException(ex);
        }
    } catch (Exception e) {
        e.printStackTrace();
    }
    return result;
}

From source file:org.eobjects.datacleaner.monitor.pentaho.PentahoCarteClient.java

private HttpClient createHttpClient(PentahoJobType pentahoJobType) {
    final String hostname = pentahoJobType.getCarteHostname();
    final Integer port = pentahoJobType.getCartePort();
    final String username = pentahoJobType.getCarteUsername();
    final String password = pentahoJobType.getCartePassword();

    final DefaultHttpClient httpClient = new DefaultHttpClient();
    final CredentialsProvider credentialsProvider = httpClient.getCredentialsProvider();

    final UsernamePasswordCredentials credentials = new UsernamePasswordCredentials(username, password);

    final List<String> authpref = new ArrayList<String>();
    authpref.add(AuthPolicy.BASIC);//from  www . j av  a  2 s.  c o m
    authpref.add(AuthPolicy.DIGEST);
    httpClient.getParams().setParameter(AuthPNames.PROXY_AUTH_PREF, authpref);

    credentialsProvider.setCredentials(new AuthScope(hostname, port), credentials);
    return httpClient;
}

From source file:org.springframework.social.reddit.connect.RedditOAuth2Template.java

private String getAccessToken(String code, String redirectUrl)
        throws UnsupportedEncodingException, IOException {
    DefaultHttpClient httpclient = new DefaultHttpClient();
    try {//from  ww  w  . jav a 2 s  .  c o m

        //Reddit Requires clientId and clientSecret be attached via basic auth
        httpclient.getCredentialsProvider().setCredentials(new AuthScope("ssl.reddit.com", 443),
                new UsernamePasswordCredentials(clientId, clientSecret));

        HttpPost httppost = new HttpPost(RedditPaths.OAUTH_TOKEN_URL);

        List<NameValuePair> nvps = new ArrayList<NameValuePair>(3);
        nvps.add(new BasicNameValuePair("code", code));
        nvps.add(new BasicNameValuePair("grant_type", "authorization_code"));
        nvps.add(new BasicNameValuePair("redirect_uri", redirectUrl));

        httppost.setEntity(new UrlEncodedFormEntity(nvps));
        httppost.addHeader("User-Agent", "a unique user agent");
        httppost.setHeader("Accept", "any;");

        HttpResponse request = httpclient.execute(httppost);
        HttpEntity response = request.getEntity(); // Reddit response containing accessToken

        if (response != null) {
            BufferedReader br = new BufferedReader(new InputStreamReader(response.getContent()));
            StringBuilder content = new StringBuilder();
            String line;
            while (null != (line = br.readLine())) {
                content.append(line);
            }
            System.out.println(content.toString());
            Map json = (Map) JSONValue.parse(content.toString());
            if (json.containsKey("access_token")) {
                return (String) (json.get("access_token"));
            }
        }
        EntityUtils.consume(response);
    } finally {
        httpclient.getConnectionManager().shutdown(); //cleanup
    }
    return null;
}

From source file:org.datacleaner.monitor.cluster.HttpClusterManagerFactory.java

@Override
public ClusterManager getClusterManager(TenantIdentifier tenant) {
    final DefaultHttpClient httpClient = new DefaultHttpClient(new PoolingClientConnectionManager());
    if (username != null && password != null) {
        final CredentialsProvider credentialsProvider = httpClient.getCredentialsProvider();
        final UsernamePasswordCredentials credentials = new UsernamePasswordCredentials(username, password);
        final List<String> authpref = new ArrayList<String>();
        authpref.add(AuthPolicy.BASIC);/*from  ww w.j  a  v a  2  s  . co m*/
        authpref.add(AuthPolicy.DIGEST);
        httpClient.getParams().setParameter(AuthPNames.PROXY_AUTH_PREF, authpref);
        credentialsProvider.setCredentials(new AuthScope(null, -1), credentials);
    }

    // use the server list
    final List<String> finalEndpoints = new ArrayList<String>();
    for (String endpoint : slaveServerUrls) {
        if (!endpoint.endsWith("/")) {
            endpoint = endpoint + "/";
        }
        endpoint = endpoint + "repository/" + tenant.getId() + "/cluster_slave_endpoint";
        finalEndpoints.add(endpoint);
    }

    return new HttpClusterManager(httpClient, finalEndpoints);
}

From source file:org.talend.librariesmanager.deploy.ArtifactsDeployer.java

private void installToRemote(HttpEntity entity, URL targetURL) throws BusinessException {
    DefaultHttpClient httpClient = new DefaultHttpClient();
    try {/*from  www  .j  a va 2  s. c  o  m*/
        httpClient.getCredentialsProvider().setCredentials(
                new AuthScope(targetURL.getHost(), targetURL.getPort()),
                new UsernamePasswordCredentials(nexusServer.getUserName(), nexusServer.getPassword()));

        HttpPut httpPut = new HttpPut(targetURL.toString());
        httpPut.setEntity(entity);
        HttpResponse response = httpClient.execute(httpPut);
        StatusLine statusLine = response.getStatusLine();
        int responseCode = statusLine.getStatusCode();
        EntityUtils.consume(entity);
        if (responseCode > 399) {
            if (responseCode == 401) {
                throw new BusinessException("Authrity failed");
            } else {
                throw new BusinessException(
                        "Deploy failed: " + responseCode + ' ' + statusLine.getReasonPhrase());
            }
        }
    } catch (Exception e) {
        throw new BusinessException("softwareupdate.error.cannotupload", e.getMessage());
    } finally {
        httpClient.getConnectionManager().shutdown();
    }
}

From source file:org.artificer.test.AbstractIntegrationTest.java

protected ClientRequest clientRequest(String endpoint) {
    DefaultHttpClient client = new DefaultHttpClient();
    UsernamePasswordCredentials credentials = new UsernamePasswordCredentials(USERNAME, PASSWORD);
    client.getCredentialsProvider().setCredentials(new AuthScope(AuthScope.ANY), credentials);
    AuthCache authCache = new BasicAuthCache();
    BasicScheme basicAuth = new BasicScheme();
    HttpHost targetHost = new HttpHost(HOST, PORT);
    authCache.put(targetHost, basicAuth);
    BasicHttpContext localContext = new BasicHttpContext();
    localContext.setAttribute(ClientContext.AUTH_CACHE, authCache);
    ApacheHttpClient4Executor executor = new ApacheHttpClient4Executor(client, localContext);

    ClientRequest clientRequest = new ClientRequest(BASE_URL + endpoint, executor);
    return clientRequest;
}