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:org.openlmis.UiUtils.HttpClient.java

public ResponseEntity SendJSONWithoutHeaders(String json, String url, String commMethod, String username,
        String password) {//from   ww  w.  j ava 2  s  .com
    HttpHost targetHost = new HttpHost(HOST, PORT, PROTOCOL);
    AuthScope localhost = new AuthScope(HOST, PORT);

    UsernamePasswordCredentials credentials = new UsernamePasswordCredentials(username, password);
    httpClient.getCredentialsProvider().setCredentials(localhost, credentials);

    AuthCache authCache = new BasicAuthCache();
    authCache.put(targetHost, new BasicScheme());

    httpContext.setAttribute(AUTH_CACHE, authCache);

    try {
        return handleRequest(commMethod, json, url, false);
    } catch (Exception e) {
        e.printStackTrace();
    }
    return null;
}

From source file:org.fcrepo.server.utilities.ServerUtility.java

/**
 * Hits the given Fedora Server URL and returns the response as a String.
 * Throws an IOException if the response code is not 200(OK).
 */// www  .  jav a  2  s  .co m
private static String getServerResponse(String protocol, String user, String pass, String path)
        throws IOException {
    String url = getBaseURL(protocol) + path;
    logger.info("Getting URL: " + url);
    UsernamePasswordCredentials creds = new UsernamePasswordCredentials(user, pass);
    return s_webClient.getResponseAsString(url, true, creds);
}

From source file:org.eclipse.epp.internal.logging.aeri.ui.utils.Proxies.java

public static Executor proxyAuthentication(Executor executor, URI target) throws IOException {
    IProxyData proxy = getProxyData(target).orNull();
    if (proxy != null) {
        HttpHost proxyHost = new HttpHost(proxy.getHost(), proxy.getPort());
        if (proxy.getUserId() != null) {
            String userId = getUserName(proxy.getUserId()).orNull();
            String pass = proxy.getPassword();
            String workstation = getWorkstation().orNull();
            String domain = getUserDomain(proxy.getUserId()).orNull();
            return executor
                    .auth(new AuthScope(proxyHost, AuthScope.ANY_REALM, "ntlm"),
                            new NTCredentials(userId, pass, workstation, domain))
                    .auth(new AuthScope(proxyHost, AuthScope.ANY_REALM, AuthScope.ANY_SCHEME),
                            new UsernamePasswordCredentials(userId, pass));
        } else {/* w  w  w  .  jav  a2s . com*/
            return executor;
        }
    }
    return executor;
}

From source file:de.tsystems.mms.apm.performancesignature.viewer.rest.model.CustomJenkinsHttpClient.java

private static HttpClientBuilder createHttpClientBuilder(final boolean verifyCertificate,
        final CustomProxy customProxy) {

    HttpClientBuilder httpClientBuilder = HttpClients.custom();
    httpClientBuilder.useSystemProperties();
    if (!verifyCertificate) {
        SSLContextBuilder builder = new SSLContextBuilder();
        try {/*from   w w  w.  j av  a 2 s .c  o m*/
            builder.loadTrustMaterial(null, new TrustStrategy() {
                public boolean isTrusted(X509Certificate[] chain, String authType) throws CertificateException {
                    return true;
                }
            });
            httpClientBuilder.setSSLSocketFactory(new SSLConnectionSocketFactory(builder.build()));
        } catch (NoSuchAlgorithmException | KeyStoreException | KeyManagementException e) {
            LOGGER.severe(ExceptionUtils.getFullStackTrace(e));
        }

    }
    if (customProxy != null) {
        Jenkins jenkins = PerfSigUIUtils.getInstance();
        if (customProxy.isUseJenkinsProxy() && jenkins.proxy != null) {
            final ProxyConfiguration proxyConfiguration = jenkins.proxy;
            if (StringUtils.isNotBlank(proxyConfiguration.name) && proxyConfiguration.port > 0) {
                httpClientBuilder.setProxy(new HttpHost(proxyConfiguration.name, proxyConfiguration.port));
                if (StringUtils.isNotBlank(proxyConfiguration.getUserName())) {
                    CredentialsProvider credsProvider = new BasicCredentialsProvider();
                    UsernamePasswordCredentials usernamePasswordCredentials = new UsernamePasswordCredentials(
                            proxyConfiguration.getUserName(), proxyConfiguration.getUserName());
                    credsProvider.setCredentials(
                            new AuthScope(proxyConfiguration.name, proxyConfiguration.port),
                            usernamePasswordCredentials);
                    httpClientBuilder.setDefaultCredentialsProvider(credsProvider);
                    httpClientBuilder.setProxyAuthenticationStrategy(new ProxyAuthenticationStrategy());
                }
            }
        } else {
            httpClientBuilder.setProxy(new HttpHost(customProxy.getProxyServer(), customProxy.getProxyPort()));
            if (StringUtils.isNotBlank(customProxy.getProxyUser())
                    && StringUtils.isNotBlank(customProxy.getProxyPassword())) {
                CredentialsProvider credsProvider = new BasicCredentialsProvider();
                UsernamePasswordCredentials usernamePasswordCredentials = new UsernamePasswordCredentials(
                        customProxy.getProxyUser(), customProxy.getProxyPassword());
                credsProvider.setCredentials(
                        new AuthScope(customProxy.getProxyServer(), customProxy.getProxyPort()),
                        usernamePasswordCredentials);
                httpClientBuilder.setDefaultCredentialsProvider(credsProvider);
                httpClientBuilder.setProxyAuthenticationStrategy(new ProxyAuthenticationStrategy());
            }
        }
    }
    return httpClientBuilder;
}

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

