Example usage for org.apache.http.auth AuthScope ANY

List of usage examples for org.apache.http.auth AuthScope ANY

Introduction

In this page you can find the example usage for org.apache.http.auth AuthScope ANY.

Prototype

AuthScope ANY

To view the source code for org.apache.http.auth AuthScope ANY.

Click Source Link

Document

Default scope matching any host, port, realm and authentication scheme.

Usage

From source file:org.hawkular.alerts.actions.elasticsearch.ElasticsearchPlugin.java

private CredentialsProvider checkBasicCredentials(Action a) {
    String user = a.getProperties().get(PROP_USER);
    String password = a.getProperties().get(PROP_PASS);
    if (!isEmpty(user)) {
        if (!isEmpty(password)) {
            CredentialsProvider credentialsProvider = new BasicCredentialsProvider();
            credentialsProvider.setCredentials(AuthScope.ANY, new UsernamePasswordCredentials(user, password));
            return credentialsProvider;
        } else {//from   ww w.jav a  2 s  .  com
            log.warnf("User [%s] without password ", user);
        }
    }
    return null;
}

From source file:org.glassfish.jersey.apache.connector.AuthTest.java

@Test
@Ignore("JERSEY-1750: Cannot retry request with a non-repeatable request entity. How to buffer the entity?"
        + " Allow repeatable write in jersey?")
public void testAuthInteractivePost() {
    CredentialsProvider credentialsProvider = new org.apache.http.impl.client.BasicCredentialsProvider();
    credentialsProvider.setCredentials(AuthScope.ANY, new UsernamePasswordCredentials("name", "password"));

    ClientConfig cc = new ClientConfig();
    cc.property(ApacheClientProperties.CREDENTIALS_PROVIDER, credentialsProvider);
    cc.connectorProvider(new ApacheConnectorProvider());
    Client client = ClientBuilder.newClient(cc);
    WebTarget r = client.target(getBaseUri()).path("test");

    assertEquals("POST", r.request().post(Entity.text("POST"), String.class));
}

From source file:aajavafx.CustomerMedicineController.java

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

    ObservableList<Customers> customers = FXCollections.observableArrayList();
    Customers myCustomer = new Customers();
    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/customers");

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

    //JSONArray jsonArray = new JSONArray(IOUtils.toString(new URL(CustomersRootURL), 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);//from w  w  w  .java2 s  .co  m

    }
    return customers;
}

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 ww  .j a v  a2  s. com
    return devicesCustomers;
}

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()));

    }//from w  w w . j  a  va2 s .  c  o m

    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:fi.laverca.util.CommonsHTTPSender.java

/**
 * Extracts info from message context./* w  ww.  ja v a 2  s. c o  m*/
 *
 * @param method Post method
 * @param httpClient The client used for posting
 * @param msgContext the message context
 * @param tmpURL the url to post to.
 *
 * @throws Exception if any error occurred
 */
