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:edu.ucsb.nceas.ezid.EZIDService.java

/**
 * Log into the EZID service using account credentials provided by EZID. The cookie
 * returned by EZID is cached in a local CookieStore for the duration of the EZIDService,
 * and so subsequent calls uning this instance of the service will function as
 * fully authenticated. An exception is thrown if authentication fails.
 * @param username to identify the user account from EZID
 * @param password the secret password for this account
 * @throws EZIDException if authentication fails for any reason
 *///w  w w . j  a v a2  s . c om
public void login(String username, String password) throws EZIDException {
    try {
        URI serviceUri = new URI(loginServiceEndpoint);
        HttpHost targetHost = new HttpHost(serviceUri.getHost(), serviceUri.getPort(), serviceUri.getScheme());
        CredentialsProvider credsProvider = new BasicCredentialsProvider();
        credsProvider.setCredentials(new AuthScope(targetHost.getHostName(), targetHost.getPort()),
                new UsernamePasswordCredentials(username, password));
        AuthCache authCache = new BasicAuthCache();
        BasicScheme basicAuth = new BasicScheme();
        authCache.put(targetHost, basicAuth);
        HttpClientContext localcontext = HttpClientContext.create();
        localcontext.setAuthCache(authCache);
        localcontext.setCredentialsProvider(credsProvider);

        ResponseHandler<byte[]> handler = new ResponseHandler<byte[]>() {
            public byte[] handleResponse(HttpResponse response) throws ClientProtocolException, IOException {
                HttpEntity entity = response.getEntity();
                if (entity != null) {
                    return EntityUtils.toByteArray(entity);
                } else {
                    return null;
                }
            }
        };
        byte[] body = null;

        HttpGet httpget = new HttpGet(loginServiceEndpoint);
        body = httpclient.execute(httpget, handler, localcontext);
        String message = new String(body);
        String msg = parseIdentifierResponse(message);
    } catch (URISyntaxException e) {
        throw new EZIDException(e.getMessage());
    } catch (ClientProtocolException e) {
        throw new EZIDException(e.getMessage());
    } catch (IOException e) {
        throw new EZIDException(e.getMessage());
    }
}

From source file:org.xwiki.eclipse.storage.rest.XWikiRestClient.java

protected HttpResponse executePutXml(URI uri, java.lang.Object object) throws Exception {
    DefaultHttpClient httpClient = new DefaultHttpClient();

    UsernamePasswordCredentials creds = new UsernamePasswordCredentials(username, password);

    HttpPut request = new HttpPut(uri);
    request.addHeader(new BasicScheme().authenticate(creds, request));
    request.addHeader("Content-type", "text/xml; charset=UTF-8");
    request.addHeader("Accept", MediaType.APPLICATION_XML);

    ByteArrayOutputStream os = new ByteArrayOutputStream();
    marshaller.marshal(object, os);/*ww  w  . java 2 s .c  o m*/
    HttpEntity entity = new ByteArrayEntity(os.toByteArray());
    request.setEntity(entity);

    HttpResponse response = httpClient.execute(request);

    return response;
}

From source file:org.elasticsearch.xpack.watcher.common.http.HttpClient.java

