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.dasein.cloud.ibm.sce.SCEMethod.java

protected @Nonnull HttpClient getClient() throws InternalException {
    ProviderContext ctx = provider.getContext();

    if (ctx == null) {
        throw new SCEConfigException("No context was defined for this request");
    }/*from   ww w.  j av  a2 s.c om*/
    String endpoint = ctx.getEndpoint();

    if (endpoint == null) {
        throw new SCEConfigException("No cloud endpoint was defined");
    }
    boolean ssl = endpoint.startsWith("https");
    int targetPort;
    URI uri;

    try {
        uri = new URI(endpoint);
        targetPort = uri.getPort();
        if (targetPort < 1) {
            targetPort = (ssl ? 443 : 80);
        }
    } catch (URISyntaxException e) {
        throw new SCEConfigException(e);
    }
    HttpHost targetHost = new HttpHost(uri.getHost(), targetPort, uri.getScheme());
    HttpParams params = new BasicHttpParams();

    HttpProtocolParams.setVersion(params, HttpVersion.HTTP_1_1);
    //noinspection deprecation
    HttpProtocolParams.setContentCharset(params, HTTP.UTF_8);
    HttpProtocolParams.setUserAgent(params, "");

    Properties p = ctx.getCustomProperties();

    if (p != null) {
        String proxyHost = p.getProperty("proxyHost");
        String proxyPort = p.getProperty("proxyPort");

        if (proxyHost != null) {
            int port = 0;

            if (proxyPort != null && proxyPort.length() > 0) {
                port = Integer.parseInt(proxyPort);
            }
            params.setParameter(ConnRoutePNames.DEFAULT_PROXY,
                    new HttpHost(proxyHost, port, ssl ? "https" : "http"));
        }
    }
    DefaultHttpClient client = new DefaultHttpClient(params);

    try {
        String userName = new String(ctx.getAccessPublic(), "utf-8");
        String password = new String(ctx.getAccessPrivate(), "utf-8");

        client.getCredentialsProvider().setCredentials(
                new AuthScope(targetHost.getHostName(), targetHost.getPort()),
                new UsernamePasswordCredentials(userName, password));
    } catch (UnsupportedEncodingException e) {
        throw new InternalException(e);
    }
    return client;
}

From source file:org.dspace.identifier.doi.DataCiteConnector.java

/**
 * /*ww  w.  j  av a2  s.  c  o  m*/
 * @param req
 * @param doi
 * @return
 * @throws DOIIdentifierException 
 */
