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: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  .c om*/
    }
    numberHours = numberFinish - numberStart;

    return numberHours;
}

From source file:UploadTest.java

@Test
public void appache_test() throws ClientProtocolException, IOException {

    String user = "edoweb-admin";
    String password = "admin";
    String encoding = Base64.encodeBase64String((user + ":" + password).getBytes());
    System.out.println(encoding);
    CredentialsProvider provider = new BasicCredentialsProvider();
    UsernamePasswordCredentials credentials = new UsernamePasswordCredentials(user, password);
    provider.setCredentials(AuthScope.ANY, credentials);
    URL myurl = new URL("http://localhost:9000/resource/frl:6376984/data");

    // ----------------------------------------------------------------------------

    String boundary = "==" + System.currentTimeMillis() + "===";
    String filePath = "/home/raul/test/frl%3A6376982/123.txt";
    File file = new File(filePath);
    String fileLength = Long.toString(file.getTotalSpace());
    HttpEntity entity = MultipartEntityBuilder.create().addTextBody("data", boundary)
            .addBinaryBody("data", file, ContentType.create("application/pdf"), "6376986.pdf").build();
    HttpClient client = HttpClientBuilder.create().setDefaultCredentialsProvider(provider).build();

    HttpPut put = new HttpPut(myurl.toString());
    // put.setHeader("Authorization", "Basic " + encoding);
    // put.setHeader("Accept", "*/*");
    // put.setHeader("Content-Length", fileLength);
    put.setEntity(entity);//from   w  w w.j av  a2 s .  c  o  m
    HttpResponse response = client.execute(put);
    int statusCode = response.getStatusLine().getStatusCode();
    System.out.println(statusCode);
    Assert.assertEquals(statusCode, HttpStatus.SC_OK);
}

From source file:aajavafx.CustomerMedicineController.java

public ObservableList<CustomersTakesMedicines> getCustomersTakesMedicines() throws IOException, JSONException {

    ObservableList<CustomersTakesMedicines> ctMeds = FXCollections.observableArrayList();
    //Managers manager = new Managers();
    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/customersmedicines/");

    HttpResponse response = client.execute(get);
    System.out.println("RESPONSE IS: " + response);
    //...................
    // JSONArray jsonArray = new JSONArray(IOUtils.toString(new URL(MedicineRootURL), Charset.forName("UTF-8")));
    JSONArray jsonArray = new JSONArray(
            IOUtils.toString(response.getEntity().getContent(), Charset.forName("UTF-8")));

    //JSONArray jsonArray = new JSONArray(IOUtils.toString(new URL(MedicineCustomerRootURL), Charset.forName("UTF-8")));
    System.out.println(jsonArray);
    for (int i = 0; i < jsonArray.length(); i++) {
        //get the main json object, which contains customer object, pk object, dosage, start date, schedule and medicine object
        jo = (JSONObject) jsonArray.getJSONObject(i);
        System.out.println("JSON OBJECT #" + i + " " + jo);
        //get the customer json sub-string
        JSONObject custObj = (JSONObject) jo.get("customers");
        Customers customer = gson.fromJson(custObj.toString(), Customers.class);
        //get the primary key json sub-string
        JSONObject pkObj = (JSONObject) jo.get("customersTakesMedicinesPK");
        CustomersTakesMedicinesPK ctmPK = gson.fromJson(pkObj.toString(), CustomersTakesMedicinesPK.class);
        //get the medicine json sub-string
        JSONObject medObj = (JSONObject) jo.get("medicines");
        Medicines medicine = gson.fromJson(medObj.toString(), Medicines.class);
        //get the individual strings
        String dose = jo.getString("medDosage");
        String startDate = jo.getString("medStartDate");
        double schedule = jo.getDouble("medicationintakeschedule");
        CustomersTakesMedicines cuTaMe = new CustomersTakesMedicines(ctmPK, dose, startDate, schedule);
        cuTaMe.setCustomers(customer);/*from  ww w.ja v  a  2s .co  m*/
        cuTaMe.setMedicines(medicine);
        ctMeds.add(cuTaMe);
    }
    return ctMeds;
}

From source file:com.heneryh.aquanotes.io.ApexExecutor.java

