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.sonatype.nexus.plugins.webhook.WebHookNotifier.java

/**
 * Instantiate a new {@link HttpClient} instance, configured to accept all SSL certificates, and use proxy settings
 * from Nexus./*from   ww w.j ava  2 s  .co  m*/
 * 
 * @return an {@link HttpClient} instance - won't be null
 */
private HttpClient instantiateHttpClient() {
    DefaultHttpClient httpClient = new DefaultHttpClient();

    // configure user-agent
    HttpProtocolParams.setUserAgent(httpClient.getParams(), "Nexus WebHook Plugin");

    // configure SSL
    SSLSocketFactory socketFactory = null;
    try {
        socketFactory = new SSLSocketFactory(new TrustStrategy() {

            public boolean isTrusted(X509Certificate[] chain, String authType) throws CertificateException {
                return true;
            }
        }, SSLSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER);
    } catch (KeyManagementException e) {
        throw new RuntimeException(e);
    } catch (UnrecoverableKeyException e) {
        throw new RuntimeException(e);
    } catch (NoSuchAlgorithmException e) {
        throw new RuntimeException(e);
    } catch (KeyStoreException e) {
        throw new RuntimeException(e);
    }
    httpClient.getConnectionManager().getSchemeRegistry().register(new Scheme("https", 443, socketFactory));

    // configure proxy
    if (proxySettings != null && proxySettings.isEnabled()) {
        HttpHost proxy = new HttpHost(proxySettings.getHostname(), proxySettings.getPort());
        if (UsernamePasswordRemoteAuthenticationSettings.class
                .isInstance(proxySettings.getProxyAuthentication())) {
            UsernamePasswordRemoteAuthenticationSettings proxyAuthentication = (UsernamePasswordRemoteAuthenticationSettings) proxySettings
                    .getProxyAuthentication();
            httpClient.getCredentialsProvider().setCredentials(
                    new AuthScope(proxySettings.getHostname(), proxySettings.getPort()),
                    new UsernamePasswordCredentials(proxyAuthentication.getUsername(),
                            proxyAuthentication.getPassword()));
        }
        httpClient.getParams().setParameter(ConnRoutePNames.DEFAULT_PROXY, proxy);
    }

    return httpClient;
}

From source file:org.talend.core.nexus.HttpClientTransport.java

public void doRequestOne(IProgressMonitor monitor, final URI requestURI) throws Exception {
    if (monitor == null) {
        monitor = new NullProgressMonitor();
    }/*from  w  w  w.  ja v a2  s  .c o m*/
    if (monitor.isCanceled()) {
        throw new OperationCanceledException();
    }
    if (requestURI == null) {
        return;
    }
    DefaultHttpClient httpClient = new DefaultHttpClient();

    IProxySelectorProvider proxySelectorProvider = null;
    try {
        if (StringUtils.isNotBlank(username)) { // set username
            httpClient.getCredentialsProvider().setCredentials(
                    new AuthScope(requestURI.getHost(), requestURI.getPort()),
                    new UsernamePasswordCredentials(username, password));
        }
        int timeout = NexusServerUtils.getTimeout();
        IDesignerCoreService designerCoreService = CoreRuntimePlugin.getInstance().getDesignerCoreService();
        if (designerCoreService != null) {
            timeout = designerCoreService.getTACConnectionTimeout() * 1000;
        }
        HttpParams params = httpClient.getParams();
        params.setIntParameter(CoreConnectionPNames.CONNECTION_TIMEOUT, timeout);
        params.setIntParameter(CoreConnectionPNames.SO_TIMEOUT, timeout);

        proxySelectorProvider = addProxy(httpClient, requestURI);
        HttpResponse response = execute(monitor, httpClient, requestURI);

        processResponseCode(response);
    } catch (org.apache.http.conn.HttpHostConnectException e) {
        // connection failure
        throw e;
    } catch (java.net.SocketTimeoutException e) {
        // Read timed out
        throw e;
    } catch (Exception e) {
        throw new Exception(requestURI.toString(), e);
    } finally {
        httpClient.getConnectionManager().shutdown();
        removeProxy(proxySelectorProvider);
    }
}

From source file:org.talend.core.nexus.HttpClientTransport.java