private DataCiteResponse sendHttpRequest(HttpUriRequest req, String doi) throws DOIIdentifierException {
    DefaultHttpClient httpclient = new DefaultHttpClient();
    httpclient.getCredentialsProvider().setCredentials(new AuthScope(HOST, 443),
            new UsernamePasswordCredentials(this.getUsername(), this.getPassword()));

    HttpEntity entity = null;
    try {
        HttpResponse response = httpclient.execute(req);

        StatusLine status = response.getStatusLine();
        int statusCode = status.getStatusCode();

        String content = null;
        entity = response.getEntity();
        if (null != entity) {
            content = EntityUtils.toString(entity, "UTF-8");
        }

        /* While debugging it can be useful to see whitch requests are send:
         *
         * log.debug("Going to send HTTP request of type " + req.getMethod() + ".");
         * log.debug("Will be send to " + req.getURI().toString() + ".");
         * if (req instanceof HttpEntityEnclosingRequestBase)
         * {
         *     log.debug("Request contains entity!");
         *     HttpEntityEnclosingRequestBase reqee = (HttpEntityEnclosingRequestBase) req;
         *     if (reqee.getEntity() instanceof StringEntity)
         *     {
         *         StringEntity se = (StringEntity) reqee.getEntity();
         *         try {
         *             BufferedReader br = new BufferedReader(new InputStreamReader(se.getContent()));
         *             String line = null;
         *             while ((line = br.readLine()) != null)
         *             {
         *                 log.debug(line);
         *             }
         *             log.info("----");
         *         } catch (IOException ex) {
         *             
         *         }
         *     }
         * } else {
         *     log.debug("Request contains no entity!");
         * }
         * log.debug("The request got http status code {}.", Integer.toString(statusCode));
         * if (null == content)
         * {
         *     log.debug("The response did not contain any answer.");
         * } else {
         *     log.debug("DataCite says: {}", content);
         * }
         * 
         */

        // We can handle some status codes here, others have to be handled above
        switch (statusCode) {
        // we get a 401 if we forgot to send credentials or if the username
        // and password did not match.
        case (401): {
            log.info("We were unable to authenticate against the DOI registry agency.");
            log.info("The response was: {}", content);
            throw new DOIIdentifierException("Cannot authenticate at the "
                    + "DOI registry agency. Please check if username " + "and password are set correctly.",
                    DOIIdentifierException.AUTHENTICATION_ERROR);
        }

        // We get a 403 Forbidden if we are managing a DOI that belongs to
        // another party or if there is a login problem.
        case (403): {
            log.info("Managing a DOI ({}) was prohibited by the DOI " + "registration agency: {}", doi,
                    content);
            throw new DOIIdentifierException(
                    "We can check, register or " + "reserve DOIs that belong to us only.",
                    DOIIdentifierException.FOREIGN_DOI);
        }

        // 500 is documented and signals an internal server error
        case (500): {
            log.warn("Caught an http status code 500 while managing DOI " + "{}. Message was: " + content);
            throw new DOIIdentifierException(
                    "DataCite API has an internal error. " + "It is temporarily impossible to manage DOIs. "
                            + "Further information can be found in DSpace log file.",
                    DOIIdentifierException.INTERNAL_ERROR);
        }
        }

        return new DataCiteResponse(statusCode, content);
    } catch (IOException e) {
        log.warn("Caught an IOException: " + e.getMessage());
        throw new RuntimeException(e);
    } finally {
        try {
            // Release any ressources used by HTTP-Request.
            if (null != entity) {
                EntityUtils.consume(entity);
            }
        } catch (IOException e) {
            log.warn("Can't release HTTP-Entity: " + e.getMessage());
        }
    }
}

From source file:org.keycloak.testsuite.federation.kerberos.AbstractKerberosTest.java

protected void initHttpClient(boolean useSpnego) {
    if (client != null) {
        cleanupApacheHttpClient();//from   ww w. j ava 2 s.  c  o  m
    }

    DefaultHttpClient httpClient = (DefaultHttpClient) new HttpClientBuilder().disableCookieCache(false)
            .build();

    httpClient.getAuthSchemes().register(AuthSchemes.SPNEGO, spnegoSchemeFactory);

    if (useSpnego) {
        Credentials fake = new Credentials() {

            @Override
            public String getPassword() {
                return null;
            }

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

        };

        httpClient.getCredentialsProvider().setCredentials(new AuthScope(null, -1, null), fake);
    }
    ApacheHttpClient4Engine engine = new ApacheHttpClient4Engine(httpClient);
    client = new ResteasyClientBuilder().httpEngine(engine).build();
}

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

@Test
public void testSetParams() {
    ModifiableSolrParams params = new ModifiableSolrParams();
    params.set(HttpClientUtil.PROP_ALLOW_COMPRESSION, true);
    params.set(HttpClientUtil.PROP_BASIC_AUTH_PASS, "pass");
    params.set(HttpClientUtil.PROP_BASIC_AUTH_USER, "user");
    params.set(HttpClientUtil.PROP_CONNECTION_TIMEOUT, 12345);
    params.set(HttpClientUtil.PROP_FOLLOW_REDIRECTS, true);
    params.set(HttpClientUtil.PROP_MAX_CONNECTIONS, 22345);
    params.set(HttpClientUtil.PROP_MAX_CONNECTIONS_PER_HOST, 32345);
    params.set(HttpClientUtil.PROP_SO_TIMEOUT, 42345);
    params.set(HttpClientUtil.PROP_USE_RETRY, false);
    DefaultHttpClient client = (DefaultHttpClient) HttpClientUtil.createClient(params);
    try {//from w  ww . j  a v  a  2  s  . co m
        assertEquals(12345, HttpConnectionParams.getConnectionTimeout(client.getParams()));
        assertEquals(PoolingClientConnectionManager.class, client.getConnectionManager().getClass());
        assertEquals(22345, ((PoolingClientConnectionManager) client.getConnectionManager()).getMaxTotal());
        assertEquals(32345,
                ((PoolingClientConnectionManager) client.getConnectionManager()).getDefaultMaxPerRoute());
        assertEquals(42345, HttpConnectionParams.getSoTimeout(client.getParams()));
        assertEquals(HttpClientUtil.NO_RETRY, client.getHttpRequestRetryHandler());
        assertEquals("pass",
                client.getCredentialsProvider().getCredentials(new AuthScope("127.0.0.1", 1234)).getPassword());
        assertEquals("user", client.getCredentialsProvider().getCredentials(new AuthScope("127.0.0.1", 1234))
                .getUserPrincipal().getName());
        assertEquals(true, client.getParams().getParameter(ClientPNames.HANDLE_REDIRECTS));
    } finally {
        client.close();
    }
}