public void feedCycle(Cursor cursor, int cycleNumber) throws HandlerException {

    /**//from w w  w .  j a v  a 2 s .c  o  m
     * The cursor contains all of the controller details.
     */
    String lanUri = cursor.getString(ControllersQuery.LAN_URL);
    String wanUri = cursor.getString(ControllersQuery.WAN_URL);
    String user = cursor.getString(ControllersQuery.USER);
    String pw = cursor.getString(ControllersQuery.PW);
    String ssid = cursor.getString(ControllersQuery.WIFI_SSID);
    String model = cursor.getString(ControllersQuery.MODEL);

    String apexBaseURL;

    // Determine if we are on the LAN or WAN and then use appropriate URL

    // Uhg, WifiManager stuff below crashes if wifi not enabled so first we have to check if on wifi
    ConnectivityManager cm = (ConnectivityManager) mActContext.getSystemService(Context.CONNECTIVITY_SERVICE);
    NetworkInfo nInfo = cm.getActiveNetworkInfo();

    if (nInfo.getType() == ConnectivityManager.TYPE_WIFI) {
        // Get the currently connected SSID, if it matches the 'Home' one then use the local WiFi URL rather than the public one
        WifiManager wm = (WifiManager) mActContext.getSystemService(Context.WIFI_SERVICE);
        WifiInfo wInfo = wm.getConnectionInfo();

        // somewhere read this was a quoted string but appears not to be
        if (wInfo.getSSID().equalsIgnoreCase(ssid)) { // the ssid will be quoted in the info class
            apexBaseURL = lanUri;
        } else {
            apexBaseURL = wanUri;
        }
    } else {
        apexBaseURL = wanUri;

    }

    // for this function we need to append to the URL.  I should really
    // check if the "/" was put on the end by the user here to avoid 
    // possible errors.
    if (!apexBaseURL.endsWith("/")) {
        String tmp = apexBaseURL + "/";
        apexBaseURL = tmp;
    }

    // oh, we should also check if it starts with an "http://"
    if (!apexBaseURL.toLowerCase().startsWith("http://")) {
        String tmp = "http://" + apexBaseURL;
        apexBaseURL = tmp;
    }

    // we should also check if it ends with an "status.sht" on the end and remove it.

    // This used to be common for both the Apex and ACiii but during
    // the 4.04 beta Apex release it seemed to have broke and forced
    // me to use status.sht for the Apex.  Maybe it was fixed but I 
    // haven't checked it.
    // edit - this was not needed for the longest while but now that we are pushing just one
    // outlet, the different methods seem to be needed again.  Really not sure why.
    String apexURL;
    if (model.equalsIgnoreCase("AC4")) {
        apexURL = apexBaseURL + "status.sht";
    } else {
        apexURL = apexBaseURL + "cgi-bin/status.cgi";
    }

    //Create credentials for basic auth
    // create a basic credentials provider and pass the credentials
    // Set credentials provider for our default http client so it will use those credentials
    UsernamePasswordCredentials c = new UsernamePasswordCredentials(user, pw);
    BasicCredentialsProvider cP = new BasicCredentialsProvider();
    cP.setCredentials(AuthScope.ANY, c);
    ((DefaultHttpClient) mHttpClient).setCredentialsProvider(cP);

    // Build the POST update which looks like this:
    // form="status"
    // method="post"
    // action="status.sht"
    //
    // name="T5s_state", value="0"   (0=Auto, 1=Man Off, 2=Man On)
    // submit -> name="Update", value="Update"
    // -- or
    // name="FeedSel", value="0"   (0=A, 1=B)
    // submit -> name="FeedCycle", value="Feed"
    // -- or
    // submit -> name="FeedCycle", value="Feed Cancel"

    HttpPost httppost = new HttpPost(apexURL);

    List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(2);

    // Add your data  
    nameValuePairs.add(new BasicNameValuePair("name", "status"));
    nameValuePairs.add(new BasicNameValuePair("method", "post"));
    if (model.equalsIgnoreCase("AC4")) {
        nameValuePairs.add(new BasicNameValuePair("action", "status.sht"));
    } else {
        nameValuePairs.add(new BasicNameValuePair("action", "/cgi-bin/status.cgi"));
    }

    String cycleNumberString = Integer.toString(cycleNumber).trim();
    if (cycleNumber < 4) {
        nameValuePairs.add(new BasicNameValuePair("FeedSel", cycleNumberString));
        nameValuePairs.add(new BasicNameValuePair("FeedCycle", "Feed"));
    } else {
        nameValuePairs.add(new BasicNameValuePair("FeedCycle", "Feed Cancel"));
    }

    nameValuePairs.add(new BasicNameValuePair("Update", "Update"));
    try {

        httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));

        HttpResponse resp = mHttpClient.execute(httppost);
        final int status = resp.getStatusLine().getStatusCode();
        if (status != HttpStatus.SC_OK) {
            throw new HandlerException(
                    "Unexpected server response " + resp.getStatusLine() + " for " + httppost.getRequestLine());
        }
    } catch (HandlerException e) {
        throw e;
    } catch (ClientProtocolException e) {
        throw new HandlerException("Problem reading remote response for " + httppost.getRequestLine(), e);
    } catch (IOException e) {
        throw new HandlerException("Problem reading remote response for " + httppost.getRequestLine(), e);
    }

}

