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.mqm.client.AbstractMqmRestClient.java

/**
 * Constructor for AbstractMqmRestClient.
 *
 * @param connectionConfig MQM connection configuration, Fields 'location', 'domain', 'project' and 'clientType' must not be null or empty.
 *//*from  w  ww  .  j  a v  a2s .c  o  m*/
protected AbstractMqmRestClient(MqmConnectionConfig connectionConfig) {
    checkNotEmpty("Parameter 'location' must not be null or empty.", connectionConfig.getLocation());
    checkNotEmpty("Parameter 'sharedSpace' must not be null or empty.", connectionConfig.getSharedSpace());
    checkNotEmpty("Parameter 'clientType' must not be null or empty.", connectionConfig.getClientType());
    clientType = connectionConfig.getClientType();
    location = connectionConfig.getLocation();
    sharedSpace = connectionConfig.getSharedSpace();
    username = connectionConfig.getUsername();
    password = connectionConfig.getPassword();

    PoolingHttpClientConnectionManager cm = new PoolingHttpClientConnectionManager();
    cm.setMaxTotal(20);
    cm.setDefaultMaxPerRoute(20);
    cookieStore = new BasicCookieStore();

    if (connectionConfig.getProxyHost() != null && !connectionConfig.getProxyHost().isEmpty()) {
        HttpHost proxy = new HttpHost(connectionConfig.getProxyHost(), connectionConfig.getProxyPort());

        RequestConfig requestConfig = RequestConfig.custom().setProxy(proxy)
                .setConnectTimeout(connectionConfig.getDefaultConnectionTimeout() != null
                        ? connectionConfig.getDefaultConnectionTimeout()
                        : DEFAULT_CONNECTION_TIMEOUT)
                .setSocketTimeout(connectionConfig.getDefaultSocketTimeout() != null
                        ? connectionConfig.getDefaultSocketTimeout()
                        : DEFAULT_SO_TIMEOUT)
                .build();

        if (connectionConfig.getProxyCredentials() != null) {
            AuthScope proxyAuthScope = new AuthScope(connectionConfig.getProxyHost(),
                    connectionConfig.getProxyPort());
            Credentials credentials = proxyCredentialsToCredentials(connectionConfig.getProxyCredentials());

            CredentialsProvider credsProvider = new BasicCredentialsProvider();
            credsProvider.setCredentials(proxyAuthScope, credentials);

            httpClient = HttpClients.custom().setConnectionManager(cm).setDefaultCookieStore(cookieStore)
                    .setDefaultCredentialsProvider(credsProvider).setDefaultRequestConfig(requestConfig)
                    .build();
        } else {
            httpClient = HttpClients.custom().setConnectionManager(cm).setDefaultCookieStore(cookieStore)
                    .setDefaultRequestConfig(requestConfig).build();
        }
    } else {
        RequestConfig requestConfig = RequestConfig.custom()
                .setConnectTimeout(connectionConfig.getDefaultConnectionTimeout() != null
                        ? connectionConfig.getDefaultConnectionTimeout()
                        : DEFAULT_CONNECTION_TIMEOUT)
                .setSocketTimeout(connectionConfig.getDefaultSocketTimeout() != null
                        ? connectionConfig.getDefaultSocketTimeout()
                        : DEFAULT_SO_TIMEOUT)
                .build();
        httpClient = HttpClients.custom().setConnectionManager(cm).setDefaultCookieStore(cookieStore)
                .setDefaultRequestConfig(requestConfig).build();
    }
}

From source file:aajavafx.Schedule1Controller.java