private IProxySelectorProvider addProxy(final DefaultHttpClient httpClient, URI requestURI) {
    IProxySelectorProvider proxySelectorProvider = null;
    try {//from   ww  w . j a  v a 2  s  .c o m
        if (Boolean.valueOf(
                System.getProperty(PROP_PROXY_HTTP_CLIENT_USE_DEFAULT_SETTINGS, Boolean.FALSE.toString()))) {
            return proxySelectorProvider;
        }
        final List<Proxy> proxyList = TalendProxySelector.getInstance().getDefaultProxySelector()
                .select(requestURI);
        Proxy usedProxy = null;
        if (proxyList != null && !proxyList.isEmpty()) {
            usedProxy = proxyList.get(0);
        }

        if (usedProxy != null) {
            if (Type.DIRECT.equals(usedProxy.type())) {
                return proxySelectorProvider;
            }
            final Proxy finalProxy = usedProxy;
            InetSocketAddress address = (InetSocketAddress) finalProxy.address();
            String proxyServer = address.getHostName();
            int proxyPort = address.getPort();
            PasswordAuthentication proxyAuthentication = Authenticator.requestPasswordAuthentication(
                    proxyServer, address.getAddress(), proxyPort, "Http Proxy", "Http proxy authentication",
                    null);
            if (proxyAuthentication != null) {
                String proxyUser = proxyAuthentication.getUserName();
                if (StringUtils.isNotBlank(proxyUser)) {
                    String proxyPassword = "";
                    char[] passwordChars = proxyAuthentication.getPassword();
                    if (passwordChars != null) {
                        proxyPassword = new String(passwordChars);
                    }
                    httpClient.getCredentialsProvider().setCredentials(new AuthScope(proxyServer, proxyPort),
                            new UsernamePasswordCredentials(proxyUser, proxyPassword));
                }
            }
            HttpHost proxyHost = new HttpHost(proxyServer, proxyPort);
            httpClient.getParams().setParameter(ConnRoutePNames.DEFAULT_PROXY, proxyHost);
            proxySelectorProvider = createProxySelectorProvider();
        }
        return proxySelectorProvider;
    } finally {
        if (proxySelectorProvider != null) {
            TalendProxySelector.getInstance().addProxySelectorProvider(proxySelectorProvider);
        }
    }
}

From source file:org.wso2.bps.integration.common.clients.bpmn.ActivitiRestClient.java

/**
 * This Method is used to deploy BPMN packages to the BPMN Server
 *
 * @param fileName The name of the Package to be deployed
 * @param filePath The location of the BPMN package to be deployed
 * @throws java.io.IOException//from  w w  w.  j  av a 2 s.c o  m
 * @throws org.json.JSONException
 * @returns String array with status, deploymentID and Name
 */
public String[] deployBPMNPackage(String filePath, String fileName) throws Exception {
    String url = serviceURL + "repository/deployments";

    HttpHost target = new HttpHost(hostname, port, "http");

    DefaultHttpClient httpClient = new DefaultHttpClient();
    httpClient.getCredentialsProvider().setCredentials(new AuthScope(target.getHostName(), target.getPort()),
            new UsernamePasswordCredentials(username, password));

    HttpPost httpPost = new HttpPost(url);

    MultipartEntityBuilder builder = MultipartEntityBuilder.create();
    builder.addBinaryBody("file", new File(filePath), ContentType.MULTIPART_FORM_DATA, fileName);
    HttpEntity multipart = builder.build();
    httpPost.setEntity(multipart);
    HttpResponse response = httpClient.execute(httpPost);
    String status = response.getStatusLine().toString();
    String responseData = EntityUtils.toString(response.getEntity());
    JSONObject jsonResponseObject = new JSONObject(responseData);
    if (status.contains(Integer.toString(HttpStatus.SC_CREATED))
            || status.contains(Integer.toString(HttpStatus.SC_OK))) {
        String deploymentID = jsonResponseObject.getString("id");
        String name = jsonResponseObject.getString("name");
        return new String[] { status, deploymentID, name };
    } else if (status.contains(Integer.toString(HttpStatus.SC_INTERNAL_SERVER_ERROR))) {

        String errorMessage = jsonResponseObject.getString("errorMessage");
        throw new RestClientException(errorMessage);
        //            return new String[]{status, errorMessage};
    } else {
        throw new RestClientException("Failed to deploy package " + fileName);
    }
}