public HttpResponse execute(HttpRequest request) throws IOException {
    URI uri = createURI(request);

    HttpRequestBase internalRequest;/*from   w  w  w .  j  a  va  2  s. c  o m*/
    if (request.method == HttpMethod.HEAD) {
        internalRequest = new HttpHead(uri);
    } else {
        HttpMethodWithEntity methodWithEntity = new HttpMethodWithEntity(uri, request.method.name());
        if (request.hasBody()) {
            ByteArrayEntity entity = new ByteArrayEntity(request.body.getBytes(StandardCharsets.UTF_8));
            String contentType = request.headers().get(HttpHeaders.CONTENT_TYPE);
            if (Strings.hasLength(contentType)) {
                entity.setContentType(contentType);
            } else {
                entity.setContentType(ContentType.TEXT_PLAIN.toString());
            }
            methodWithEntity.setEntity(entity);
        }
        internalRequest = methodWithEntity;
    }
    internalRequest.setHeader(HttpHeaders.ACCEPT_CHARSET, StandardCharsets.UTF_8.name());

    // headers
    if (request.headers().isEmpty() == false) {
        for (Map.Entry<String, String> entry : request.headers.entrySet()) {
            internalRequest.setHeader(entry.getKey(), entry.getValue());
        }
    }

    // BWC - hack for input requests made to elasticsearch that do not provide the right content-type header!
    if (request.hasBody() && internalRequest.containsHeader("Content-Type") == false) {
        XContentType xContentType = XContentFactory.xContentType(request.body());
        if (xContentType != null) {
            internalRequest.setHeader("Content-Type", xContentType.mediaType());
        }
    }

    RequestConfig.Builder config = RequestConfig.custom();
    setProxy(config, request, settingsProxy);
    HttpClientContext localContext = HttpClientContext.create();
    // auth
    if (request.auth() != null) {
        ApplicableHttpAuth applicableAuth = httpAuthRegistry.createApplicable(request.auth);
        CredentialsProvider credentialsProvider = new BasicCredentialsProvider();
        applicableAuth.apply(credentialsProvider, new AuthScope(request.host, request.port));
        localContext.setCredentialsProvider(credentialsProvider);

        // preemptive auth, no need to wait for a 401 first
        AuthCache authCache = new BasicAuthCache();
        BasicScheme basicAuth = new BasicScheme();
        authCache.put(new HttpHost(request.host, request.port, request.scheme.scheme()), basicAuth);
        localContext.setAuthCache(authCache);
    }

    // timeouts
    if (request.connectionTimeout() != null) {
        config.setConnectTimeout(Math.toIntExact(request.connectionTimeout.millis()));
    } else {
        config.setConnectTimeout(Math.toIntExact(defaultConnectionTimeout.millis()));
    }

    if (request.readTimeout() != null) {
        config.setSocketTimeout(Math.toIntExact(request.readTimeout.millis()));
        config.setConnectionRequestTimeout(Math.toIntExact(request.readTimeout.millis()));
    } else {
        config.setSocketTimeout(Math.toIntExact(defaultReadTimeout.millis()));
        config.setConnectionRequestTimeout(Math.toIntExact(defaultReadTimeout.millis()));
    }

    internalRequest.setConfig(config.build());

    try (CloseableHttpResponse response = SocketAccess
            .doPrivileged(() -> client.execute(internalRequest, localContext))) {
        // headers
        Header[] headers = response.getAllHeaders();
        Map<String, String[]> responseHeaders = new HashMap<>(headers.length);
        for (Header header : headers) {
            if (responseHeaders.containsKey(header.getName())) {
                String[] old = responseHeaders.get(header.getName());
                String[] values = new String[old.length + 1];

                System.arraycopy(old, 0, values, 0, old.length);
                values[values.length - 1] = header.getValue();

                responseHeaders.put(header.getName(), values);
            } else {
                responseHeaders.put(header.getName(), new String[] { header.getValue() });
            }
        }

        final byte[] body;
        // not every response has a content, i.e. 204
        if (response.getEntity() == null) {
            body = new byte[0];
        } else {
            try (ByteArrayOutputStream outputStream = new ByteArrayOutputStream()) {
                try (InputStream is = new SizeLimitInputStream(maxResponseSize,
                        response.getEntity().getContent())) {
                    Streams.copy(is, outputStream);
                }
                body = outputStream.toByteArray();
            }
        }
        return new HttpResponse(response.getStatusLine().getStatusCode(), body, responseHeaders);
    }
}

From source file:com.ibm.ws.lars.rest.RepositoryContext.java

