Example usage for org.apache.http.impl.auth BasicScheme BasicScheme

List of usage examples for org.apache.http.impl.auth BasicScheme BasicScheme

Introduction

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

Prototype

public BasicScheme() 

Source Link

Usage

From source file:org.hawkular.client.RestFactory.java

public T createAPI(URI uri, String userName, String password) {
    HttpClient httpclient = null;//from w w w.j a v  a  2s .c  om
    if (uri.toString().startsWith("https")) {
        httpclient = getHttpClient();
    } else {
        httpclient = HttpClientBuilder.create().build();
    }
    ResteasyClient client = null;
    if (userName != null) {
        HttpHost targetHost = new HttpHost(uri.getHost(), uri.getPort());
        CredentialsProvider credsProvider = new BasicCredentialsProvider();
        credsProvider.setCredentials(new AuthScope(targetHost.getHostName(), targetHost.getPort()),
                new UsernamePasswordCredentials(userName, password));
        // 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);
        ApacheHttpClient4Engine engine = new ApacheHttpClient4Engine(httpclient, context);

        client = new ResteasyClientBuilder().httpEngine(engine).build();
    } else {
        ApacheHttpClient4Engine engine = new ApacheHttpClient4Engine(getHttpClient());
        client = new ResteasyClientBuilder().httpEngine(engine).build();
    }

    client.register(JacksonJaxbJsonProvider.class);
    client.register(JacksonObjectMapperProvider.class);
    client.register(RestRequestFilter.class);
    client.register(RestResponseFilter.class);
    client.register(HCJacksonJson2Provider.class);
    ProxyBuilder<T> proxyBuilder = client.target(uri).proxyBuilder(apiClassType);
    if (classLoader != null) {
        proxyBuilder = proxyBuilder.classloader(classLoader);
    }
    return proxyBuilder.build();
}

From source file:com.seleniumtests.browserfactory.SauceLabsDriverFactory.java

/**
 * Upload application to saucelabs server
 * @param targetAppPath//from   w  w w  .j  a  v  a2  s  . c o  m
 * @param serverURL
 * @return
 * @throws IOException
 * @throws AuthenticationException 
 */
protected static boolean uploadFile(String targetAppPath) throws IOException, AuthenticationException {

    // extract user name and password from getWebDriverGrid
    Matcher matcher = REG_USER_PASSWORD
            .matcher(SeleniumTestsContextManager.getThreadContext().getWebDriverGrid().get(0));
    String user;
    String password;
    if (matcher.matches()) {
        user = matcher.group(1);
        password = matcher.group(2);
    } else {
        throw new ConfigurationException(
                "getWebDriverGrid variable does not have the right format for connecting to sauceLabs");
    }

    FileEntity entity = new FileEntity(new File(targetAppPath));
    UsernamePasswordCredentials creds = new UsernamePasswordCredentials(user, password);

    HttpPost request = new HttpPost(String.format(SAUCE_UPLOAD_URL, user, new File(targetAppPath).getName()));
    request.setEntity(entity);
    request.addHeader(new BasicScheme().authenticate(creds, request, null));
    request.addHeader("Content-Type", "application/octet-stream");

    try (CloseableHttpClient client = HttpClients.createDefault();) {
        CloseableHttpResponse response = client.execute(request);

        if (response.getStatusLine().getStatusCode() != 200) {
            client.close();
            throw new ConfigurationException(
                    "Application file upload failed: " + response.getStatusLine().getReasonPhrase());
        }
    }

    return true;
}

From source file:com.emc.storageos.driver.dellsc.scapi.rest.RestClient.java

/**
 * Instantiates a new Rest client.//from  ww  w.  j  ava2 s . c  o  m
 *
 * @param host Host name or IP address of the Dell Storage Manager server.
 * @param port Port the DSM data collector is listening on.
 * @param user The DSM user name to use.
 * @param password The DSM password.
 */
