Example usage for org.apache.http.client CredentialsProvider setCredentials

List of usage examples for org.apache.http.client CredentialsProvider setCredentials

Introduction

In this page you can find the example usage for org.apache.http.client CredentialsProvider setCredentials.

Prototype

void setCredentials(AuthScope authscope, Credentials credentials);

Source Link

Document

Sets the Credentials credentials for the given authentication scope.

Usage

From source file:com.hp.octane.integrations.services.rest.OctaneRestClientImpl.java

private HttpClientContext createHttpContext(String requestUrl, boolean isLoginRequest) {
    HttpClientContext context = HttpClientContext.create();
    context.setCookieStore(new BasicCookieStore());

    //  add security token if needed
    if (!isLoginRequest) {
        context.getCookieStore().addCookie(LWSSO_TOKEN);
    }//from  ww  w  . jav  a 2  s . c o  m

    //  prepare request config
    RequestConfig.Builder requestConfigBuilder = RequestConfig.custom().setCookieSpec(CookieSpecs.STANDARD);

    //  configure proxy if needed
    URL parsedUrl = CIPluginSDKUtils.parseURL(requestUrl);
    CIProxyConfiguration proxyConfiguration = configurer.pluginServices.getProxyConfiguration(parsedUrl);
    if (proxyConfiguration != null) {
        logger.debug("proxy will be used with the following setup: " + proxyConfiguration);
        HttpHost proxyHost = new HttpHost(proxyConfiguration.getHost(), proxyConfiguration.getPort());

        if (proxyConfiguration.getUsername() != null && !proxyConfiguration.getUsername().isEmpty()) {
            AuthScope authScope = new AuthScope(proxyHost);
            Credentials credentials = new UsernamePasswordCredentials(proxyConfiguration.getUsername(),
                    proxyConfiguration.getPassword());
            CredentialsProvider credentialsProvider = new SystemDefaultCredentialsProvider();
            credentialsProvider.setCredentials(authScope, credentials);
            context.setCredentialsProvider(credentialsProvider);
        }
        requestConfigBuilder.setProxy(proxyHost);
    }

    context.setRequestConfig(requestConfigBuilder.build());
    return context;
}

From source file:aajavafx.EmployeeController.java

public ObservableList<EmployeeProperty> getEmployee() throws IOException, JSONException, Exception {
    Employees myEmployee = new Employees();
    Managers manager = new Managers();
    Gson gson = new Gson();
    ObservableList<EmployeeProperty> employeesProperty = FXCollections.observableArrayList();
    JSONObject jo = new JSONObject();
    CredentialsProvider provider = new BasicCredentialsProvider();
    UsernamePasswordCredentials credentials = new UsernamePasswordCredentials("EMPLOYEE", "password");
    provider.setCredentials(AuthScope.ANY, credentials);
    HttpClient client = HttpClientBuilder.create().setDefaultCredentialsProvider(provider).build();
    HttpGet get = new HttpGet("http://localhost:8080/MainServerREST/api/employees");

    HttpResponse response = client.execute(get);
    System.out.println("RESPONSE IS: " + response);

    JSONArray jsonArray = new JSONArray(
            IOUtils.toString(response.getEntity().getContent(), Charset.forName("UTF-8")));
    System.out.println(jsonArray);
    for (int i = 0; i < jsonArray.length(); i++) {
        jo = (JSONObject) jsonArray.getJSONObject(i);
        myEmployee = gson.fromJson(jo.toString(), Employees.class);
        System.out.println(myEmployee.getEmpPhone());
        employeesProperty.add(new EmployeeProperty(myEmployee.getEmpId(), myEmployee.getEmpLastname(),
                myEmployee.getEmpFirstname(), myEmployee.getEmpUsername(), myEmployee.getEmpPassword(),
                myEmployee.getEmpEmail(), myEmployee.getEmpPhone(), myEmployee.getManagersManId().getManId(),
                myEmployee.getEmpRegistered()));
    }/*from w  ww . j  ava2s. c o  m*/
    return employeesProperty;
}

From source file:org.apache.hadoop.gateway.shell.Hadoop.java

