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:org.openscore.content.httpclient.build.auth.CredentialsProviderBuilder.java

public CredentialsProvider buildCredentialsProvider() {
    CredentialsProvider credentialsProvider = new BasicCredentialsProvider();

    if (!StringUtils.isEmpty(username)) {
        Credentials credentials;/* www. ja v  a  2 s . co  m*/
        if (authTypes.contains(AuthTypes.NTLM)) {
            String[] domainAndUsername = getDomainUsername(username);
            credentials = new NTCredentials(domainAndUsername[1], password, host, domainAndUsername[0]);
        } else {
            credentials = new UsernamePasswordCredentials(username, password);
        }
        credentialsProvider.setCredentials(new AuthScope(host, Integer.parseInt(port)), credentials);
    } else if (authTypes.contains(AuthTypes.KERBEROS)) {
        credentialsProvider.setCredentials(new AuthScope(host, Integer.parseInt(port)), new Credentials() {
            @Override
            public Principal getUserPrincipal() {
                return null;
            }

            @Override
            public String getPassword() {
                return null;
            }
        });
    }

    if (!StringUtils.isEmpty(proxyUsername)) {
        int intProxyPort = 8080;
        if (!StringUtils.isEmpty(proxyPort)) {
            intProxyPort = Integer.parseInt(proxyPort);
        }
        credentialsProvider.setCredentials(new AuthScope(proxyHost, intProxyPort),
                new UsernamePasswordCredentials(proxyUsername, proxyPassword));
    }

    return credentialsProvider;
}

From source file:io.cloudslang.content.httpclient.build.auth.CredentialsProviderBuilder.java

public CredentialsProvider buildCredentialsProvider() {
    CredentialsProvider credentialsProvider = new BasicCredentialsProvider();

    if (!StringUtils.isEmpty(username)) {
        Credentials credentials;/*from w w  w . j av a 2  s  .  c om*/
        if (authTypes.contains(AuthTypes.NTLM)) {
            String[] domainAndUsername = getDomainUsername(username);
            credentials = new NTCredentials(domainAndUsername[1], password, host, domainAndUsername[0]);
        } else {
            credentials = new UsernamePasswordCredentials(username, password);
        }
        credentialsProvider.setCredentials(new AuthScope(host, Integer.parseInt(port)), credentials);
    } else if (authTypes.contains(AuthTypes.KERBEROS)) {
        credentialsProvider.setCredentials(new AuthScope(host, Integer.parseInt(port)), new Credentials() {
            @Override
            public Principal getUserPrincipal() {
                return null;
            }

            @Override
            public String getPassword() {
                return null;
            }
        });
    }

    if (!StringUtils.isEmpty(proxyUsername)) {
        int intProxyPort = 8080;
        if (!StringUtils.isEmpty(proxyPort)) {
            intProxyPort = Utils.validatePortNumber(proxyPort);
        }
        credentialsProvider.setCredentials(new AuthScope(proxyHost, intProxyPort),
                new UsernamePasswordCredentials(proxyUsername, proxyPassword));
    }

    return credentialsProvider;
}

From source file:com.github.mike10004.jenkinsbbhook.WebhookHandler.java

protected CredentialsProvider asCredentialsProvider(URL jenkinsCrumbUrl, AppParams appParams, String username,
        String apiToken) {/*from w  w w  .j  a v a 2s  .  c  om*/
    CredentialsProvider credentialsProvider = new BasicCredentialsProvider();
    String jenkinsHost = jenkinsCrumbUrl.getHost();
    int jenkinsPort = jenkinsCrumbUrl.getPort();
    if (jenkinsPort == -1) {
        jenkinsPort = jenkinsCrumbUrl.getDefaultPort();
    }
    AuthScope scope = new AuthScope(jenkinsHost, jenkinsPort);
    credentialsProvider.setCredentials(scope, new UsernamePasswordCredentials(username, apiToken));
    return credentialsProvider;
}

From source file:com.rockagen.commons.http.HttpConn.java

/**
 * Handler main/* www  . ja  v a 2s . c  om*/
 *
 * @param targetHost target {@link HttpHost}
 * @param proxyHost proxy {@link HttpHost}
 * @param httpRequestMethod HttpGet or HttpPost...
 * @param encoding encoding
 * @param upc {@link UsernamePasswordCredentials}
 * @param keystore keystore stream
 * @param password keystore password
 * @return result String
 * @throws IOException  if an I/O error occurs
 */