public RestClient(String host, int port, String user, String password) {
    this.baseUrl = String.format("https://%s:%d/api/rest", host, port);

    try {
        // Set up auth handling
        CredentialsProvider credsProvider = new BasicCredentialsProvider();
        credsProvider.setCredentials(new AuthScope(host, port),
                new UsernamePasswordCredentials(user, password));
        AuthCache authCache = new BasicAuthCache();
        BasicScheme basicAuth = new BasicScheme();
        HttpHost target = new HttpHost(host, port, "https");
        authCache.put(target, basicAuth);

        // Set up our context
        httpContext = HttpClientContext.create();
        httpContext.setCookieStore(new BasicCookieStore());
        httpContext.setAuthCache(authCache);

        // Create our HTTPS client
        SSLContext sslContext = SSLContexts.custom().loadTrustMaterial(null, new TrustStrategy() {
            @Override
            public boolean isTrusted(X509Certificate[] arg0, String arg1) throws CertificateException {
                return true;
            }
        }).build();

        SSLConnectionSocketFactory sslSocketFactory = new SSLConnectionSocketFactory(sslContext,
                SSLConnectionSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER);

        this.httpClient = HttpClients.custom().setHostnameVerifier(new AllowAllHostnameVerifier())
                .setDefaultCredentialsProvider(credsProvider).setSSLSocketFactory(sslSocketFactory).build();
    } catch (NoSuchAlgorithmException | KeyStoreException | KeyManagementException e) {
        // Hopefully default SSL handling is set up
        LOG.warn("Failed to configure HTTP handling, falling back to default handler.");
        LOG.debug("Config error: {}", e);
        this.httpClient = HttpClients.createDefault();
    }
}

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);//  ww  w  .j  a v  a  2 s.  c o m

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

From source file:org.superbiz.AuthBeanTest.java

private String get(final String user, final String password) {
    final BasicCredentialsProvider basicCredentialsProvider = new BasicCredentialsProvider();
    basicCredentialsProvider.setCredentials(AuthScope.ANY, new UsernamePasswordCredentials(user, password));
    final CloseableHttpClient client = HttpClients.custom()
            .setDefaultCredentialsProvider(basicCredentialsProvider).build();

    final HttpHost httpHost = new HttpHost(webapp.getHost(), webapp.getPort(), webapp.getProtocol());
    final AuthCache authCache = new BasicAuthCache();
    final BasicScheme basicAuth = new BasicScheme();
    authCache.put(httpHost, basicAuth);/*  w  w w .  j  a v a2  s.  c o  m*/
    final HttpClientContext context = HttpClientContext.create();
    context.setAuthCache(authCache);

    final HttpGet get = new HttpGet(webapp.toExternalForm() + "servlet");
    CloseableHttpResponse response = null;
    try {
        response = client.execute(httpHost, get, context);
        return response.getStatusLine().getStatusCode() + " " + EntityUtils.toString(response.getEntity());
    } catch (final IOException e) {
        throw new IllegalStateException(e);
    } finally {
        try {
            IO.close(response);
        } catch (final IOException e) {
            // no-op
        }
    }
}

From source file:de.perdian.apps.dashboard.support.clients.JsonClient.java

/**
 * Executes the given job and return the response
 *
 * @param requestUri/*  ww w.j  a v  a  2  s .com*/
 *     the URI to which the request should be sent
 * @return
 *     the JSON result
 */
public JsonNode sendRequest(CharSequence requestUri) {
    try {

        HttpGet httpGet = new HttpGet(requestUri.toString());
        if (this.getUsername() != null && this.getPassword() != null) {
            httpGet.addHeader(new BasicScheme().authenticate(
                    new UsernamePasswordCredentials(this.getUsername(), this.getPassword()), httpGet,
                    new BasicHttpContext()));
        }
        for (Map.Entry<Object, Object> defaultHeaderEntry : this.getDefaultHeaders().entrySet()) {
            httpGet.addHeader((String) defaultHeaderEntry.getKey(), (String) defaultHeaderEntry.getValue());
        }

        String httpResponseString = this.getHttpClient().execute(httpGet, new BasicResponseHandler());
        return JsonUtil.fromJsonString(httpResponseString);

    } catch (Exception e) {
        StringBuilder errorMessage = new StringBuilder();
        errorMessage.append("Cannot send HTTP request [").append(requestUri);
        errorMessage.append("] using client [").append(this).append("]");
        log.debug(errorMessage.toString(), e);
        throw new DashboardException(errorMessage.toString(), e);
    }
}

From source file:com.netdimensions.client.Client.java

