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.cerberus.util.HTTPSession.java

/**
 * Start a HTTP Session with authorisation
 *
 * @param username//from   ww  w.j  av  a 2  s  .  c  o  m
 * @param password
 */
public void startSession(String username, String password) {
    // Create your httpclient
    client = new DefaultHttpClient();
    client.getParams().setBooleanParameter(ClientPNames.ALLOW_CIRCULAR_REDIRECTS, true);

    // Then provide the right credentials
    client.getCredentialsProvider().setCredentials(new AuthScope(AuthScope.ANY_HOST, AuthScope.ANY_PORT),
            new UsernamePasswordCredentials(username, password));

    // Generate BASIC scheme object and stick it to the execution context
    basicAuth = new BasicScheme();
    context = new BasicHttpContext();
    context.setAttribute("preemptive-auth", basicAuth);

    // Add as the first (because of the zero) request interceptor
    // It will first intercept the request and preemptively initialize the authentication scheme if there is not
    client.addRequestInterceptor(new PreemptiveAuth(), 0);
}

From source file:magicware.scm.redmine.tools.RedmineClient.java

public void fillBasicAuth(String userName, String base64Pwd) {

    // Basic?/*from  w  w w .j a  v  a 2  s  .c  om*/
    httpclient.getCredentialsProvider().setCredentials(
            new AuthScope(targetHost.getHostName(), targetHost.getPort()),
            new UsernamePasswordCredentials(userName,
                    StringUtils.isEmpty(base64Pwd) ? UUID.randomUUID().toString()
                            : new String(Base64.decodeBase64(base64Pwd))));
    AuthCache authCache = new BasicAuthCache();
    BasicScheme basicAuth = new BasicScheme();
    authCache.put(targetHost, basicAuth);
    BasicHttpContext localcontext = new BasicHttpContext();
    localcontext.setAttribute(ClientContext.AUTH_CACHE, authCache);
}

From source file:org.fcrepo.camel.FcrepoHttpClientBuilder.java

/**
 *  Build an HttpClient//  w  w w. j  a  v  a 2  s  .c om
 *
 *  @return an HttpClient
 */
public CloseableHttpClient build() {

    if (isBlank(username) || isBlank(password)) {
        return HttpClients.createDefault();
    } else {
        LOGGER.debug("Accessing fcrepo with user credentials");

        final CredentialsProvider credsProvider = new BasicCredentialsProvider();
        AuthScope scope = null;

        if (isBlank(host)) {
            scope = new AuthScope(AuthScope.ANY);
        } else {
            scope = new AuthScope(new HttpHost(host));
        }
        credsProvider.setCredentials(scope, new UsernamePasswordCredentials(username, password));
        return HttpClients.custom().setDefaultCredentialsProvider(credsProvider).build();
    }
}

From source file:org.fcrepo.client.FcrepoHttpClientBuilder.java

/**
 *  Build an HttpClient//from w w w.  j av  a2s .  c o  m
 *
 *  @return an HttpClient
 */
public CloseableHttpClient build() {

    if (isBlank(username) || isBlank(password)) {
        return HttpClients.createSystem();
    } else {
        LOGGER.debug("Accessing fcrepo with user credentials");

        final CredentialsProvider credsProvider = new BasicCredentialsProvider();
        AuthScope scope = null;

        if (isBlank(host)) {
            scope = new AuthScope(AuthScope.ANY);
        } else {
            scope = new AuthScope(new HttpHost(host));
        }
        credsProvider.setCredentials(scope, new UsernamePasswordCredentials(username, password));
        return HttpClients.custom().setDefaultCredentialsProvider(credsProvider).useSystemProperties().build();
    }
}

From source file:com.google.code.maven.plugin.http.client.Credentials.java

/**
 * converts to {@link UsernamePasswordCredentials}
 * /*  w  ww  .  j  a  v  a2s. c om*/
 * @return
 */
public UsernamePasswordCredentials toUsernamePasswordCredentials() {
    return new UsernamePasswordCredentials(login, password);
}

From source file:com.quartzdesk.executor.core.job.UrlInvokerJob.java