From source file:org.smap.smapTask.android.tasks.DownloadTasksTask.java

private void updateTaskStatusToServer() throws Exception {

    DefaultHttpClient client = new DefaultHttpClient();
    HttpResponse getResponse = null;/* w  ww  .j  ava  2 s .  com*/
    TaskResponse updateResponse = new TaskResponse();
    updateResponse.forms = tr.forms;

    // Add credentials
    if (username != null && password != null) {
        client.getCredentialsProvider().setCredentials(new AuthScope(null, -1, null),
                new UsernamePasswordCredentials(username, password));
    }

    // Add device id to response
    updateResponse.deviceId = new PropertyManager(Collect.getInstance().getApplicationContext())
            .getSingularProperty(PropertyManager.DEVICE_ID_PROPERTY);

    // Get tasks that have not been synchronised
    ArrayList<TaskEntry> nonSynchTasks = new ArrayList<TaskEntry>();
    Utilities.getTasks(nonSynchTasks, true);

    /*
     * Set updates to task status
     */
    updateResponse.taskAssignments = new ArrayList<TaskAssignment>(); // Updates to task status

    for (TaskEntry t : nonSynchTasks) {
        if (t.taskStatus != null && t.isSynced.equals(Utilities.STATUS_SYNC_NO)) {
            TaskAssignment ta = new TaskAssignment();
            ta.assignment = new Assignment();
            ta.assignment.assignment_id = (int) t.assId;
            ta.assignment.dbId = (int) t.id;
            ta.assignment.assignment_status = t.taskStatus;

            updateResponse.taskAssignments.add(ta);
        }
    }

    /*
     * Set details on submitted tasks
     */
    if (tr.settings != null && tr.settings.ft_send_trail) {
        updateResponse.taskCompletionInfo = new ArrayList<TaskCompletionInfo>(); // Details on completed tasks

        for (TaskEntry t : nonSynchTasks) {
            if ((t.taskStatus.equals(Utilities.STATUS_T_SUBMITTED)
                    || t.taskStatus.equals(Utilities.STATUS_T_CLOSED))
                    && t.isSynced.equals(Utilities.STATUS_SYNC_NO)) {
                TaskCompletionInfo tci = new TaskCompletionInfo();
                tci.actFinish = t.actFinish;
                tci.lat = t.actLat;
                tci.lon = t.actLon;
                tci.ident = t.ident;
                tci.uuid = t.uuid;

                updateResponse.taskCompletionInfo.add(tci);
            }
        }

        // Get Points
        updateResponse.userTrail = new ArrayList<PointEntry>(100);
        TraceUtilities.getPoints(updateResponse.userTrail);
    }

    // Call the service
    String taskURL = serverUrl + "/surveyKPI/myassignments";
    HttpPost postRequest = new HttpPost(taskURL);
    ArrayList<NameValuePair> postParameters = new ArrayList<NameValuePair>();

    Gson gson = new GsonBuilder().disableHtmlEscaping().setDateFormat("yyyy-MM-dd").create();
    String resp = gson.toJson(updateResponse);

    postParameters.add(new BasicNameValuePair("assignInput", resp));

    postRequest.setEntity(new UrlEncodedFormEntity(postParameters));
    getResponse = client.execute(postRequest);

    int statusCode = getResponse.getStatusLine().getStatusCode();

    if (statusCode != HttpStatus.SC_OK) {
        Log.w(getClass().getSimpleName(), "Error:" + statusCode + " for URL " + taskURL);
    } else {
        Log.w("updateTaskStatusToServer", "Status updated");
        for (TaskAssignment ta : updateResponse.taskAssignments) {
            Utilities.setTaskSynchronized((long) ta.assignment.dbId); // Mark the task status as synchronised
        }
        TraceUtilities.deleteSource();
    }

}