public double getNumbersOfHoursPerDay(int id) throws JSONException, IOException {
    double numberHours = 0;
    double numberStart = 0;
    double numberFinish = 0;
    //Customers customers = new Customers();
    EmployeeSchedule mySchedule = new EmployeeSchedule();

    Gson gson = new Gson();
    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/date/" + getDate());
    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("2 " + jsonArray);

    for (int i = 0; i < jsonArray.length(); i++) {
        jo = (JSONObject) jsonArray.getJSONObject(i);

        mySchedule = gson.fromJson(jo.toString(), EmployeeSchedule.class);
        if (mySchedule.getEmployeesEmpId().getEmpId().equals(id)) {
            numberFinish = Double.valueOf(mySchedule.getSchUntilTime()) + numberFinish;
            System.out.println("Finish: " + Double.valueOf(mySchedule.getSchUntilTime()));
            numberStart = Double.valueOf(mySchedule.getSchFromTime()) + numberStart;
        }/* w  w  w.  j  a  v a  2  s. co m*/
    }
    numberHours = numberFinish - numberStart;

    return numberHours;
}

From source file:org.opennms.smoketest.OpenNMSSeleniumTestCase.java

private Integer doRequest(final HttpRequestBase request)
        throws ClientProtocolException, IOException, InterruptedException {
    final CountDownLatch waitForCompletion = new CountDownLatch(1);

    final URI uri = request.getURI();
    final HttpHost targetHost = new HttpHost(uri.getHost(), uri.getPort(), uri.getScheme());
    CredentialsProvider credsProvider = new BasicCredentialsProvider();
    credsProvider.setCredentials(new AuthScope(targetHost.getHostName(), targetHost.getPort()),
            new UsernamePasswordCredentials("admin", "admin"));
    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);//w ww  .ja  v  a 2  s. com

    final CloseableHttpClient client = HttpClients.createDefault();

    final ResponseHandler<Integer> responseHandler = new ResponseHandler<Integer>() {
        @Override
        public Integer handleResponse(final HttpResponse response) throws ClientProtocolException, IOException {
            try {
                final int status = response.getStatusLine().getStatusCode();
                // 400 because we return that if you try to delete something that is already deleted
                // 404 because it's OK if it's already not there
                if (status >= 200 && status < 300 || status == 400 || status == 404) {
                    EntityUtils.consume(response.getEntity());
                    return status;
                } else {
                    throw new ClientProtocolException("Unexpected response status: " + status);
                }
            } finally {
                waitForCompletion.countDown();
            }
        }
    };

    final Integer status = client.execute(targetHost, request, responseHandler, context);

    waitForCompletion.await();
    client.close();
    return status;
}

From source file:org.alfresco.provision.ActiveMQService.java

private CloseableHttpClient buildClient() {
    CredentialsProvider credsProvider = new BasicCredentialsProvider();
    credsProvider.setCredentials(new AuthScope(activeMQHost, activeMQPort),
            new UsernamePasswordCredentials(username, password));
    PoolingHttpClientConnectionManager poolingConnManager = new PoolingHttpClientConnectionManager();
    poolingConnManager.setMaxTotal(200);

    CloseableHttpClient client = HttpClients.custom().setConnectionManager(poolingConnManager)
            .setDefaultCredentialsProvider(credsProvider).build();
    client.getParams().setParameter(CoreConnectionPNames.CONNECTION_TIMEOUT, 5);
    client.getParams().setParameter(CoreConnectionPNames.SO_TIMEOUT, 5);
    return client;
}

From source file:aajavafx.Schedule1Controller.java

public ObservableList<CustomerProperty> getUnsignedCustomers() throws IOException, JSONException {
    //Customers customers = new Customers();
    EmployeeSchedule mySchedule = new EmployeeSchedule();
    singleton = Singleton.getInstance();
    Gson gson = new Gson();

    ObservableList<CustomerProperty> customerPropertyCustomersSigned = FXCollections.observableArrayList();
    ObservableList<CustomerProperty> customerPropertyAllCustomers = this.getCustomer();
    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/date/" + getDate());
    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("1 " + jsonArray);

    for (int i = 0; i < jsonArray.length(); i++) {
        jo = (JSONObject) jsonArray.getJSONObject(i);

        mySchedule = gson.fromJson(jo.toString(), EmployeeSchedule.class);

        customerPropertyCustomersSigned.add(new CustomerProperty(mySchedule.getCustomersCuId().getCuId(),
                mySchedule.getCustomersCuId().getCuFirstname(), mySchedule.getCustomersCuId().getCuLastname(),
                mySchedule.getCustomersCuId().getCuPersonnummer()));

    }// w ww.ja  v a  2s . com

    for (int i = 0; i < customerPropertyAllCustomers.size(); i++) {

        for (int j = 0; j < customerPropertyCustomersSigned.size(); j++) {

            if (customerPropertyAllCustomers.get(i).getPersonnumer()
                    .equals(customerPropertyCustomersSigned.get(j).getPersonnumer())) {

                customerPropertyAllCustomers.remove(i);
            }
        }
    }

    singleton.setList(customerPropertyAllCustomers);
    return customerPropertyAllCustomers;
}

