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.codebutler.rsp.Util.java

public static String getURL(URL url, String password) throws Exception {
    Log.i("Util.getURL", url.toString());

    DefaultHttpClient client = new DefaultHttpClient();

    if (password != null && password.length() > 0) {
        UsernamePasswordCredentials creds;
        creds = new UsernamePasswordCredentials("user", password);
        client.getCredentialsProvider().setCredentials(AuthScope.ANY, creds);
    }//from w w w  . j av  a2s .  c o m

    HttpGet method = new HttpGet(url.toURI());
    BasicResponseHandler responseHandler = new BasicResponseHandler();
    return client.execute(method, responseHandler);
}

From source file:com.esri.geoportal.commons.utils.HttpClientContextBuilder.java

/**
 * Creates client context.//  w ww  . ja  v a2  s  .c  o m
 * @param url url
 * @param cred credentials
 * @return client context
 */
public static HttpClientContext createHttpClientContext(URL url, SimpleCredentials cred) {
    HttpHost targetHost = new HttpHost(url.getHost(), url.getPort(), url.getProtocol());
    CredentialsProvider credsProvider = new BasicCredentialsProvider();
    credsProvider.setCredentials(new AuthScope(targetHost.getHostName(), targetHost.getPort()),
            new UsernamePasswordCredentials(cred.getUserName(), cred.getPassword()));

    // Create AuthCache instance
    AuthCache authCache = new BasicAuthCache();
    // Generate BASIC scheme object and add it to the local auth cache
    BasicScheme basicAuth = new BasicScheme();
    authCache.put(targetHost, basicAuth);

    // Add AuthCache to the execution context
    HttpClientContext context = HttpClientContext.create();
    context.setCredentialsProvider(credsProvider);
    context.setAuthCache(authCache);

    return context;
}

From source file:su.fmi.photoshareclient.remote.LoginHandler.java

public static boolean login(String username, char[] password) {
    try {/*from  w  w  w  . j  ava  2  s.  com*/
        ProjectProperties properties = new ProjectProperties();
        HttpClient client = new DefaultHttpClient();
        HttpPost post = new HttpPost(
                "http://" + properties.get("socket") + properties.get("restEndpoint") + "/user/login");
        StringEntity input = new StringEntity(
                "{\"username\":\"" + username + "\",\"password\":\"" + new String(password) + "\"}",
                ContentType.create("application/json"));
        post.setHeader("Content-Type", "application/json");
        post.addHeader(BasicScheme.authenticate(new UsernamePasswordCredentials(username, new String(password)),
                "UTF-8", false));
        post.setEntity(input);

        if (username.isEmpty() || password.length == 0) {
            return false;
        }
        HttpResponse response = (HttpResponse) client.execute(post);
        if (response.getStatusLine().getStatusCode() == 200) {
            String authString = username + ":" + new String(password);
            byte[] authEncBytes = Base64.encodeBase64(authString.getBytes());
            authStringEncr = new String(authEncBytes);
            return true;
        } else {
            return false;
        }
    } catch (UnsupportedEncodingException ex) {
        Logger.getLogger(LoginGUI.class.getName()).log(Level.SEVERE, null, ex);
    } catch (IOException ex) {
        Logger.getLogger(LoginGUI.class.getName()).log(Level.SEVERE, null, ex);
    }
    return false;
}

From source file:nl.surfnet.sab.SabClientIntegrationTest.java

@Test
@Ignore/*ww w.  j av  a2 s  .  c o m*/
public void test() throws IOException {

    UsernamePasswordCredentials credentials = new UsernamePasswordCredentials("x", "x");
    HttpClientTransport transport = new HttpClientTransport(credentials, credentials, URI.create("x"),
            URI.create("y"));
    SabClient sabClient = new SabClient(transport);
    SabRoleHolder roles = sabClient.getRoles("x");
    System.out.println(roles);
}

From source file:org.talend.components.elasticsearch.runtime_2_4.ElasticsearchConnection.java

public static RestClient createClient(ElasticsearchDatastoreProperties datastore) throws MalformedURLException {
    String urlStr = datastore.nodes.getValue();
    String[] urls = urlStr.split(",");
    HttpHost[] hosts = new HttpHost[urls.length];
    int i = 0;/*  w  w w . ja va2s .c om*/
    for (String address : urls) {
        URL url = new URL("http://" + address);
        hosts[i] = new HttpHost(url.getHost(), url.getPort(), url.getProtocol());
        i++;
    }
    RestClientBuilder restClientBuilder = RestClient.builder(hosts);
    if (datastore.auth.useAuth.getValue()) {
        final CredentialsProvider credentialsProvider = new BasicCredentialsProvider();
        credentialsProvider.setCredentials(AuthScope.ANY, new UsernamePasswordCredentials(
                datastore.auth.userId.getValue(), datastore.auth.password.getValue()));
        restClientBuilder.setHttpClientConfigCallback(new RestClientBuilder.HttpClientConfigCallback() {

            public HttpAsyncClientBuilder customizeHttpClient(HttpAsyncClientBuilder httpAsyncClientBuilder) {
                return httpAsyncClientBuilder.setDefaultCredentialsProvider(credentialsProvider);
            }
        });
    }
    return restClientBuilder.build();
}

From source file:com.sinfonier.util.JSonUtils.java