From source file:org.talend.mdm.workbench.serverexplorer.console.MDMServerMessageConsole.java

private DefaultHttpClient createHttpClient() {
    DefaultHttpClient httpclient = new DefaultHttpClient();

    AuthScope authScope = new AuthScope(serverDef.getHost(), Integer.parseInt(serverDef.getPort()));
    UsernamePasswordCredentials credentials = new UsernamePasswordCredentials(serverDef.getUser(),
            serverDef.getPasswd());//ww w  .  j  a  v  a 2 s .  c om
    if (httpclient != null) {
        httpclient.getCredentialsProvider().setCredentials(authScope, credentials);
    }
    return httpclient;
}

From source file:org.callimachusproject.test.WebResource.java

public void patch(String type, byte[] body) throws IOException {
    ByteArrayEntity entity = new ByteArrayEntity(body);
    entity.setContentType(type);/*w ww .  j  a  v  a2 s  .c om*/
    HttpPatch req = new HttpPatch(uri);
    req.setEntity(entity);
    DefaultHttpClient client = new DefaultHttpClient();
    URL url = req.getURI().toURL();
    int port = url.getPort();
    String host = url.getHost();
    PasswordAuthentication passAuth = Authenticator.requestPasswordAuthentication(url.getHost(),
            InetAddress.getByName(url.getHost()), port, url.getProtocol(), "", "digest", url,
            RequestorType.SERVER);
    UsernamePasswordCredentials credentials = new UsernamePasswordCredentials(passAuth.getUserName(),
            new String(passAuth.getPassword()));
    client.getCredentialsProvider().setCredentials(new AuthScope(host, port), credentials);
    client.execute(req, new ResponseHandler<Void>() {
        public Void handleResponse(HttpResponse response) throws ClientProtocolException, IOException {
            StatusLine status = response.getStatusLine();
            int code = status.getStatusCode();
            if (code != 200 && code != 204) {
                Assert.assertEquals(status.getReasonPhrase(), 204, code);
            }
            return null;
        }
    });
}

From source file:org.jboss.as.test.integration.security.jaas.JAASIdentityCachingTestCase.java

/**
 * Test how many times is called login() method of {@link CustomLoginModule} and if the response from HelloBean is the
 * expected one./*from   w w w . j a  va  2 s  .com*/
 * 
 * @param webAppURL
 * @throws Exception
 */
@Test
public void test(@ArquillianResource URL webAppURL) throws Exception {
    final URI greetingUri = new URI(webAppURL.toExternalForm() + HelloEJBCallServlet.SERVLET_PATH.substring(1)
            + "?" + HelloEJBCallServlet.PARAM_JNDI_NAME + "="
            + URLEncoder.encode("java:app/" + JAR_BASE_NAME + "/" + HelloBean.class.getSimpleName(), "UTF-8"));
    final URI counterUri = new URI(webAppURL.toExternalForm() + LMCounterServlet.SERVLET_PATH.substring(1));
    LOGGER.info("Requesting URL " + greetingUri);
    final DefaultHttpClient httpClient = new DefaultHttpClient();
    try {
        final HttpGet getCounter = new HttpGet(counterUri);
        final HttpGet getGreeting = new HttpGet(greetingUri);
        HttpResponse response = httpClient.execute(getGreeting);
        assertEquals(HttpServletResponse.SC_UNAUTHORIZED, response.getStatusLine().getStatusCode());
        EntityUtils.consume(response.getEntity());

        //check if LoginModule #login() counter is initialized correctly
        response = httpClient.execute(getCounter);
        assertEquals("0", EntityUtils.toString(response.getEntity()));

        final UsernamePasswordCredentials credentials = new UsernamePasswordCredentials("admin",
                CustomLoginModule.PASSWORD);
        httpClient.getCredentialsProvider()
                .setCredentials(new AuthScope(greetingUri.getHost(), greetingUri.getPort()), credentials);

        //make 2 calls to the servlet
        response = httpClient.execute(getGreeting);
        assertEquals("Hello Caller!", EntityUtils.toString(response.getEntity()));
        response = httpClient.execute(getGreeting);
        assertEquals("Hello Caller!", EntityUtils.toString(response.getEntity()));

        //There should be only one call to login() method 
        response = httpClient.execute(getCounter);
        assertEquals("1", EntityUtils.toString(response.getEntity()));
    } finally {
        httpClient.getConnectionManager().shutdown();
    }
}