private CloseableHttpClient createClient(ClientContext clientContext) throws GeneralSecurityException {

    // SSL//  w  w  w. j a  v a 2 s. c  o  m
    HostnameVerifier hostnameVerifier = NoopHostnameVerifier.INSTANCE;
    TrustStrategy trustStrategy = null;
    if (clientContext.connection().secure()) {
        hostnameVerifier = SSLConnectionSocketFactory.getDefaultHostnameVerifier();
    } else {
        trustStrategy = TrustSelfSignedStrategy.INSTANCE;
        System.out.println("**************** WARNING ******************\n"
                + "This is an insecure client instance and may\n"
                + "leave the interactions subject to a man in\n" + "the middle attack. Please use the login()\n"
                + "method instead of loginInsecure() for any\n" + "sensitive or production usecases.\n"
                + "*******************************************");
    }

    KeyStore trustStore = getTrustStore();
    SSLContext sslContext = SSLContexts.custom().loadTrustMaterial(trustStore, trustStrategy).build();
    Registry<ConnectionSocketFactory> registry = RegistryBuilder.<ConnectionSocketFactory>create()
            .register("http", PlainConnectionSocketFactory.getSocketFactory())
            .register("https", new SSLConnectionSocketFactory(sslContext, hostnameVerifier)).build();

    // Pool
    PoolingHttpClientConnectionManager connectionManager = new PoolingHttpClientConnectionManager(registry);
    connectionManager.setMaxTotal(clientContext.pool().maxTotal());
    connectionManager.setDefaultMaxPerRoute(clientContext.pool().defaultMaxPerRoute());

    ConnectionConfig connectionConfig = ConnectionConfig.custom()
            .setBufferSize(clientContext.connection().bufferSize()).build();
    connectionManager.setDefaultConnectionConfig(connectionConfig);

    SocketConfig socketConfig = SocketConfig.custom().setSoKeepAlive(clientContext.socket().keepalive())
            .setSoLinger(clientContext.socket().linger())
            .setSoReuseAddress(clientContext.socket().reuseAddress())
            .setSoTimeout(clientContext.socket().timeout()).setTcpNoDelay(clientContext.socket().tcpNoDelay())
            .build();
    connectionManager.setDefaultSocketConfig(socketConfig);

    // Auth
    URI uri = URI.create(clientContext.url());
    host = new HttpHost(uri.getHost(), uri.getPort(), uri.getScheme());

    CredentialsProvider credentialsProvider = null;
    if (clientContext.username() != null && clientContext.password() != null) {
        credentialsProvider = new BasicCredentialsProvider();
        credentialsProvider.setCredentials(new AuthScope(host.getHostName(), host.getPort()),
                new UsernamePasswordCredentials(clientContext.username(), clientContext.password()));

        AuthCache authCache = new BasicAuthCache();
        BasicScheme authScheme = new BasicScheme();
        authCache.put(host, authScheme);
        context = new BasicHttpContext();
        context.setAttribute(org.apache.http.client.protocol.HttpClientContext.AUTH_CACHE, authCache);
    }
    return HttpClients.custom().setConnectionManager(connectionManager)
            .setDefaultCredentialsProvider(credentialsProvider).build();

}

From source file:aajavafx.EmployeeController.java

public void change(int id) throws IOException, JSONException {
    Employees myEmployee = new Employees();

    Gson gson = new Gson();
    Employees employeeNew = null;//from   w  w  w  . j  av a  2 s .co m
    JSONObject jo = new JSONObject();
    CredentialsProvider provider = new BasicCredentialsProvider();
    UsernamePasswordCredentials credentials = new UsernamePasswordCredentials("EMPLOYEE", "password");
    provider.setCredentials(AuthScope.ANY, credentials);
    HttpClient client = HttpClientBuilder.create().setDefaultCredentialsProvider(provider).build();
    HttpGet get = new HttpGet("http://localhost:8080/MainServerREST/api/employees");

    HttpResponse response = client.execute(get);
    System.out.println("RESPONSE IS: " + response);
    boolean register = true;
    JSONArray jsonArray = new JSONArray(
            IOUtils.toString(response.getEntity().getContent(), Charset.forName("UTF-8")));
    System.out.println(jsonArray);
    for (int i = 0; i < jsonArray.length(); i++) {
        jo = (JSONObject) jsonArray.getJSONObject(i);
        myEmployee = gson.fromJson(jo.toString(), Employees.class);
        if (myEmployee.getEmpId().equals(id)) {
            employeeNew = new Employees(1, myEmployee.getEmpFirstname(), myEmployee.getEmpLastname(),
                    myEmployee.getEmpUsername(), myEmployee.getEmpPassword(), myEmployee.getEmpEmail(),
                    myEmployee.getEmpPhone(), manager, register);
        }

    }
    deleteRow(id);
    validate(employeeNew);
}