From source file:com.ibm.watson.developer_cloud.professor_languo.pipeline.RnrMergerAndRanker.java

/**
 * Returns the status of the specified ranker
 * /*from w w w.  java 2 s.c o  m*/
 * @param ranker_id of the ranker
 * @return status. e.g. "Available", "Training", "Failed"
 * @throws IOException
 */
public String getRankerStatus(String ranker_id) throws IOException {

    String status = null;
    JSONObject res;
    // Create authorized HttpClient
    client = RankerCreationUtil.createHttpClient(AuthScope.ANY, creds);

    try {
        HttpGet httpget = new HttpGet(ranker_url + "/" + ranker_id);
        CloseableHttpResponse response = client.execute(httpget);

        try {

            String result = EntityUtils.toString(response.getEntity());
            res = (JSONObject) JSON.parse(result);
            status = (String) res.get("status");

        } catch (NullPointerException | JSONException e) {
            logger.error(e.getMessage());
        }

        finally {
            response.close();
        }
    }

    finally {
        client.close();
    }

    return status;
}

From source file:aajavafx.CustomerController.java

@FXML
private void handleRegisterButton(ActionEvent event) {
    //labelError.setText(null);
    try {//from  w  w w .ja v  a2  s  . c  o m
        //String customerNumber = customerID.getText();
        //customerID.clear();
        String lastName = lastNameID.getText();
        lastNameID.clear();
        String firstName = firstNameID.getText();
        firstNameID.clear();
        String address = addressID.getText();
        addressID.clear();
        String birthdate = birthdateID.getText();
        birthdateID.clear();
        String persunnumer = persunnumerID.getText();
        persunnumerID.clear();
        try {
            Gson gson = new Gson();
            Customers customer = new Customers(1, firstName, lastName, address, birthdate, persunnumer);
            String jsonString = new String(gson.toJson(customer));
            System.out.println("json string: " + jsonString);
            StringEntity postString = new StringEntity(jsonString);
            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(postCustomerURL);
            post.setEntity(postString);
            post.setHeader("Content-type", "application/json");
            HttpResponse response = httpClient.execute(post);
            ByteArrayOutputStream outstream = new ByteArrayOutputStream();
            if (response != null) {
                response.getEntity().writeTo(outstream);
                byte[] responseBody = outstream.toByteArray();
                String str = new String(responseBody, "UTF-8");
                System.out.print(str);
            } else {
                System.out.println("Success");
            }
        } catch (UnsupportedEncodingException ex) {
            System.out.println(ex);
        } catch (IOException e) {
            System.out.println(e);
        }
    } catch (Exception ex) {
        ex.printStackTrace();
        // labelError.setText("Salary or phone field does not have a integer!");
    }
}

From source file:com.ge.research.semtk.sparqlX.SparqlEndpointInterface.java

/**
 * Execute an auth query using POST/*from  ww  w. j  ava 2s.co  m*/
 * @return a JSONObject wrapping the results. in the event the results were tabular, they can be obtained in the JsonArray "@Table". if the results were a graph, use "@Graph" for json-ld
 * @throws Exception
 */