private void addContextInfo(final HttpPost method, final HttpClient httpClient, final MessageContext msgContext,
        final URL tmpURL) throws Exception {
    HttpParams params = method.getParams();

    if (msgContext.getTimeout() != 0) {
        // optionally set a timeout for response waits
        HttpConnectionParams.setSoTimeout(params, msgContext.getTimeout());
    }

    // Always set the 30 second timeout on establishing the connection
    HttpConnectionParams.setConnectionTimeout(params, connectionTimeout);

    Message msg = msgContext.getRequestMessage();
    if (msg != null) {
        method.setHeader(HTTPConstants.HEADER_CONTENT_TYPE, msg.getContentType(msgContext.getSOAPConstants()));
    }

    if (msgContext.useSOAPAction()) {
        // define SOAPAction header
        String action = msgContext.getSOAPActionURI();
        if (action != null && !"".equals(action))
            method.setHeader(HTTPConstants.HEADER_SOAP_ACTION, "\"" + action + "\"");
    }

    String userID = msgContext.getUsername();
    String passwd = msgContext.getPassword();

    // if UserID is not part of the context, but is in the URL, use
    // the one in the URL.
    if ((userID == null) && (tmpURL.getUserInfo() != null)) {
        String info = tmpURL.getUserInfo();
        int sep = info.indexOf(':');

        if ((sep >= 0) && (sep + 1 < info.length())) {
            userID = info.substring(0, sep);
            passwd = info.substring(sep + 1);
        } else {
            userID = info;
        }
    }
    if (userID != null) {
        Credentials proxyCred = new UsernamePasswordCredentials(userID, passwd);
        // if the username is in the form "user\domain"
        // then use NTCredentials instead.
        int domainIndex = userID.indexOf("\\");
        if (domainIndex > 0) {
            String domain = userID.substring(0, domainIndex);
            if (userID.length() > domainIndex + 1) {
                String user = userID.substring(domainIndex + 1);
                proxyCred = new NTCredentials(user, passwd, NetworkUtils.getLocalHostname(), domain);
            }
        }
        ((DefaultHttpClient) httpClient).getCredentialsProvider().setCredentials(AuthScope.ANY, proxyCred);
    }

    // add compression headers if needed
    if (msgContext.isPropertyTrue(HTTPConstants.MC_ACCEPT_GZIP)) {
        method.addHeader(HTTPConstants.HEADER_ACCEPT_ENCODING, HTTPConstants.COMPRESSION_GZIP);
    }
    if (msgContext.isPropertyTrue(HTTPConstants.MC_GZIP_REQUEST)) {
        method.addHeader(HTTPConstants.HEADER_CONTENT_ENCODING, HTTPConstants.COMPRESSION_GZIP);
    }

    // Transfer MIME headers of SOAPMessage to HTTP headers.
    MimeHeaders mimeHeaders = msg.getMimeHeaders();
    if (mimeHeaders != null) {
        for (Iterator<?> i = mimeHeaders.getAllHeaders(); i.hasNext();) {
            MimeHeader mimeHeader = (MimeHeader) i.next();
            //HEADER_CONTENT_TYPE and HEADER_SOAP_ACTION are already set.
            //Let's not duplicate them.
            String headerName = mimeHeader.getName();
            if (headerName.equals(HTTPConstants.HEADER_CONTENT_TYPE)
                    || headerName.equals(HTTPConstants.HEADER_SOAP_ACTION)) {
                continue;
            }
            method.addHeader(mimeHeader.getName(), mimeHeader.getValue());
        }
    }

    // process user defined headers for information.
    Hashtable<?, ?> userHeaderTable = (Hashtable<?, ?>) msgContext.getProperty(HTTPConstants.REQUEST_HEADERS);

    if (userHeaderTable != null) {
        for (Iterator<?> e = userHeaderTable.entrySet().iterator(); e.hasNext();) {
            Map.Entry<?, ?> me = (Map.Entry<?, ?>) e.next();
            Object keyObj = me.getKey();

            if (null == keyObj) {
                continue;
            }
            String key = keyObj.toString().trim();
            String value = me.getValue().toString().trim();

            if (key.equalsIgnoreCase(HTTPConstants.HEADER_EXPECT)
                    && value.equalsIgnoreCase(HTTPConstants.HEADER_EXPECT_100_Continue)) {
                HttpProtocolParams.setUseExpectContinue(params, true);
            } else if (key.equalsIgnoreCase(HTTPConstants.HEADER_TRANSFER_ENCODING_CHUNKED)) {
                String val = me.getValue().toString();
                if (null != val) {
                    httpChunkStream = JavaUtils.isTrue(val);
                }
            } else {
                method.addHeader(key, value);
            }
        }
    }
}

From source file:fr.gael.dhus.sync.impl.ODataProductSynchronizer.java