From source file:org.wso2.bps.integration.common.clients.bpmn.ActivitiRestClient.java

/**
 * Method is used to acquire deployment details using the deployment ID
 *
 * @param deploymentID Deployment ID of the BPMN Package
 * @throws java.io.IOException/*from   www .  j a va  2s .c  o m*/
 * @throws org.json.JSONException
 * @returns String Array with status, deploymentID and Name
 */
public String[] getDeploymentInfoById(String deploymentID) throws Exception {

    String url = serviceURL + "repository/deployments/" + deploymentID;
    HttpHost target = new HttpHost(hostname, port, "http");

    DefaultHttpClient httpClient = new DefaultHttpClient();
    httpClient.getCredentialsProvider().setCredentials(new AuthScope(target.getHostName(), target.getPort()),
            new UsernamePasswordCredentials(username, password));

    HttpGet httpget = new HttpGet(url);
    HttpResponse response = httpClient.execute(httpget);
    String status = response.getStatusLine().toString();
    String responseData = EntityUtils.toString(response.getEntity());
    JSONObject jsonResponseObject = new JSONObject(responseData);
    if (status.contains(Integer.toString(HttpStatus.SC_CREATED))
            || status.contains(Integer.toString(HttpStatus.SC_OK))) {
        String ID = jsonResponseObject.getString("id");
        String name = jsonResponseObject.getString("name");
        return new String[] { status, ID, name };
    } else if (status.contains(Integer.toString(HttpStatus.SC_NOT_FOUND))) {
        throw new RestClientException(NOT_AVAILABLE);
    } else {
        throw new RestClientException("Cannot find deployment");
    }
}

From source file:org.wso2.bps.integration.common.clients.bpmn.ActivitiRestClient.java

/**
 * Method is used to undeploy/remove a deployment from the server
 *
 * @param deploymentID used to identify the deployment to be removed
 * @return String with the Status//from w w  w  .  jav a 2s .  c  o m
 * @throws IOException
 */

public String unDeployBPMNPackage(String deploymentID) throws IOException {

    String url = serviceURL + "repository/deployments/" + deploymentID;
    HttpHost target = new HttpHost(hostname, port, "http");
    DefaultHttpClient httpClient = new DefaultHttpClient();
    httpClient.getCredentialsProvider().setCredentials(new AuthScope(target.getHostName(), target.getPort()),
            new UsernamePasswordCredentials(username, password));
    HttpDelete httpDelete = new HttpDelete(url);
    HttpResponse response = httpClient.execute(httpDelete);
    return response.getStatusLine().toString();
}

From source file:org.wso2.bps.integration.common.clients.bpmn.ActivitiRestClient.java

/**
 * Method to find the definitionID which is necessary to start a process instance
 *
 * @param deploymentID the deployment id is used to identify the deployment uniquely
 * @return String Array containing status and definitionID
 * @throws IOException/*from w w  w.  ja v  a  2  s. c  om*/
 * @throws JSONException
 */
public String[] findProcessDefinitionInfoById(String deploymentID) throws IOException, JSONException {
    String url = serviceURL + "repository/process-definitions";
    String definitionId = "";
    HttpHost target = new HttpHost(hostname, port, "http");
    DefaultHttpClient httpClient = new DefaultHttpClient();
    httpClient.getCredentialsProvider().setCredentials(new AuthScope(target.getHostName(), target.getPort()),
            new UsernamePasswordCredentials(username, password));

    HttpGet httpget = new HttpGet(url);
    HttpResponse response = httpClient.execute(httpget);

    String status = response.getStatusLine().toString();
    String responseData = EntityUtils.toString(response.getEntity());
    JSONObject jsonResponseObject = new JSONObject(responseData);
    JSONArray data = jsonResponseObject.getJSONArray("data");

    int responseObjectSize = Integer.parseInt(jsonResponseObject.get("total").toString());

    for (int j = 0; j < responseObjectSize; j++) {
        if (data.getJSONObject(j).getString("deploymentId").equals(deploymentID)) {
            definitionId = data.getJSONObject(j).getString("id");
        }
    }
    return new String[] { status, definitionId };

}