public static void createDB(String dbName) {
    try {/*  w  w w  .  j  a va  2  s . co  m*/

        DefaultHttpClient client = new DefaultHttpClient();
        client.getCredentialsProvider().setCredentials(new AuthScope("localhost", 8002),
                new UsernamePasswordCredentials("admin", "admin"));

        HttpPost post = new HttpPost("http://localhost:8002" + "/manage/v2/databases?format=json");
        String JSONString = "[{\"database-name\":\"" + dbName + "\"}]";

        post.addHeader("Content-type", "application/json");
        post.setEntity(new StringEntity(JSONString));

        HttpResponse response = client.execute(post);
        HttpEntity respEntity = response.getEntity();

        if (respEntity != null) {
            // EntityUtils to get the response content
            String content = EntityUtils.toString(respEntity);
            System.out.println(content);
        }
    } catch (Exception e) {
        // writing error to Log
        e.printStackTrace();
    }
}

From source file:org.apache.sling.hapi.client.impl.AbstractHtmlClientImpl.java

public AbstractHtmlClientImpl(String baseUrl, String user, String password) throws URISyntaxException {
    this.baseUrl = new URI(baseUrl);
    HttpHost targetHost = URIUtils.extractHost(this.baseUrl);
    BasicCredentialsProvider credsProvider = new BasicCredentialsProvider();
    credsProvider.setCredentials(new AuthScope(targetHost.getHostName(), targetHost.getPort()),
            new UsernamePasswordCredentials(user, password));
    this.client = HttpClientBuilder.create().setDefaultCredentialsProvider(credsProvider)
            .setRedirectStrategy(new LaxRedirectStrategy()).build();
}

From source file:de.avanux.smartapplianceenabler.appliance.HttpTransactionExecutor.java

/**
 * Send a HTTP request whose response has to be closed by the caller!
 * @param url//from  w w w  . j a  va 2  s .c o m
 * @return
 */
protected CloseableHttpResponse sendHttpRequest(String url, String data, ContentType contentType,
        String username, String password) {
    HttpClientBuilder httpClientBuilder = HttpClientBuilder.create();
    if (username != null && password != null) {
        CredentialsProvider provider = new BasicCredentialsProvider();
        UsernamePasswordCredentials credentials = new UsernamePasswordCredentials(username, password);
        provider.setCredentials(AuthScope.ANY, credentials);
        httpClientBuilder.setDefaultCredentialsProvider(provider);
    }
    CloseableHttpClient client = httpClientBuilder.build();
    logger.debug("Sending HTTP request");
    logger.debug("url=" + url);
    logger.debug("data=" + data);
    logger.debug("contentType=" + contentType);
    logger.debug("username=" + username);
    logger.debug("password=" + password);
    try {
        HttpRequestBase request = null;
        if (data != null) {
            request = new HttpPost(url);
            ((HttpPost) request).setEntity(new StringEntity(data, contentType));
        } else {
            request = new HttpGet(url);
        }
        CloseableHttpResponse response = client.execute(request);
        int responseCode = response.getStatusLine().getStatusCode();
        logger.debug("Response code is " + responseCode);
        return response;
    } catch (IOException e) {
        logger.error("Error executing HTTP request.", e);
        return null;
    }
}

From source file:net.shirayu.android.WlanLogin.MyHttpClient.java

public Credentials getCredentials(AuthScope authscope) {
    if ((username != null && username.length() > 0) || (password != null && password.length() > 0)) {
        stop_auth = true;//from   w  w w  . java 2  s .c  om
        return new UsernamePasswordCredentials(username == null ? "" : username,
                password == null ? "" : password);
    } else {
        throw new RuntimeException("Authentication required");
    }
}

From source file:org.openehealth.ipf.labs.maven.confluence.export.AbstractConfluenceExportMojo.java

protected void configureHttpClientProxy() {
    Proxy activeProxy = this.settings.getActiveProxy();
    HttpHost proxy = new HttpHost(activeProxy.getHost(), activeProxy.getPort());

    String proxyUserName = activeProxy.getUsername();
    if (defined(proxyUserName)) {
        String proxyPassword = activeProxy.getPassword();
        client.getCredentialsProvider().setCredentials(new AuthScope(proxy.getHostName(), proxy.getPort()),
                new UsernamePasswordCredentials(proxyUserName, proxyPassword));
    }/*from   www .  j  a  v  a 2  s .  c o m*/
    getLog().info("Using proxy: " + activeProxy.getHost() + ":" + activeProxy.getPort());
    client.getParams().setParameter(ConnRoutePNames.DEFAULT_PROXY, proxy);
}

From source file:com.ibm.watson.developer_cloud.android.text_to_speech.v1.TextToSpeech.java

private void buildAuthenticationHeader(HttpGet httpGet) {

    // use token based authentication if possible, otherwise Basic Authentication will be used
    if (this.tokenProvider != null) {
        Log.d(TAG, "using token based authentication");
        httpGet.setHeader("X-Watson-Authorization-Token", this.tokenProvider.getToken());
    } else {/*w  w  w.  j a va2 s  .co  m*/
        Log.d(TAG, "using basic authentication");
        httpGet.setHeader(BasicScheme
                .authenticate(new UsernamePasswordCredentials(this.username, this.password), "UTF-8", false));
    }
}