Example usage for org.apache.http.auth UsernamePasswordCredentials UsernamePasswordCredentials

List of usage examples for org.apache.http.auth UsernamePasswordCredentials UsernamePasswordCredentials

Introduction

In this page you can find the example usage for org.apache.http.auth UsernamePasswordCredentials UsernamePasswordCredentials.

Prototype

public UsernamePasswordCredentials(final String userName, final String password) 

Source Link

Document

The constructor with the username and password arguments.

Usage

From source file:com.cloudapp.rest.CloudApi.java

public CloudApi(String mail, String pw) {
    client = new DefaultHttpClient();
    client.setReuseStrategy(new DefaultConnectionReuseStrategy());

    // Try to authenticate.
    AuthScope scope = new AuthScope("my.cl.ly", 80);
    client.getCredentialsProvider().setCredentials(scope, new UsernamePasswordCredentials(mail, pw));
}

From source file:com.microsoft.azure.hdinsight.spark.common.SparkBatchSubmission.java

/**
 * Set http request credential using username and password
 * @param username : username/*  w ww.jav a2s.  c om*/
 * @param password : password
 */
public void setCredentialsProvider(String username, String password) {
    credentialsProvider.setCredentials(new AuthScope(AuthScope.ANY),
            new UsernamePasswordCredentials(username, password));
}

From source file:de.onyxbits.raccoon.gplay.PlayManager.java

/**
 * create a proxy client/* w w  w .ja  v  a 2s  .  co  m*/
 * 
 * @return either a client or null if none is configured
 * @throws KeyManagementException
 * @throws NumberFormatException
 *           if that port could not be parsed.
 * @throws NoSuchAlgorithmException
 */
private static HttpClient createProxyClient(PlayProfile profile)
        throws KeyManagementException, NoSuchAlgorithmException {
    if (profile.getProxyAddress() == null) {
        return null;
    }

    PoolingClientConnectionManager connManager = new PoolingClientConnectionManager(
            SchemeRegistryFactory.createDefault());
    connManager.setMaxTotal(100);
    connManager.setDefaultMaxPerRoute(30);

    DefaultHttpClient client = new DefaultHttpClient(connManager);
    client.getConnectionManager().getSchemeRegistry().register(Utils.getMockedScheme());
    HttpHost proxy = new HttpHost(profile.getProxyAddress(), profile.getProxyPort());
    client.getParams().setParameter(ConnRoutePNames.DEFAULT_PROXY, proxy);
    if (profile.getProxyUser() != null && profile.getProxyPassword() != null) {
        client.getCredentialsProvider().setCredentials(new AuthScope(proxy),
                new UsernamePasswordCredentials(profile.getProxyUser(), profile.getProxyPassword()));
    }
    return client;
}

From source file:ro.cosu.vampires.server.rest.controllers.AbstractControllerTest.java

protected static HttpClient getHttpClient() {
    CredentialsProvider credsProvider = new BasicCredentialsProvider();
    credsProvider.setCredentials(AuthScope.ANY,
            new UsernamePasswordCredentials(User.admin().id(), User.admin().id()));
    return HttpClientBuilder.create().setDefaultCredentialsProvider(credsProvider).build();
}

From source file:com.mockey.model.ProxyServerModel.java

public Credentials getCredentials() {
    String username = getProxyUsername();
    String pass = getProxyPassword();
    if (username == null) {
        username = "";
    }//ww w.  j  ava 2  s  . c  o  m
    if (pass == null) {
        username = "";
    }
    // Can't pass null
    return new UsernamePasswordCredentials(username, pass);
}

From source file:org.zalando.stups.tokens.CloseableHttpProvider.java

public CloseableHttpProvider(ClientCredentials clientCredentials, UserCredentials userCredentials,
        URI accessTokenUri, HttpConfig httpConfig) {
    this.userCredentials = userCredentials;
    this.accessTokenUri = accessTokenUri;
    requestConfig = RequestConfig.custom().setSocketTimeout(httpConfig.getSocketTimeout())
            .setConnectTimeout(httpConfig.getConnectTimeout())
            .setConnectionRequestTimeout(httpConfig.getConnectionRequestTimeout())
            .setStaleConnectionCheckEnabled(httpConfig.isStaleConnectionCheckEnabled()).build();

    // prepare basic auth credentials
    final CredentialsProvider credentialsProvider = new BasicCredentialsProvider();
    credentialsProvider.setCredentials(new AuthScope(accessTokenUri.getHost(), accessTokenUri.getPort()),
            new UsernamePasswordCredentials(clientCredentials.getId(), clientCredentials.getSecret()));

    client = HttpClients.custom().setDefaultCredentialsProvider(credentialsProvider).build();

    host = new HttpHost(accessTokenUri.getHost(), accessTokenUri.getPort(), accessTokenUri.getScheme());

    // enable basic auth for the request
    final AuthCache authCache = new BasicAuthCache();
    final BasicScheme basicAuth = new BasicScheme();
    authCache.put(host, basicAuth);//from   ww w .j  a va 2 s. c  o m

    localContext = HttpClientContext.create();
    localContext.setAuthCache(authCache);
}

From source file:com.appdynamics.monitors.varnish.VarnishWrapper.java