From source file:net.java.sip.communicator.service.httputil.HttpUtils.java

/**
 * Posting form to <tt>address</tt>. For submission we use POST method
 * which is "application/x-www-form-urlencoded" encoded.
 * @param address HTTP address./*from   www  . j  av  a2 s. com*/
 * @param usernamePropertyName the property to use to retrieve/store
 * username value if protected site is hit, for username
 * ConfigurationService service is used.
 * @param passwordPropertyName the property to use to retrieve/store
 * password value if protected site is hit, for password
 * CredentialsStorageService service is used.
 * @param formParamNames the parameter names to include in post.
 * @param formParamValues the corresponding parameter values to use.
 * @param usernameParamIx the index of the username parameter in the
 * <tt>formParamNames</tt> and <tt>formParamValues</tt>
 * if any, otherwise -1.
 * @param passwordParamIx the index of the password parameter in the
 * <tt>formParamNames</tt> and <tt>formParamValues</tt>
 * if any, otherwise -1.
 * @param redirectHandler handles redirection, should we redirect and
 * the actual redirect.
 * @param headerParamNames additional header name to include
 * @param headerParamValues corresponding header value to include
 * @return the result or null if send was not possible or
 * credentials ask if any was canceled.
 */
public static HTTPResponseResult postForm(String address, String usernamePropertyName,
        String passwordPropertyName, ArrayList<String> formParamNames, ArrayList<String> formParamValues,
        int usernameParamIx, int passwordParamIx, RedirectHandler redirectHandler,
        List<String> headerParamNames, List<String> headerParamValues) throws Throwable {
    DefaultHttpClient httpClient;
    HttpPost postMethod;
    HttpEntity resEntity = null;

    // if any authentication exception rise while executing
    // will retry
    AuthenticationException authEx;
    HTTPCredentialsProvider credentialsProvider = null;
    do {
        postMethod = new HttpPost(address);
        httpClient = getHttpClient(usernamePropertyName, passwordPropertyName, postMethod.getURI().getHost(),
                credentialsProvider);

        try {
            // execute post
            resEntity = postForm(httpClient, postMethod, address, formParamNames, formParamValues,
                    usernameParamIx, passwordParamIx, redirectHandler, headerParamNames, headerParamValues);

            authEx = null;
        } catch (AuthenticationException ex) {
            authEx = ex;

            // lets reuse credentialsProvider
            credentialsProvider = (HTTPCredentialsProvider) httpClient.getCredentialsProvider();
            String userName = credentialsProvider.authUsername;

            // clear
            credentialsProvider.clear();

            // lets show the same username
            credentialsProvider.authUsername = userName;
            credentialsProvider.errorMessage = HttpUtilActivator.getResources().getI18NString(
                    "service.gui.AUTHENTICATION_FAILED",
                    new String[] { credentialsProvider.usedScope.getHost() });
        }
    } while (authEx != null);

    // canceled or no result
    if (resEntity == null)
        return null;

    return new HTTPResponseResult(resEntity, httpClient);
}

From source file:com.marklogic.client.functionaltest.ConnectedRESTQA.java

public static void deleteForest(String fName) {
    try {// w  ww .ja v  a2  s.c  om
        DefaultHttpClient client = new DefaultHttpClient();
        client.getCredentialsProvider().setCredentials(new AuthScope("localhost", 8002),
                new UsernamePasswordCredentials("admin", "admin"));

        HttpDelete delete = new HttpDelete("http://localhost:8002/manage/v2/forests/" + fName + "?level=full");
        client.execute(delete);

    } catch (Exception e) {
        // writing error to Log
        e.printStackTrace();
    }
}