From source file:org.yamj.api.common.http.SimpleHttpClientBuilder.java

/**
 * Create the CloseableHttpClient// w w w. j a  v  a 2 s.  c o m
 *
 * @return
 */
public CloseableHttpClient build() {
    // create proxy
    HttpHost proxy = null;
    CredentialsProvider credentialsProvider = null;

    if (isNotBlank(proxyHost) && proxyPort > 0) {
        proxy = new HttpHost(proxyHost, proxyPort);

        if (isNotBlank(proxyUsername) && isNotBlank(proxyPassword)) {
            if (systemProperties) {
                credentialsProvider = new SystemDefaultCredentialsProvider();
            } else {
                credentialsProvider = new BasicCredentialsProvider();
            }
            credentialsProvider.setCredentials(new AuthScope(proxyHost, proxyPort),
                    new UsernamePasswordCredentials(proxyUsername, proxyPassword));
        }
    }

    HttpClientBuilder builder = HttpClientBuilder.create().setMaxConnTotal(maxConnTotal)
            .setMaxConnPerRoute(maxConnPerRoute).setProxy(proxy)
            .setDefaultCredentialsProvider(credentialsProvider)
            .setDefaultRequestConfig(RequestConfig.custom()
                    .setConnectionRequestTimeout(connectionRequestTimeout).setConnectTimeout(connectTimeout)
                    .setSocketTimeout(socketTimeout).setProxy(proxy).build());

    // use system properties
    if (systemProperties) {
        builder.useSystemProperties();
    }

    // build the http client
    return builder.build();
}

From source file:org.codice.alliance.nsili.endpoint.requests.OrderRequestImpl.java

protected void writeFile(FileLocation destination, InputStream fileData, long size, String name,
        String contentType) throws IOException {
    CloseableHttpClient httpClient = null;
    String urlPath = protocol + "://" + destination.host_name + ":" + port + "/" + destination.path_name + "/"
            + name;/*from www.j av a  2 s. c o m*/

    LOGGER.debug("Writing ordered file to URL: {}", urlPath);

    try {
        HttpPut putMethod = new HttpPut(urlPath);
        putMethod.addHeader(HTTP.CONTENT_TYPE, contentType);
        HttpEntity httpEntity = new InputStreamEntity(fileData, size);
        putMethod.setEntity(httpEntity);

        if (destination.user_name != null && destination.password != null) {
            CredentialsProvider credsProvider = new BasicCredentialsProvider();
            credsProvider.setCredentials(new AuthScope(destination.host_name, port),
                    new UsernamePasswordCredentials(destination.user_name, destination.password));
            httpClient = HttpClients.custom().setDefaultCredentialsProvider(credsProvider).build();
        } else {
            httpClient = HttpClients.createDefault();
        }

        httpClient.execute(putMethod);
        fileData.close();
        putMethod.releaseConnection();
    } finally {
        if (httpClient != null) {
            httpClient.close();
        }
    }
}

From source file:org.syncany.cli.CommandLineClient.java