From source file:org.trancecode.xproc.step.RequestParser.java

private CredentialsProvider parseAuthentication(final XdmNode requestNode) {
    final String username = requestNode.getAttributeValue(XProcXmlModel.Attributes.USERNAME);
    if (!Strings.isNullOrEmpty(username)) {
        final String password = requestNode.getAttributeValue(XProcXmlModel.Attributes.PASSWORD);
        final String authMethod = requestNode.getAttributeValue(XProcXmlModel.Attributes.AUTH_METHOD);
        if (!StringUtils.equalsIgnoreCase(AuthPolicy.BASIC, authMethod)
                && !StringUtils.equalsIgnoreCase(AuthPolicy.DIGEST, authMethod)) {
            throw XProcExceptions.xc0003(requestNode);
        }/*ww  w. j  a  va2  s.c o  m*/

        final CredentialsProvider credsProvider = new BasicCredentialsProvider();
        final HttpHost httpHost = request.getHttpHost();
        credsProvider.setCredentials(new AuthScope(httpHost.getHostName(), httpHost.getPort()),
                new UsernamePasswordCredentials(username, password));

        return credsProvider;
    }
    return null;
}

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

public void setProxySettings(String proxyHost, int proxyPort, String proxyUsername, String proxyPass) {
    HttpHost proxy = new HttpHost(proxyHost, proxyPort);

    proxyConfig = RequestConfig.custom().setProxy(proxy).build();

    CredentialsProvider credsProvider = new BasicCredentialsProvider();
    AuthScope authScope = new AuthScope(proxyHost, proxyPort);
    UsernamePasswordCredentials creds = new UsernamePasswordCredentials(proxyUsername, proxyPass);
    credsProvider.setCredentials(authScope, creds);

    httpClient = HttpClients.custom().setDefaultCredentialsProvider(credsProvider).build();
}

From source file:aajavafx.DevicesController.java

public ObservableList<DevicesCustomerProperty> getDevicesCustomer() throws IOException, JSONException {

    ObservableList<DevicesCustomerProperty> devicesCustomers = FXCollections.observableArrayList();

    Gson gson = new Gson();
    JSONObject jo = new JSONObject();
    // SSL update .......
    CredentialsProvider provider = new BasicCredentialsProvider();
    UsernamePasswordCredentials credentials = new UsernamePasswordCredentials("EMPLOYEE", "password");
    provider.setCredentials(AuthScope.ANY, credentials);
    HttpClient client = HttpClientBuilder.create().setDefaultCredentialsProvider(provider).build();
    HttpGet get = new HttpGet("http://localhost:8080/MainServerREST/api/devicescustomers");
    HttpResponse response = client.execute(get);
    System.out.println("RESPONSE IS: " + response);

    JSONArray jsonArray = new JSONArray(
            IOUtils.toString(response.getEntity().getContent(), Charset.forName("UTF-8")));
    // ...........
    //JSONArray jsonArray = new JSONArray(IOUtils.toString(new URL(DevicesCustomerRootURL), Charset.forName("UTF-8")));
    System.out.println(jsonArray);
    for (int i = 0; i < jsonArray.length(); i++) {
        jo = (JSONObject) jsonArray.getJSONObject(i);
        JSONObject jObj = (JSONObject) jo.get("customersCuId");
        Customers customer = gson.fromJson(jObj.toString(), Customers.class);
        System.out.println("JSON OBJECT #" + i + " " + jo);
        String cuDevId = jo.getString("devId");
        String cuDevName = jo.getString("devName");
        devicesCustomers.add(new DevicesCustomerProperty(customer.getCuId(), customer.getCuFirstname(),
                customer.getCuLastname(), customer.getCuBirthdate(), customer.getCuAddress(),
                customer.getCuPersonnummer(), cuDevId, cuDevName));

    }/*from w w w.  j  ava 2  s  . com*/
    return devicesCustomers;
}

From source file:aajavafx.DevicesController.java