/** Downloads a product. */
private void downloadProduct(Product p) throws IOException, InterruptedException {
    // Creates a client producer that produces HTTP Basic auth aware clients
    HttpAsyncClientProducer cliprod = new HttpAsyncClientProducer() {
        @Override/*from  www .  jav  a2s . c o  m*/
        public CloseableHttpAsyncClient generateClient() {
            CredentialsProvider credsProvider = new BasicCredentialsProvider();
            credsProvider.setCredentials(new AuthScope(AuthScope.ANY),
                    new UsernamePasswordCredentials(serviceUser, servicePass));
            CloseableHttpAsyncClient res = HttpAsyncClients.custom()
                    .setDefaultCredentialsProvider(credsProvider).build();
            res.start();
            return res;
        }
    };

    // Asks the Incoming manager for a download path
    Path dir = Paths.get(INCOMING_MANAGER.getNewIncomingPath().toURI());
    Path tmp_pd = dir.resolve(p.getIdentifier() + ".part"); // Temporary names
    Path tmp_ql = dir.resolve(p.getIdentifier() + "-ql.part");
    Path tmp_tn = dir.resolve(p.getIdentifier() + "-tn.part");
    // These files will be moved once download is complete

    InterruptibleHttpClient http_client = new InterruptibleHttpClient(cliprod);
    DownloadResult pd_res = null, ql_res = null, tn_res = null;
    try {
        long delta = System.currentTimeMillis();
        pd_res = downloadValidateRename(http_client, tmp_pd, p.getOrigin());
        logODataPerf(p.getOrigin(), System.currentTimeMillis() - delta);

        // Sets download info in the product (not written in the db here)
        p.setPath(pd_res.data.toUri().toURL());
        p.setDownloadablePath(pd_res.data.toString());
        p.setDownloadableType(pd_res.dataType);
        p.setDownloadableSize(pd_res.dataSize);

        // Downloads and sets the quicklook and thumbnail (if any)
        if (p.getQuicklookFlag()) {
            // Failing at downloading a quicklook must not abort the download!
            try {
                ql_res = downloadValidateRename(http_client, tmp_ql, p.getQuicklookPath());
                p.setQuicklookPath(ql_res.data.toString());
                p.setQuicklookSize(ql_res.dataSize);
            } catch (IOException ex) {
                LOGGER.error("Failed to download quicklook at " + p.getQuicklookPath(), ex);
            }
        }
        if (p.getThumbnailFlag()) {
            // Failing at downloading a thumbnail must not abort the download!
            try {
                tn_res = downloadValidateRename(http_client, tmp_tn, p.getThumbnailPath());
                p.setThumbnailPath(tn_res.data.toString());
                p.setThumbnailSize(tn_res.dataSize);
            } catch (IOException ex) {
                LOGGER.error("Failed to download thumbnail at " + p.getThumbnailPath(), ex);
            }
        }
    } catch (Exception ex) {
        // Removes downloaded files if an error occured
        if (pd_res != null) {
            Files.delete(pd_res.data);
        }
        if (ql_res != null) {
            Files.delete(ql_res.data);
        }
        if (tn_res != null) {
            Files.delete(tn_res.data);
        }
        throw ex;
    }
}

From source file:org.botlibre.util.Utils.java

public static String httpAuthPOST(String url, String user, String password, Map<String, String> formParams)
        throws Exception {
    HttpPost request = new HttpPost(url);

    List<NameValuePair> params = new ArrayList<NameValuePair>();
    for (Map.Entry<String, String> entry : formParams.entrySet()) {
        params.add(new BasicNameValuePair(entry.getKey(), entry.getValue()));
    }/*from www.j av a  2s.co m*/
    request.setEntity(new UrlEncodedFormEntity(params, "UTF-8"));

    DefaultHttpClient client = new DefaultHttpClient();
    client.getCredentialsProvider().setCredentials(new AuthScope(AuthScope.ANY),
            new UsernamePasswordCredentials(user, password));
    HttpResponse response = client.execute(request);
    return fetchResponse(response);
}