private JSONObject executeQueryAuthPost(String query, SparqlResultTypes resultType) throws Exception {

    if (resultType == null) {
        resultType = getDefaultResultType();
    }

    DefaultHttpClient httpclient = new DefaultHttpClient();

    httpclient.getCredentialsProvider().setCredentials(AuthScope.ANY,
            new UsernamePasswordCredentials(this.userName, this.password));

    String[] serverNoProtocol = this.server.split("://");
    //System.err.println("the new server name is: " + serverNoProtocol[1]);

    HttpHost targetHost = new HttpHost(serverNoProtocol[1], Integer.valueOf(this.port), "http");

    DigestScheme digestAuth = new DigestScheme();
    AuthCache authCache = new BasicAuthCache();
    digestAuth.overrideParamter("realm", "SPARQL");
    // Suppose we already know the expected nonce value
    digestAuth.overrideParamter("nonce", "whatever");
    authCache.put(targetHost, digestAuth);
    BasicHttpContext localcontext = new BasicHttpContext();
    localcontext.setAttribute(ClientContext.AUTH_CACHE, authCache);

    // add new stuff
    HttpPost httppost = new HttpPost(getPostURL());
    String resultsFormat = this.getContentType(resultType);
    httppost.addHeader("Accept", resultsFormat);
    httppost.addHeader("X-Sparql-default-graph", this.dataset);

    // add params
    List<NameValuePair> params = new ArrayList<NameValuePair>(3);
    params.add(new BasicNameValuePair("query", query));
    params.add(new BasicNameValuePair("format", resultsFormat));
    params.add(new BasicNameValuePair("default-graph-uri", this.dataset));

    httppost.setEntity(new UrlEncodedFormEntity(params, "UTF-8"));

    // finish new stuff

    HttpResponse response_http = httpclient.execute(targetHost, httppost, localcontext);
    HttpEntity entity = response_http.getEntity();
    String responseTxt = EntityUtils.toString(entity, "UTF-8");

    // some diagnostic output
    if (responseTxt == null) {
        System.err.println("the response text was null!");
    }

    if (responseTxt.trim().isEmpty()) {
        handleEmptyResponse(); // implementation-specific behavior
    }

    JSONObject resp;
    try {
        resp = (JSONObject) JSONValue.parse(responseTxt);
    } catch (Exception e) {
        entity.getContent().close();
        throw new Exception("Cannot parse query result into JSON: " + responseTxt);
    }

    if (resp == null) {
        System.err.println("the response could not be transformed into json");

        if (responseTxt.contains("Error")) {
            entity.getContent().close();
            throw new Exception(responseTxt);
        }
        entity.getContent().close();
        return null;
    } else {
        JSONObject procResp = getResultsFromResponse(resp, resultType);
        entity.getContent().close();

        return procResp;
    }
}

From source file:cn.edu.zzu.wemall.http.AsyncHttpClient.java

/**
 * Sets basic authentication for the request. Uses AuthScope.ANY. This is the same as
 * setBasicAuth('username','password',AuthScope.ANY)
 *
 * @param username Basic Auth username/*ww  w.j  a va2 s .c o m*/
 * @param password Basic Auth password
 */
public void setBasicAuth(String username, String password) {
    AuthScope scope = AuthScope.ANY;
    setBasicAuth(username, password, scope);
}

From source file:alien4cloud.paas.cloudify2.rest.external.RestClientExecutor.java

/**
 *
 * @param username .//from www. j  a va2 s. c o m
 * @param password .
 */
public void setCredentials(final String username, final String password) {
    if (StringUtils.notEmpty(username) && StringUtils.notEmpty(password)) {
        httpClient.getCredentialsProvider().setCredentials(new AuthScope(AuthScope.ANY),
                new UsernamePasswordCredentials(username, password));
    }
}

From source file:com.googlecode.sardine.SardineImpl.java

/**
 * Small wrapper around HttpClient.execute() in order to wrap the IOException into a SardineException.
 *///w  w  w .j  a v a 2 s . c om
private HttpResponse executeWrapper(HttpRequestBase base) throws SardineException {
    try {
        if (this.authEnabled) {
            Credentials creds = this.client.getCredentialsProvider().getCredentials(AuthScope.ANY);
            String value = "Basic " + new String(Base64.encodeBase64(
                    new String(creds.getUserPrincipal().getName() + ":" + creds.getPassword()).getBytes()));
            base.setHeader("Authorization", value);
        }

        return this.client.execute(base);
    } catch (IOException ex) {
        base.abort();
        throw new SardineException(ex);
    }
}