@FXML
private void handleRemoveButton(ActionEvent event) {
    //remove is annotated with @DELETE on server so we use a HttpDelete object
    try {/*from w w w .ja  v  a 2  s.c o m*/
        //......for ssl handshake....
        CredentialsProvider provider = new BasicCredentialsProvider();
        UsernamePasswordCredentials credentials = new UsernamePasswordCredentials("EMPLOYEE", "password");
        provider.setCredentials(AuthScope.ANY, credentials);
        //........
        HttpClient httpClient = HttpClientBuilder.create().build();
        String idToDelete = deviceID.getText();
        //add the id to the end of the URL so this will call the method at MainServerREST/api/visitors/id
        HttpDelete delete = new HttpDelete(DevicesCustomerRootURL + idToDelete);
        HttpResponse response = httpClient.execute(delete);
        System.out.println("response from server " + response.getStatusLine());
    } catch (Exception ex) {
        System.out.println(ex);
    }
    try {
        //refresh table
        tableCustomer.setItems(getDevicesCustomer());
    } catch (IOException ex) {
        Logger.getLogger(VisitorController.class.getName()).log(Level.SEVERE, null, ex);
    } catch (Exception ex) {
        Logger.getLogger(VisitorController.class.getName()).log(Level.SEVERE, null, ex);
    }
}

From source file:securitytools.veracode.VeracodeClient.java

/**
 * Constructs a new VeracodeClient using the specified configuration.
 *     /*from  w  w w.ja v a2  s . c om*/
 * @param credentials Credentials used to access Veracode services.   
 * @param clientConfiguration Client configuration for options such as proxy
 * settings, user-agent header, and network timeouts.
 */
public VeracodeClient(VeracodeCredentials credentials, ClientConfiguration clientConfiguration) {
    CredentialsProvider credentialsProvider = new BasicCredentialsProvider();
    credentialsProvider.setCredentials(new AuthScope(TARGET), credentials);

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

    context = HttpClientContext.create();
    context.setCredentialsProvider(credentialsProvider);
    context.setAuthCache(authCache);

    try {
        client = HttpClientFactory.build(clientConfiguration);
    } catch (NoSuchAlgorithmException nsae) {
        throw new VeracodeClientException(nsae.getMessage(), nsae);
    }
}

From source file:aajavafx.DevicesController.java

public ObservableList<String> getCustomer() throws IOException, JSONException {

    ObservableList<String> customerStrings = FXCollections.observableArrayList();
    //customers.add(new CustomerProperty(1, "Johny", "Walker", "London", "1972-07-01", "7207012222"));
    Customers myCustomer = new Customers();
    //Managers manager = new Managers();
    Gson gson = new Gson();
    ObservableList<CustomerProperty> customersProperty = FXCollections.observableArrayList();
    JSONObject jo = new JSONObject();

    // SSL update .......
    CredentialsProvider provider = new BasicCredentialsProvider();
    UsernamePasswordCredentials credentials = new UsernamePasswordCredentials("EMPLOYEE", "password");
    provider.setCredentials(AuthScope.ANY, credentials);
    HttpClient client = HttpClientBuilder.create().setDefaultCredentialsProvider(provider).build();
    HttpGet get = new HttpGet("http://localhost:8080/MainServerREST/api/customers");
    HttpResponse response = client.execute(get);
    System.out.println("RESPONSE IS: " + response);

    //JSONArray jsonArray = new JSONArray(IOUtils.toString(new URL("http://localhost:8080/MainServerREST/api/customers"), Charset.forName("UTF-8")));
    JSONArray jsonArray = new JSONArray(
            IOUtils.toString(response.getEntity().getContent(), Charset.forName("UTF-8")));
    // ...........
    System.out.println(jsonArray);
    for (int i = 0; i < jsonArray.length(); i++) {
        jo = (JSONObject) jsonArray.getJSONObject(i);
        myCustomer = gson.fromJson(jo.toString(), Customers.class);
        customers.add(myCustomer);/*www  .  ja v  a  2  s.  com*/
        System.out.println(myCustomer.getCuId());
        String s = myCustomer.getCuId() + ". " + myCustomer.getCuFirstname() + " " + myCustomer.getCuLastname()
                + " " + myCustomer.getCuPersonnummer();
        customerStrings.add(s);
        customersProperty.add(new CustomerProperty(myCustomer.getCuId(), myCustomer.getCuFirstname(),
                myCustomer.getCuLastname(), myCustomer.getCuBirthdate(), myCustomer.getCuAddress(),
                myCustomer.getCuPersonnummer()));

    }
    return customerStrings;
}