private static BasicAuthCache authCache(final URI url) {
    final BasicAuthCache result = new BasicAuthCache();
    result.put(host(url), new BasicScheme());
    return result;
}

From source file:neembuu.vfs.test.FileNameAndSizeFinderService.java

private DefaultHttpClient newClient() {
    DefaultHttpClient client = new DefaultHttpClient();
    GlobalTestSettings.ProxySettings proxySettings = GlobalTestSettings.getGlobalProxySettings();
    HttpContext context = new BasicHttpContext();
    SchemeRegistry schemeRegistry = new SchemeRegistry();

    schemeRegistry.register(new Scheme("http", new PlainSocketFactory(), 80));

    try {/*w ww .ja v  a2  s .c o m*/
        KeyStore keyStore = KeyStore.getInstance(KeyStore.getDefaultType());
        schemeRegistry.register(new Scheme("https", new SSLSocketFactory(keyStore), 8080));
    } catch (Exception a) {
        a.printStackTrace(System.err);
    }

    context.setAttribute(ClientContext.SCHEME_REGISTRY, schemeRegistry);
    context.setAttribute(ClientContext.AUTHSCHEME_REGISTRY,
            new BasicScheme()/*file.httpClient.getAuthSchemes()*/);

    context.setAttribute(ClientContext.COOKIESPEC_REGISTRY,
            client.getCookieSpecs()/*file.httpClient.getCookieSpecs()*/
    );

    BasicCookieStore basicCookieStore = new BasicCookieStore();

    context.setAttribute(ClientContext.COOKIE_STORE, basicCookieStore/*file.httpClient.getCookieStore()*/);
    context.setAttribute(ClientContext.CREDS_PROVIDER,
            new BasicCredentialsProvider()/*file.httpClient.getCredentialsProvider()*/);

    HttpConnection hc = new DefaultHttpClientConnection();
    context.setAttribute(ExecutionContext.HTTP_CONNECTION, hc);

    //System.out.println(file.httpClient.getParams().getParameter("http.useragent"));
    HttpParams httpParams = new BasicHttpParams();

    if (proxySettings != null) {
        AuthState as = new AuthState();
        as.setCredentials(new UsernamePasswordCredentials(proxySettings.userName, proxySettings.password));
        as.setAuthScope(AuthScope.ANY);
        as.setAuthScheme(new BasicScheme());
        httpParams.setParameter(ClientContext.PROXY_AUTH_STATE, as);
        httpParams.setParameter("http.proxy_host", new HttpHost(proxySettings.host, proxySettings.port));
    }

    client = new DefaultHttpClient(
            new SingleClientConnManager(httpParams/*file.httpClient.getParams()*/, schemeRegistry),
            httpParams/*file.httpClient.getParams()*/);

    if (proxySettings != null) {
        client.getCredentialsProvider().setCredentials(AuthScope.ANY,
                new UsernamePasswordCredentials(proxySettings.userName, proxySettings.password));
    }

    return client;
}

From source file:hu.dolphio.tprttapi.service.TrackingFlushServiceTpImpl.java

public TrackingFlushServiceTpImpl(String dateFrom, String dateTo) {
    this.dateFrom = dateFrom;
    this.dateTo = dateTo;

    targetHost = new HttpHost(propertyReader.getTpHost(), 80, "http");
    credsProvider = new BasicCredentialsProvider();
    Credentials credentials = new UsernamePasswordCredentials(propertyReader.getTpUserName(),
            propertyReader.getTpPassword());
    credsProvider.setCredentials(new AuthScope(targetHost.getHostName(), targetHost.getPort()), credentials);
    config = RequestConfig.custom().setSocketTimeout(propertyReader.getConnectionTimeout())
            .setConnectTimeout(propertyReader.getConnectionTimeout()).build();

    AuthCache authCache = new BasicAuthCache();

    BasicScheme basicAuth = new BasicScheme();
    authCache.put(targetHost, basicAuth);

    clientContext.setAuthCache(authCache);
}

From source file:org.openlmis.UiUtils.HttpClient.java

public ResponseEntity SendJSONWithoutHeaders(String json, String url, String commMethod, String username,
        String password) {//from w  ww .ja va  2s  .co  m
    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;
}