From source file:org.wso2.bps.integration.common.clients.bpmn.ActivitiRestClient.java

/**
 * Methods used to test/search if the specify process instance is present
 *
 * @param processDefintionID used to start a processInstance
 * @return String which contains the status
 * @throws IOException/*w  w w .  j av a  2s .  co m*/
 */
public String searchProcessInstanceByDefintionID(String processDefintionID) throws IOException {
    String url = serviceURL + "query/process-instances";

    HttpHost target = new HttpHost(hostname, port, "http");
    DefaultHttpClient httpClient = new DefaultHttpClient();
    httpClient.getCredentialsProvider().setCredentials(new AuthScope(target.getHostName(), target.getPort()),
            new UsernamePasswordCredentials(username, password));

    HttpPost httpPost = new HttpPost(url);
    StringEntity params = new StringEntity("{\"processDefinitionId\":\"" + processDefintionID + "\"}",
            ContentType.APPLICATION_JSON);
    httpPost.setEntity(params);
    HttpResponse response = httpClient.execute(httpPost);
    String status = response.getStatusLine().toString();
    return status;
}

From source file:org.wso2.bps.integration.common.clients.bpmn.ActivitiRestClient.java

/**
 * This method is used to validate/check if the process instance is present or not
 *
 * @param processDefinitionID used to identify the process instance
 * @return a String value of the status//ww w .ja  va  2 s .c  om
 * @throws IOException
 * @throws JSONException
 */
public String validateProcessInstanceById(String processDefinitionID) throws Exception {
    String url = serviceURL + "runtime/process-instances";
    HttpHost target = new HttpHost(hostname, port, "http");
    DefaultHttpClient httpClient = new DefaultHttpClient();
    httpClient.getCredentialsProvider().setCredentials(new AuthScope(target.getHostName(), target.getPort()),
            new UsernamePasswordCredentials(username, password));
    HttpGet httpget = new HttpGet(url);
    HttpResponse response = httpClient.execute(httpget);
    String responseData = EntityUtils.toString(response.getEntity());
    JSONObject jsonResponseObject = new JSONObject(responseData);
    JSONArray data = jsonResponseObject.getJSONArray("data");

    int responseObjectSize = Integer.parseInt(jsonResponseObject.get("total").toString());

    for (int j = 0; j < responseObjectSize; j++) {
        if (data.getJSONObject(j).getString("processDefinitionId").equals(processDefinitionID)) {
            return AVAILABLE;
        }
    }
    throw new RestClientException(NOT_AVAILABLE);
}

From source file:org.wso2.bps.integration.common.clients.bpmn.ActivitiRestClient.java

/**
 * Method use to instantiate a process instance using the definition ID
 *
 * @param processDefintionID used to start a processInstance
 * @throws IOException// w ww  . j  a  v  a 2s  .  c o  m
 * @throws JSONException
 * @returns String Array which contains status and processInstanceID
 */
public String[] startProcessInstanceByDefintionID(String processDefintionID) throws Exception {

    String url = serviceURL + "runtime/process-instances";

    HttpHost target = new HttpHost(hostname, port, "http");
    DefaultHttpClient httpClient = new DefaultHttpClient();
    httpClient.getCredentialsProvider().setCredentials(new AuthScope(target.getHostName(), target.getPort()),
            new UsernamePasswordCredentials(username, password));
    HttpPost httpPost = new HttpPost(url);
    StringEntity params = new StringEntity("{\"processDefinitionId\":\"" + processDefintionID + "\"}",
            ContentType.APPLICATION_JSON);
    httpPost.setEntity(params);
    HttpResponse response = httpClient.execute(httpPost);

    String status = response.getStatusLine().toString();
    String responseData = EntityUtils.toString(response.getEntity());
    JSONObject jsonResponseObject = new JSONObject(responseData);
    if (status.contains(Integer.toString(HttpStatus.SC_CREATED))
            || status.contains(Integer.toString(HttpStatus.SC_OK))) {
        String processInstanceID = jsonResponseObject.getString("id");
        return new String[] { status, processInstanceID };
    }
    throw new RestClientException("Cannot Find Process Instance");
}