/**
 * Gets the JsonObject by parsing the JSON return from hitting the /stats url
 * @return  JsonObject containing the response from hitting the /stats url for Varnish
 * @throws  Exception/* ww  w.jav a2 s.  c  om*/
 */
private JsonObject getResponseData() throws Exception {
    String metricsURL = constructVarnishStatsURL();
    HttpGet httpGet = new HttpGet(metricsURL);
    httpGet.addHeader(
            BasicScheme.authenticate(new UsernamePasswordCredentials(username, password), "UTF-8", false));

    HttpClient httpClient = new DefaultHttpClient();
    HttpResponse response = httpClient.execute(httpGet);
    HttpEntity entity = response.getEntity();
    BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(entity.getContent()));
    StringBuilder responseString = new StringBuilder();
    String line = "";
    while ((line = bufferedReader.readLine()) != null) {
        responseString.append(line);
    }
    JsonObject responseData = new JsonParser().parse(responseString.toString()).getAsJsonObject();
    return responseData;
}

From source file:org.surfnet.example.api.oauth.OAuthAuthorizeResource.java

@POST
public Response login(@FormParam("username") String username, @FormParam("password") String password,
        @FormParam("redirect_uri") String redirectUri, @FormParam("client_id") String clientId,
        @FormParam("state") String state) {
    /*//from   ww  w .  j av  a 2s .c o  m
     * Hook for implementing consent screen (which we currently don't have) 
     */

    /*
     * From the OAuth spec:
     * 
     * HTTP/1.1 302 Found Location:
     * https://client.example.com/cb?code=SplxlOBeZQQYbYS6WxSbIA &state=xyz
     */
    Student principal = principalService.getPrincipal(new UsernamePasswordCredentials(username, password));
    String authorizationCode = tokenStore
            .storeAuthorizationCode(new ClientDetails().setResponseType("code").setClientId(clientId)
                    .setRedirectUri(redirectUri).setScope("read").setState(state).setPrincipal(principal));
    /*
     * Hook for implementation of Implicit Grant flow
     */
    if (principal != null && authorizationCode != null) {
        String uri = String.format(redirectUri.concat("?").concat("code=%s").concat("&state=%s"),
                authorizationCode, state);
        try {
            return Response.seeOther(new URI(uri)).build();
        } catch (URISyntaxException e) {
            throw new RuntimeException(String.format("Redirect URI '%s' is not valid", uri));
        }
    } else {
        return Response.status(Response.Status.UNAUTHORIZED).build();
    }
}

From source file:com.deliciousdroid.client.NetworkUtilities.java

/**
 * Attempts to authenticate to Pinboard using a legacy Pinboard account.
 * //from   ww  w.ja v a 2 s . co  m
 * @param username The user's username.
 * @param password The user's password.
 * @param handler The hander instance from the calling UI thread.
 * @param context The context of the calling Activity.
 * @return The boolean result indicating whether the user was
 *         successfully authenticated.
 */
public static boolean pinboardAuthenticate(String username, String password) {
    final HttpResponse resp;

    Uri.Builder builder = new Uri.Builder();
    builder.scheme(SCHEME);
    builder.authority(DELICIOUS_AUTHORITY);
    builder.appendEncodedPath("v1/posts/update");
    Uri uri = builder.build();

    HttpGet request = new HttpGet(String.valueOf(uri));

    DefaultHttpClient client = (DefaultHttpClient) HttpClientFactory.getThreadSafeClient();

    CredentialsProvider provider = client.getCredentialsProvider();
    Credentials credentials = new UsernamePasswordCredentials(username, password);
    provider.setCredentials(SCOPE, credentials);

    try {
        resp = client.execute(request);
        if (resp.getStatusLine().getStatusCode() == HttpStatus.SC_OK) {
            if (Log.isLoggable(TAG, Log.VERBOSE)) {
                Log.v(TAG, "Successful authentication");
            }
            return true;
        } else {
            if (Log.isLoggable(TAG, Log.VERBOSE)) {
                Log.v(TAG, "Error authenticating" + resp.getStatusLine());
            }
            return false;
        }
    } catch (final IOException e) {
        if (Log.isLoggable(TAG, Log.VERBOSE)) {
            Log.v(TAG, "IOException when getting authtoken", e);
        }
        return false;
    } finally {
        if (Log.isLoggable(TAG, Log.VERBOSE)) {
            Log.v(TAG, "getAuthtoken completing");
        }
    }
}

From source file:io.kyligence.benchmark.loadtest.client.RestClient.java

private void init(String host, int port, String userName, String password) {
    this.host = host;
    this.port = port;
    this.userName = userName;
    this.password = password;
    this.baseUrl = "http://" + host + ":" + port + "/kylin/api";

    client = new DefaultHttpClient();

    if (userName != null && password != null) {
        CredentialsProvider provider = new BasicCredentialsProvider();
        UsernamePasswordCredentials credentials = new UsernamePasswordCredentials(userName, password);
        provider.setCredentials(AuthScope.ANY, credentials);
        client.setCredentialsProvider(provider);
    }/*from ww  w  .  j  a  va  2  s. c om*/
    client.getParams().setParameter(CoreConnectionPNames.CONNECTION_TIMEOUT, ONE_HOUR_IN_MS);
    client.getParams().setParameter(CoreConnectionPNames.SO_TIMEOUT, ONE_HOUR_IN_MS);
}