public static void sendPostDucksBoard(Map<String, Object> json, String url, String apiKey) {
    HttpClient httpClient = new DefaultHttpClient();
    Gson gson = new GsonBuilder().create();
    String payload = gson.toJson(json);

    HttpPost post = new HttpPost(url);
    post.setEntity(new ByteArrayEntity(payload.getBytes(Charset.forName("UTF-8"))));
    post.setHeader("Content-type", "application/json");

    try {/*w w w  .  j a  v a 2 s.  c  om*/
        post.setHeader(new BasicScheme().authenticate(new UsernamePasswordCredentials(apiKey, "x"), post));
    } catch (AuthenticationException e) {
        e.printStackTrace();
    }

    try {
        HttpResponse response = httpClient.execute(post);
    } catch (IOException e) {
        e.printStackTrace();
    }
}

From source file:org.pentaho.reporting.designer.core.auth.AuthenticationHelper.java

public static Credentials getCredentials(final String user, final String password) {
    if (StringUtils.isEmpty(user)) {
        return null;
    }//from w  w w  .j av  a2  s .  c o m

    final Configuration config = ReportDesignerBoot.getInstance().getGlobalConfig();
    if ("true".equals(config.getConfigProperty(NT_AUTH_CONFIGKEY, "false")) == false) {
        return new UsernamePasswordCredentials(user, password);
    }

    final int domainIdx = user.indexOf(DOMAIN_SEPARATOR);
    if (domainIdx == -1) {
        return new UsernamePasswordCredentials(user, password);
    }
    try {
        final String domain = user.substring(0, domainIdx);
        final String username = user.substring(domainIdx + 1);
        final String host = InetAddress.getLocalHost().getHostName();
        return new NTCredentials(username, password, host, domain);
    } catch (UnknownHostException uhe) {
        return new UsernamePasswordCredentials(user, password);
    }
}

From source file:be.uclouvain.multipathcontrol.stats.HttpUtils.java

public static HttpClient getHttpClient(int timeout) {
    if (ConfigServer.hostname.isEmpty())
        return null;

    DefaultHttpClient defaultHttpClient;
    if (timeout > 0)
        defaultHttpClient = new DefaultHttpClient(getParamTimeout(timeout));
    else/*from   w w w.j  ava 2s  . c  o m*/
        defaultHttpClient = new DefaultHttpClient();
    if (ConfigServer.username != null && !ConfigServer.username.isEmpty()) {
        Credentials creds = new UsernamePasswordCredentials(ConfigServer.username, ConfigServer.password);
        AuthScope scope = new AuthScope(ConfigServer.hostname, ConfigServer.port);
        CredentialsProvider credProvider = defaultHttpClient.getCredentialsProvider();
        credProvider.setCredentials(scope, creds);
    }
    return defaultHttpClient;
}

From source file:org.springframework.cloud.stream.binder.rabbit.admin.RabbitManagementUtils.java

public static RestTemplate buildRestTemplate(String adminUri, String user, String password) {
    BasicCredentialsProvider credsProvider = new BasicCredentialsProvider();
    credsProvider.setCredentials(new AuthScope(AuthScope.ANY_HOST, AuthScope.ANY_PORT),
            new UsernamePasswordCredentials(user, password));
    HttpClient httpClient = HttpClients.custom().setDefaultCredentialsProvider(credsProvider).build();
    // Set up pre-emptive basic Auth because the rabbit plugin doesn't currently support challenge/response for PUT
    // Create AuthCache instance
    AuthCache authCache = new BasicAuthCache();
    // Generate BASIC scheme object and add it to the local; from the apache docs...
    // auth cache
    BasicScheme basicAuth = new BasicScheme();
    URI uri;//from  w ww  . java 2  s .  c  o m
    try {
        uri = new URI(adminUri);
    } catch (URISyntaxException e) {
        throw new RabbitAdminException("Invalid URI", e);
    }
    authCache.put(new HttpHost(uri.getHost(), uri.getPort(), uri.getScheme()), basicAuth);
    // Add AuthCache to the execution context
    final HttpClientContext localContext = HttpClientContext.create();
    localContext.setAuthCache(authCache);
    RestTemplate restTemplate = new RestTemplate(new HttpComponentsClientHttpRequestFactory(httpClient) {

        @Override
        protected HttpContext createHttpContext(HttpMethod httpMethod, URI uri) {
            return localContext;
        }

    });
    restTemplate.setMessageConverters(
            Collections.<HttpMessageConverter<?>>singletonList(new MappingJackson2HttpMessageConverter()));
    return restTemplate;
}

From source file:org.ow2.bonita.facade.rest.apachehttpclient.ApacheHttpClientUtil.java

public static HttpClient getHttpClient(String serverAddress, String username, String password)
        throws URISyntaxException {
    URI serverURI = new URI(serverAddress);
    DefaultHttpClient client = new DefaultHttpClient();
    AuthScope authScope = new AuthScope(serverURI.getHost(), serverURI.getPort(), AuthScope.ANY_REALM,
            AuthScope.ANY_SCHEME);/*from   w  ww.j  a  va2s  . c om*/
    UsernamePasswordCredentials credentials = new UsernamePasswordCredentials(username, password);
    client.getCredentialsProvider().setCredentials(authScope, credentials);
    return client;
}