@Override
protected void executeJob(final JobExecutionContext context) throws JobExecutionException {
    log.debug("Inside job: {}", context.getJobDetail().getKey());
    JobDataMap jobDataMap = context.getMergedJobDataMap();

    // url (required)
    final String url = jobDataMap.getString(JDM_KEY_URL);
    if (url == null) {
        throw new JobExecutionException("Missing required '" + JDM_KEY_URL + "' job data map parameter.");
    }//from w  ww .  j av a2 s .c  o  m

    // username (optional)
    String username = jobDataMap.getString(JDM_KEY_USERNAME);
    // password (optional)
    String password = jobDataMap.getString(JDM_KEY_PASSWORD);

    CloseableHttpClient httpClient;
    if (username != null && password != null) {
        // use HTTP basic authentication
        CredentialsProvider credsProvider = new BasicCredentialsProvider();
        credsProvider.setCredentials(AuthScope.ANY, new UsernamePasswordCredentials(username, password));

        httpClient = HttpClients.custom().setDefaultCredentialsProvider(credsProvider).build();
    } else {
        // use no HTTP authentication
        httpClient = HttpClients.custom().build();
    }

    try {
        HttpPost httpPost = new HttpPost(url);

        ResponseHandler<String> responseHandler = new ResponseHandler<String>() {
            @Override
            public String handleResponse(HttpResponse httpResponse) throws IOException {
                int status = httpResponse.getStatusLine().getStatusCode();

                //context.setResult( Integer.toString( status ) );

                if (status >= 200 && status < 300) {
                    HttpEntity entity = httpResponse.getEntity();
                    return entity == null ? null : EntityUtils.toString(entity);
                } else {
                    throw new ClientProtocolException(
                            "URL: " + url + " returned unexpected response status code: " + status);
                }
            }
        };

        log.debug("HTTP request line: {}", httpPost.getRequestLine());

        log.info("Invoking target URL: {}", url);
        String responseText = httpClient.execute(httpPost, responseHandler);

        log.debug("Response text: {}", responseText);

        if (!responseText.trim().isEmpty()) {
            /*
             * We use the HTTP response text as the Quartz job execution result. This code can then be easily
             * viewed in the Execution History in the QuartzDesk GUI and it can be, for example, used to trigger
             * execution notifications.
             */
            context.setResult(responseText);
        }

    } catch (IOException e) {
        throw new JobExecutionException("Error invoking URL: " + url, e);
    } finally {
        try {
            httpClient.close();
        } catch (IOException e) {
            log.error("Error closing HTTP client.", e);
        }
    }
}

From source file:com.microsoft.azure.hdinsight.common.task.LivyTask.java

public LivyTask(@NotNull IClusterDetail clusterDetail, @NotNull String path,
        @NotNull FutureCallback<String> callback) {
    super(callback);
    this.clusterDetail = clusterDetail;
    this.path = path;
    this.callback = callback;
    try {//from   w  w w  . j a v  a  2s  . c  o  m
        credentialsProvider.setCredentials(AuthScope.ANY, new UsernamePasswordCredentials(
                clusterDetail.getHttpUserName(), clusterDetail.getHttpPassword()));
    } catch (HDIException e) {
        e.printStackTrace();
    }
}

From source file:com.isotrol.impe3.connectors.httpclient.AbstractHttpClientConnector.java

/**
 * Create new default http client.//from www . ja  v a  2s  . c o m
 */
public void init() {
    httpclient = new DefaultHttpClient();

    if (isAuthenticated()) {
        httpclient.getCredentialsProvider().setCredentials(new AuthScope(scopeserver, scopeport),
                new UsernamePasswordCredentials(user, pass));
    }
}

From source file:org.nuxeo.connect.connector.http.ProxyHelper.java

public static void configureProxyIfNeeded(RequestConfig.Builder requestConfigBuilder,
        CredentialsProvider credentialsProvider, String url) {
    if (ConnectUrlConfig.useProxy()) {
        // configure proxy host
        HttpHost proxyHost = null;/*w  w  w.  ja  v a 2s.c  o m*/
        if (ConnectUrlConfig.useProxyPac()) {
            String[] proxy = pacResolver.findProxy(url);
            if (proxy != null) {
                proxyHost = new HttpHost(proxy[0], Integer.parseInt(proxy[1]));
            }
        } else {
            proxyHost = new HttpHost(ConnectUrlConfig.getProxyHost(), ConnectUrlConfig.getProxyPort());
        }

        if (proxyHost != null) {
            requestConfigBuilder.setProxy(proxyHost);
            // configure proxy auth in BA
            if (ConnectUrlConfig.isProxyAuthenticated()) {
                AuthScope authScope = new AuthScope(proxyHost.getHostName(), proxyHost.getPort(),
                        AuthScope.ANY_REALM);
                if (ConnectUrlConfig.isProxyNTLM()) {
                    NTCredentials ntlmCredential = new NTCredentials(ConnectUrlConfig.getProxyLogin(),
                            ConnectUrlConfig.getProxyPassword(), ConnectUrlConfig.getProxyNTLMHost(),
                            ConnectUrlConfig.getProxyNTLMDomain());
                    credentialsProvider.setCredentials(authScope, ntlmCredential);
                } else {
                    Credentials ba = new UsernamePasswordCredentials(ConnectUrlConfig.getProxyLogin(),
                            ConnectUrlConfig.getProxyPassword());
                    credentialsProvider.setCredentials(authScope, ba);
                }
            }
        }
    }
}

From source file:com.arcbees.vcs.stash.StashApi.java

public StashApi(HttpClientWrapper httpClient, StashApiPaths apiPaths, String userName, String password,
        String repositoryOwner, String repositoryName) {
    this.httpClient = httpClient;
    this.apiPaths = apiPaths;
    this.repositoryOwner = repositoryOwner;
    this.repositoryName = repositoryName;
    this.credentials = new UsernamePasswordCredentials(userName, password);
    this.gson = new GsonBuilder().registerTypeAdapter(Date.class, new GsonDateTypeAdapter()).create();
}