protected static String execute(HttpHost targetHost, HttpHost proxyHost, HttpRequest httpRequestMethod,
        String encoding, UsernamePasswordCredentials upc, InputStream keystore, char[] password)
        throws IOException {

    HttpClientBuilder hcb = HttpClients.custom();
    hcb.setDefaultRequestConfig(getRequestConfig());
    if (proxyHost != null) {
        hcb.setProxy(proxyHost);
    }
    if (keystore != null) {

        try {
            KeyStore trustStore = KeyStore.getInstance(KeyStore.getDefaultType());
            trustStore.load(keystore, password);
            SSLContext sslcontext = SSLContexts.custom()
                    .loadTrustMaterial(trustStore, new TrustSelfSignedStrategy()).build();
            SSLConnectionSocketFactory ssf = new SSLConnectionSocketFactory(sslcontext);
            hcb.setSSLSocketFactory(ssf);
        } catch (KeyStoreException e) {
            log.error("{}", e.getMessage(), e);
        } catch (CertificateException e) {
            log.error("{}", e.getMessage(), e);
        } catch (NoSuchAlgorithmException e) {
            log.error("{}", e.getMessage(), e);
        } catch (KeyManagementException e) {
            log.error("{}", e.getMessage(), e);
        } finally {
            keystore.close();
        }

    }

    if (upc != null) {
        CredentialsProvider cp = new BasicCredentialsProvider();

        AuthScope as = new AuthScope(targetHost);

        cp.setCredentials(as, upc);
        hcb.setDefaultCredentialsProvider(cp);
    }

    CloseableHttpClient chc = hcb.build();
    try {
        CloseableHttpResponse response = chc.execute(targetHost, httpRequestMethod);
        return getResponse(response, encoding);
    } finally {
        chc.close();
    }

}

From source file:aajavafx.CustomerMedicineController.java

@FXML
private void handleSaveButton(ActionEvent event) {
    //labelError.setText(null);
    try {/*from ww w.j  a v  a 2s.  co  m*/

        String dosage = dose.getText();
        dose.clear();
        String stDate = startDate.getText();
        startDate.clear();
        String sched = schedule.getText();
        schedule.clear();
        Customers customer = (Customers) customerBox.getSelectionModel().getSelectedItem();
        Medicines medicine = (Medicines) medicinesBox.getSelectionModel().getSelectedItem();
        CustomersTakesMedicinesPK ctmPK = new CustomersTakesMedicinesPK(customer.getCuId(),
                medicine.getmedId());
        CustomersTakesMedicines ctm = new CustomersTakesMedicines(ctmPK, dosage, stDate,
                Double.parseDouble(sched));
        ctm.setCustomers(customer);
        ctm.setMedicines(medicine);
        //System.out.println(customerBox.getValue());
        //String string = (String)customerBox.getValue();
        //System.out.println("STRING VALUE: "+string);
        //int customerId = Integer.parseInt(""+string.charAt(0));
        //System.out.println("CUSTOMER ID VALUE:"+customerId);
        //Customers customer = getCustomerByID(customerId);

        Gson gson = new Gson();
        //......for ssl handshake....
        CredentialsProvider provider = new BasicCredentialsProvider();
        UsernamePasswordCredentials credentials = new UsernamePasswordCredentials("EMPLOYEE", "password");
        provider.setCredentials(AuthScope.ANY, credentials);
        //........
        HttpClient httpClient = HttpClientBuilder.create().build();
        HttpEntityEnclosingRequestBase HttpEntity = null; //this is the superclass for post, put, get, etc
        if (startDate.isEditable()) { //then we are posting a new record
            HttpEntity = new HttpPost(MedicineCustomerRootURL); //so make a http post object
        } else { //we are editing a record 
            HttpEntity = new HttpPut(MedicineCustomerRootURL + startDate); //so make a http put object
        }

        String jsonString = new String(gson.toJson(ctm));
        System.out.println("json string: " + jsonString);
        StringEntity postString = new StringEntity(jsonString);

        HttpEntity.setEntity(postString);
        HttpEntity.setHeader("Content-type", "application/json");
        HttpResponse response = httpClient.execute(HttpEntity);
        int statusCode = response.getStatusLine().getStatusCode();
        if (statusCode == 204) {
            System.out.println("Customer binded to medicine successfully");
        } else {
            System.out.println("Server error: " + response.getStatusLine());
        }
        dose.setEditable(false);
        startDate.setEditable(false);
        schedule.setEditable(false);
        customerBox.setDisable(true);

    } catch (Exception ex) {
        System.out.println("Error: " + ex);
    }
    try {
        //refresh table
        tableCustomer.setItems(getCustomersTakesMedicines());
    } catch (IOException ex) {
        Logger.getLogger(DevicesController.class.getName()).log(Level.SEVERE, null, ex);
    } catch (Exception ex) {
        Logger.getLogger(DevicesController.class.getName()).log(Level.SEVERE, null, ex);
    }

}