@Override
protected void before() throws InvalidJsonAssetException, IOException, KeyManagementException,
        NoSuchAlgorithmException, KeyStoreException {

    targetHost = new HttpHost(hostname, portNumber, protocol);

    /* Create the HTTPClient that we use to make all HTTP calls */
    HttpClientBuilder b = HttpClientBuilder.create();

    // Trust all certificates
    SSLContext sslContext = new SSLContextBuilder().loadTrustMaterial(null, new TrustStrategy() {
        @Override/*from   ww w  .  java2  s. c o m*/
        public boolean isTrusted(X509Certificate[] arg0, String arg1) throws CertificateException {
            return true;
        }
    }).build();
    b.setSslcontext(sslContext);

    // By default, it will verify the hostname in the certificate, which should be localhost
    // and therefore should match. If we start running these tests against a LARS server on
    // a different host then we may need disable hostname verification.

    context = HttpClientContext.create();

    httpClient = b.build();

    /*
     * Create the HTTPClientContext with the appropriate credentials. We'll use this whenever we
     * make an HTTP call.
     */
    if (user != null && password != null) {
        credentials = new UsernamePasswordCredentials(user, password);

        CredentialsProvider credsProvider = new BasicCredentialsProvider();
        credsProvider.setCredentials(new AuthScope(targetHost.getHostName(), targetHost.getPort()),
                credentials);

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

        context.setCredentialsProvider(credsProvider);
        context.setAuthCache(authCache);
    }

    /* Clean the repository but only if the client asked us to. */
    if (cleanRepository) {
        cleanRepo();
    }
}

From source file:eu.cassandra.training.utils.APIUtilities.java

/**
 * This function is used to send the user's credentials to the Cassandra
 * Server.//from   w  ww  . j  av  a2  s .c o  m
 * 
 * @param username
 *          The username of the user in the server.
 * @param password
 *          The password of the user in the server.
 * @return true if connected, else false.
 * @throws Exception
 */
public static boolean sendUserCredentials(String username, char[] password) throws Exception {

    String pass = String.valueOf(password);

    try {
        UsernamePasswordCredentials usernamePasswordCredentials = new UsernamePasswordCredentials(username,
                pass);

        char SEP = File.separatorChar;
        File dir = new File(System.getProperty("java.home") + SEP + "lib" + SEP + "security");
        File file = new File(dir, "jssecacerts");
        if (file.isFile() == false) {
            InstallCert.createCertificate("160.40.50.233", 8443);
            JFrame success = new JFrame();

            JOptionPane.showMessageDialog(success,
                    "Certificate was created for user " + username + ". Now the connection will start",
                    "Response Model Exported", JOptionPane.INFORMATION_MESSAGE);
        }

        try {
            sslContext = SSLContext.getInstance("TLS");
            sslContext.init(null, null, null);
            sf = new SSLSocketFactory(sslContext, SSLSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER);
        } catch (Exception e1) {
        }

        Scheme scheme = new Scheme("https", 8443, sf);
        httpclient.getConnectionManager().getSchemeRegistry().register(scheme);

        HttpGet httpget = new HttpGet(url + "/usr");
        httpget.addHeader(new BasicScheme().authenticate(usernamePasswordCredentials, httpget, localcontext));

        System.out.println("executing request: " + httpget.getRequestLine());

        HttpResponse response = httpclient.execute(httpget, localcontext);
        HttpEntity entity = response.getEntity();
        String responseString = EntityUtils.toString(entity, "UTF-8");
        System.out.println(responseString);

        DBObject dbo = (DBObject) JSON.parse(responseString);

        if (dbo.get("success").toString().equalsIgnoreCase("true")) {

            BasicDBList dataObj = (BasicDBList) dbo.get("data");

            DBObject dbo2 = (DBObject) dataObj.get(0);

            userID = dbo2.get("usr_id").toString();

            System.out.println("userId: " + userID);

            return true;
        } else {
            System.out.println(false);
            return false;
        }

    } finally {
    }

}