private int sendToRest(Command command, String commandName, String[] commandArgs, File portFile) {
    try {/*  w w  w  .j  a  va 2s . c o m*/
        // Read port config (for daemon) from port file
        PortTO portConfig = readPortConfig(portFile);

        // Create authentication details
        CredentialsProvider credentialsProvider = new BasicCredentialsProvider();
        credentialsProvider.setCredentials(new AuthScope(SERVER_HOSTNAME, portConfig.getPort()),
                new UsernamePasswordCredentials(portConfig.getUser().getUsername(),
                        portConfig.getUser().getPassword()));

        // Allow all hostnames in CN; this is okay as long as hostname is localhost/127.0.0.1!
        // See: https://github.com/syncany/syncany/pull/196#issuecomment-52197017
        X509HostnameVerifier hostnameVerifier = new AllowAllHostnameVerifier();

        // Fetch the SSL context (using the user key/trust store)
        SSLContext sslContext = UserConfig.createUserSSLContext();

        // Create client with authentication details
        CloseableHttpClient client = HttpClients.custom().setSslcontext(sslContext)
                .setHostnameVerifier(hostnameVerifier).setDefaultCredentialsProvider(credentialsProvider)
                .build();

        // Build and send request, print response
        Request request = buildFolderRequestFromCommand(command, commandName, commandArgs,
                config.getLocalDir().getAbsolutePath());
        String serverUri = SERVER_SCHEMA + SERVER_HOSTNAME + ":" + portConfig.getPort() + SERVER_REST_API;

        String xmlMessageString = XmlMessageFactory.toXml(request);
        StringEntity xmlMessageEntity = new StringEntity(xmlMessageString);

        HttpPost httpPost = new HttpPost(serverUri);
        httpPost.setEntity(xmlMessageEntity);

        logger.log(Level.INFO, "Sending HTTP Request to: " + serverUri);
        logger.log(Level.FINE, httpPost.toString());
        logger.log(Level.FINE, xmlMessageString);

        HttpResponse httpResponse = client.execute(httpPost);
        int exitCode = handleRestResponse(command, httpResponse);

        return exitCode;
    } catch (Exception e) {
        logger.log(Level.SEVERE, "Command " + command.toString() + " FAILED. ", e);
        return showErrorAndExit(e.getMessage());
    }
}

From source file:aajavafx.Schedule1Controller.java

@FXML
private void handleValidate(ActionEvent event) {
    String tempDate;/*  w  w w . java2  s  . c o  m*/
    String tempEmpId;
    String tempCustId;
    String tempFinish;
    String tempStart;

    tempDate = dateText.getText();
    tempEmpId = textEmpId.getText();
    tempCustId = textCustId.getText();
    tempFinish = textFinish.getText();
    tempStart = textStart.getText();
    int empId = Integer.valueOf(tempEmpId);
    int cuId = Integer.valueOf(tempCustId);

    try {
        Gson gson = new Gson();
        Employees employee = new Employees(empId);
        Customers customers = new Customers(cuId);
        EmployeeSchedule schedule = new EmployeeSchedule(1, tempDate, tempStart, tempFinish, false, customers,
                employee);

        CredentialsProvider provider = new BasicCredentialsProvider();
        UsernamePasswordCredentials credentials = new UsernamePasswordCredentials("EMPLOYEE", "password");
        provider.setCredentials(AuthScope.ANY, credentials);

        HttpClient httpClient = HttpClientBuilder.create().setDefaultCredentialsProvider(provider).build();
        HttpPost post = new HttpPost("http://localhost:8080/MainServerREST/api/employeeschedule");

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

        post.setEntity(postString);
        post.setHeader("Content-type", "application/json");
        HttpResponse response = httpClient.execute(post);
        System.out.println("Post response: " + response);
    } catch (UnsupportedEncodingException ex) {
        System.out.println(ex);
    } catch (IOException e) {
        System.out.println(e);
    }
    try {
        tableSchedule.setItems(getSchedule());
    } catch (IOException ex) {
        Logger.getLogger(EmployeeController.class.getName()).log(Level.SEVERE, null, ex);
    } catch (JSONException ex) {
        Logger.getLogger(EmployeeController.class.getName()).log(Level.SEVERE, null, ex);
    }

}