From source file:aajavafx.Schedule1Controller.java

public void deleteRow(int id) {

    try {//  w  ww .ja v  a 2s  .  com
        String idToDelete = id + "";
        CredentialsProvider provider = new BasicCredentialsProvider();
        UsernamePasswordCredentials credentials = new UsernamePasswordCredentials("EMPLOYEE", "password");
        provider.setCredentials(AuthScope.ANY, credentials);
        HttpClient httpClient = HttpClientBuilder.create().setDefaultCredentialsProvider(provider).build();
        HttpDelete delete = new HttpDelete("http://localhost:8080/MainServerREST/api/employeeschedule/" + id);
        HttpResponse response = httpClient.execute(delete);
        System.out.println("you want to delete: " + id);
    } catch (Exception ex) {
        System.out.println(ex);
    }
}

From source file:aajavafx.Schedule1Controller.java

public ObservableList<CustomerProperty> getCustomer() throws IOException, JSONException {
    Customers customers = new Customers();
    Gson gson = new Gson();
    ObservableList<CustomerProperty> customerProperty = 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/customers");
    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);
        customers = gson.fromJson(jo.toString(), Customers.class);

        customerProperty.add(new CustomerProperty(customers.getCuId(), customers.getCuFirstname(),
                customers.getCuLastname(), customers.getCuPersonnummer()));
    }/*w w  w.j  a v  a2s.c  om*/
    return customerProperty;

}

From source file:aajavafx.Schedule1Controller.java

public ObservableList<EmployeeProperty> getEmployee() throws IOException, JSONException {
    Employees myEmployee = new Employees();

    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);
        if (myEmployee.getEmpRegistered() == true) {
            employeesProperty.add(new EmployeeProperty(myEmployee.getEmpId(), myEmployee.getEmpFirstname(),
                    myEmployee.getEmpLastname(), myEmployee.getEmpUsername()));
        }/*  ww w.  j  a  v a 2s  . c o  m*/
    }
    return employeesProperty;
}

From source file:org.fcrepo.integration.http.api.AbstractResourceIT.java

/**
 * Execute an HTTP request with preemptive basic authentication.
 *
 * @param request the request to execute
 * @param username usename to use//from   w  w w. j a  va  2s  . com
 * @param password password to use
 * @return the open responses
 * @throws IOException in case of IOException
 */
@SuppressWarnings("resource")
protected CloseableHttpResponse executeWithBasicAuth(final HttpUriRequest request, final String username,
        final String password) throws IOException {
    final HttpHost target = new HttpHost(HOSTNAME, SERVER_PORT, PROTOCOL);
    final CredentialsProvider credsProvider = new BasicCredentialsProvider();
    credsProvider.setCredentials(new AuthScope(target.getHostName(), target.getPort()),
            new UsernamePasswordCredentials(username, password));
    final CloseableHttpClient httpclient = HttpClients.custom().setDefaultCredentialsProvider(credsProvider)
            .build();
    final AuthCache authCache = new BasicAuthCache();
    final BasicScheme basicAuth = new BasicScheme();
    authCache.put(target, basicAuth);

    final HttpClientContext localContext = HttpClientContext.create();
    localContext.setAuthCache(authCache);
    return httpclient.execute(request, localContext);
}

From source file:aajavafx.Schedule1Controller.java

public ObservableList<EmployeeScheduleProperty> getSchedule() throws IOException, JSONException {
    EmployeeSchedule mySchedule = new EmployeeSchedule();

    Customers customers = new Customers();
    Employees employee = new Employees();
    Gson gson = new Gson();

    ObservableList<EmployeeScheduleProperty> employeeScheduleProperty = 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/employeeschedule");
    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);
        jo = (JSONObject) jsonArray.getJSONObject(i);
        mySchedule = gson.fromJson(jo.toString(), EmployeeSchedule.class);

        employeeScheduleProperty.add(new EmployeeScheduleProperty(mySchedule.getSchId(),
                mySchedule.getSchDate(), mySchedule.getSchFromTime(), mySchedule.getSchUntilTime(),
                mySchedule.getEmplVisitedCust(), mySchedule.getCustomersCuId().getCuPersonnummer(),
                mySchedule.getEmployeesEmpId().getEmpUsername()));
    }/* w  ww .  j a  va 2  s .c om*/

    return employeeScheduleProperty;
}