Example usage for org.apache.http.impl.auth BasicScheme authenticate

List of usage examples for org.apache.http.impl.auth BasicScheme authenticate

Introduction

In this page you can find the example usage for org.apache.http.impl.auth BasicScheme authenticate.

Prototype

@Deprecated
public static Header authenticate(final Credentials credentials, final String charset, final boolean proxy) 

Source Link

Document

Returns a basic Authorization header value for the given Credentials and charset.

Usage

From source file:org.wso2.bps.integration.tests.bpmn.BPMNTestUtils.java

public static HttpResponse doPost(String url, Object json, String user, String password) throws IOException {
    String restUrl = getRestEndPoint(url);
    log.info("Sending HTTP POST request: " + restUrl);
    client = new DefaultHttpClient();
    post = new HttpPost(restUrl);
    post.addHeader(BasicScheme.authenticate(new UsernamePasswordCredentials(user, password),
            Charset.defaultCharset().toString(), false));
    post.setEntity(new StringEntity(json.toString(), ContentType.APPLICATION_JSON));
    client.getConnectionManager().closeExpiredConnections();
    HttpResponse response = client.execute(post);
    return response;
}

From source file:com.appdynamics.monitors.boundary.BoundaryWrapper.java

/**
 * Retrieves network traffic data in the past minute from Boundary
 * @param   observationIds     A comma separated list of valid observationIds needed to make the historical API REST request
 * @return  responseData       A JsonArray containing all the ip_addresses, and their respective network traffic metrics
 *///from  ww w .  j a  v a 2  s . co m
private JsonArray getResponseData(String observationIds) throws Exception {
    String metricsURL = constructMetricsURL();
    HttpPost httpPost = new HttpPost(metricsURL);
    httpPost.addHeader(BasicScheme.authenticate(new UsernamePasswordCredentials(apiKey, ""), "UTF-8", false));

    // Request parameters and other properties.
    List<NameValuePair> params = new ArrayList<NameValuePair>(2);
    params.add(new BasicNameValuePair("aggregations", "observationDomainId"));
    params.add(new BasicNameValuePair("observationDomainIds", observationIds));
    Long currentTime = System.currentTimeMillis();
    Long oneMinuteAgo = currentTime - 60000;
    params.add(new BasicNameValuePair("from", oneMinuteAgo.toString()));
    params.add(new BasicNameValuePair("to", currentTime.toString()));
    httpPost.setEntity(new UrlEncodedFormEntity(params, "UTF-8"));

    HttpClient httpClient = new DefaultHttpClient();
    HttpResponse response = httpClient.execute(httpPost);
    HttpEntity entity = response.getEntity();
    BufferedReader bufferedReader2 = new BufferedReader(new InputStreamReader(entity.getContent()));
    StringBuilder responseString = new StringBuilder();
    String line = "";
    while ((line = bufferedReader2.readLine()) != null) {
        responseString.append(line);
    }
    JsonObject responseObject = new JsonParser().parse(responseString.toString()).getAsJsonObject();
    JsonArray responseData = responseObject.getAsJsonArray("data");
    return responseData;
}

From source file:org.wso2.bps.integration.tests.bpmn.BPMNTestUtils.java

/**
 * Returns response after the given DELETE request
 *
 * @param url string url suffix to delete the request
 * @return HttpResponse for the post request
 * @throws IOException//w  ww .  ja v a  2s .  c  o  m
 */
public static HttpResponse deleteRequest(String url) throws IOException {
    String restUrl = getRestEndPoint(url);
    log.info("Sending HTTP DELETE request: " + restUrl);
    HttpClient client = new DefaultHttpClient();
    HttpDelete delete = new HttpDelete(restUrl);
    delete.addHeader(BasicScheme.authenticate(new UsernamePasswordCredentials("admin", "admin"),
            Charset.defaultCharset().toString(), false));
    client.getConnectionManager().closeExpiredConnections();
    HttpResponse response = client.execute(delete);
    return response;
}

From source file:com.ibm.watson.developer_cloud.android.speech_to_text.v1.SpeechToText.java

/**
 * Build authentication header/*w ww. j  a v a  2  s .c  o m*/
 * @param httpGet
 */
private void buildAuthenticationHeader(HttpGet httpGet) {
    // use token based authentication if possible, otherwise Basic Authentication will be used
    if (this.tokenProvider != null) {
        Log.d(TAG, "using token based authentication");
        httpGet.setHeader("X-Watson-Authorization-Token", this.tokenProvider.getToken());
    } else {
        Log.d(TAG, "using basic authentication");
        httpGet.setHeader(BasicScheme
                .authenticate(new UsernamePasswordCredentials(this.username, this.password), "UTF-8", false));
    }
}

From source file:com.serena.rlc.provider.jira.client.JiraClient.java

/**
 * Execute a put request/* w  w w.j a  v  a2 s . c  om*/
 *
 * @param url
 * @return Response body
 * @throws JiraClientException
 */
private String processPut(SessionData session, String restUrl, String url, String putData)
        throws JiraClientException {
    String uri = restUrl + url;

    logger.debug("Start executing JIRA PUT request to url=\"{}\" with payload={}", uri);

    DefaultHttpClient httpClient = new DefaultHttpClient();
    HttpPut putRequest = new HttpPut(uri);
    UsernamePasswordCredentials creds = new UsernamePasswordCredentials(getJiraUsername(), getJiraPassword());
    putRequest.addHeader(BasicScheme.authenticate(creds, "US-ASCII", false));
    putRequest.addHeader(HttpHeaders.CONTENT_TYPE, "application/json");
    putRequest.addHeader(HttpHeaders.ACCEPT, "application/json");
    String result = "";

    try {
        putRequest.setEntity(new StringEntity(putData));

        HttpResponse response = httpClient.execute(putRequest);
        if (response.getStatusLine().getStatusCode() != HttpStatus.SC_OK) {
            throw createHttpError(response);
        }

        BufferedReader br = new BufferedReader(new InputStreamReader((response.getEntity().getContent())));
        StringBuilder sb = new StringBuilder(1024);
        String output;
        while ((output = br.readLine()) != null) {
            sb.append(output);
        }

        logger.debug("End executing JIRA PUT request to url=\"{}\" and receive this result={}", uri, sb);

        return sb.toString();
    } catch (IOException e) {
        logger.error(e.getMessage(), e);
        throw new JiraClientException("Server not available", e);
    } finally {
        httpClient.getConnectionManager().shutdown();
    }
}

From source file:com.appdynamics.monitors.pingdom.communicator.PingdomCommunicator.java

@SuppressWarnings("rawtypes")
private void getChecks(Map<String, Integer> metrics) {

    try {//from  w  ww  . ja v  a2  s  .  c o  m
        HttpClient httpclient = new DefaultHttpClient();

        UsernamePasswordCredentials creds = new UsernamePasswordCredentials(username, password);
        HttpGet httpget = new HttpGet(baseAddress + "/api/2.0/checks");
        httpget.addHeader(BasicScheme.authenticate(creds, "US-ASCII", false));
        httpget.addHeader("App-Key", appkey);

        HttpResponse response;
        response = httpclient.execute(httpget);
        HttpEntity entity = response.getEntity();

        // reading in the JSON response
        String result = "";
        if (entity != null) {
            InputStream instream = entity.getContent();
            int b;
            try {
                while ((b = instream.read()) != -1) {
                    result += Character.toString((char) b);
                }
            } finally {
                instream.close();
            }
        }

        // parsing the JSON response
        try {

            JSONParser parser = new JSONParser();

            ContainerFactory containerFactory = new ContainerFactory() {

                public List creatArrayContainer() {
                    return new LinkedList();
                }

                public Map createObjectContainer() {
                    return new LinkedHashMap();
                }

            };

            // retrieving the metrics and populating HashMap
            JSONObject obj = (JSONObject) parser.parse(result);
            if (obj.get("checks") == null) {
                logger.error("Error retrieving data. " + obj);
                return;
            }
            JSONArray array = (JSONArray) parser.parse(obj.get("checks").toString());
            for (Object checkObj : array) {
                JSONObject check = (JSONObject) checkObj;

                Map json = (Map) parser.parse(check.toJSONString(), containerFactory);

                String metricName = "";

                if (json.containsKey("name")) {
                    metricName = "Checks|" + json.get("name") + "|";
                } else {
                    logger.error("Encountered error while parsing metrics for a check: no name found!");
                    continue;
                }

                if (json.containsKey("id")) {
                    try {
                        metrics.put(metricName + "id", Integer.parseInt(json.get("id").toString()));
                    } catch (NumberFormatException e) {
                        logger.error("Error parsing metric value for " + metricName + "id");
                    }
                }

                if (json.containsKey("lastresponsetime")) {
                    try {
                        metrics.put(metricName + "lastresponsetime",
                                Integer.parseInt(json.get("lastresponsetime").toString()));
                    } catch (NumberFormatException e) {
                        logger.error("Error parsing metric value for " + metricName + "lastresponsetime");
                    }
                }

                if (json.containsKey("lasttesttime")) {
                    try {
                        int testTime = Integer.parseInt(json.get("lasttesttime").toString());
                        java.util.Date date = new java.util.Date(testTime);
                        Calendar cal = GregorianCalendar.getInstance();
                        cal.setTime(date);

                        metrics.put(metricName + "lasttesttime", cal.get(Calendar.HOUR_OF_DAY));
                    } catch (NumberFormatException e) {
                        logger.error("Error parsing metric value for " + metricName + "lasttesttime");
                    } catch (Throwable t) {
                        logger.error("Error parsing metric value for " + metricName
                                + "lasttesttime: can't get hour of day");
                    }
                }

                if (json.containsKey("resolution")) {
                    try {
                        metrics.put(metricName + "resolution",
                                Integer.parseInt(json.get("resolution").toString()));
                    } catch (NumberFormatException e) {
                        logger.error("Error parsing metric value for " + metricName + "resolution");
                    }
                }

                if (json.containsKey("status")) {
                    String status = json.get("status").toString();
                    if (status != null) {
                        if (status.equals("down")) {
                            metrics.put(metricName + "status", 0);
                        } else if (status.equals("up")) {
                            metrics.put(metricName + "status", 1);
                        } else if (status.equals("unconfirmed_down")) {
                            metrics.put(metricName + "status", 5);
                        } else if (status.equals("unknown")) {
                            metrics.put(metricName + "status", 20);
                        } else if (status.equals("paused")) {
                            metrics.put(metricName + "status", 50);
                        } else {
                            logger.error("Error parsing metric value for " + metricName
                                    + "status: Unknown status '" + status + "'");
                        }
                    } else {
                        logger.error("Error parsing metric value for " + metricName + "status");
                    }
                }
            }

        } catch (ParseException e) {
            logger.error("JSON Parsing error: " + e.getMessage());
        } catch (Throwable e) {
            logger.error(e.getMessage());
        }

        // parse header in the end to get the Req-Limits
        Header[] responseHeaders = response.getAllHeaders();
        getLimits(metrics, responseHeaders);
    } catch (IOException e1) {
        logger.error(e1.getMessage());
    } catch (Throwable t) {
        logger.error(t.getMessage());
    }

}

From source file:com.serena.rlc.provider.artifactory.client.ArtifactoryClient.java

/**
 * Execute a get request to Artifactory.
 *
 * @param path  the path for the specific request
 * @param parameters  parameters to send with the query
 * @return String containing the response body
 * @throws ArtifactoryClientException//w  ww.  ja v  a 2  s  .  c o m
 */
protected String processGet(String path, String parameters) throws ArtifactoryClientException {
    String uri = createUrl(path, parameters);

    logger.debug("Start executing Artifactory GET request to url=\"{}\"", uri);

    DefaultHttpClient httpClient = new DefaultHttpClient();
    HttpGet getRequest = new HttpGet(uri);
    UsernamePasswordCredentials creds = new UsernamePasswordCredentials(getArtifactoryUsername(),
            getArtifactoryPassword());
    getRequest.addHeader(BasicScheme.authenticate(creds, "US-ASCII", false));
    getRequest.addHeader(HttpHeaders.CONTENT_TYPE, DEFAULT_HTTP_CONTENT_TYPE);
    getRequest.addHeader(HttpHeaders.ACCEPT, DEFAULT_HTTP_CONTENT_TYPE);
    getRequest.addHeader("X-Result-Detail", "info, properties");
    String result = "";

    try {
        HttpResponse response = httpClient.execute(getRequest);
        if (response.getStatusLine().getStatusCode() != org.apache.http.HttpStatus.SC_OK) {
            throw createHttpError(response);
        }

        BufferedReader br = new BufferedReader(new InputStreamReader((response.getEntity().getContent())));
        StringBuilder sb = new StringBuilder(1024);
        String output;
        while ((output = br.readLine()) != null) {
            sb.append(output);
        }
        result = sb.toString();
    } catch (IOException ex) {
        logger.error(ex.getMessage(), ex);
        throw new ArtifactoryClientException("Server not available", ex);
    } finally {
        httpClient.getConnectionManager().shutdown();
    }

    logger.debug("End executing Artifactory GET request to url=\"{}\" and receive this result={}", uri, result);

    return result;
}

From source file:org.wso2.bps.integration.tests.bpmn.BPMNTestUtils.java

public static HttpResponse doPut(String url, Object payload, String user, String password) throws IOException {
    String restUrl = getRestEndPoint(url);
    HttpClient client = new DefaultHttpClient();
    HttpPut put = new HttpPut(restUrl);
    put.addHeader(BasicScheme.authenticate(new UsernamePasswordCredentials(user, password), "UTF-8", false));
    put.setEntity(new StringEntity(payload.toString(), ContentType.APPLICATION_JSON));
    client.getConnectionManager().closeExpiredConnections();
    HttpResponse response = client.execute(put);
    return response;
}

From source file:org.openmrs.module.dhisreport.web.controller.ReportDefinitionController.java

@RequestMapping(value = "/module/dhisreport/getReportDefinitions", method = RequestMethod.POST)
public String getReportDefinitions(WebRequest webRequest, HttpServletRequest request) {
    String username = Context.getAdministrationService().getGlobalProperty("dhisreport.dhis2UserName");
    String password = Context.getAdministrationService().getGlobalProperty("dhisreport.dhis2Password");
    String dhisurl = Context.getAdministrationService().getGlobalProperty("dhisreport.dhis2URL");
    String url = dhisurl + "/api/dataSets";
    //String url = "https://play.dhis2.org/demo/api/dataSets";
    String referer = webRequest.getHeader("Referer");
    HttpSession session = request.getSession();

    try {// w w  w  .  j a  va 2s  . c  om
        DefaultHttpClient httpClient = new DefaultHttpClient();
        HttpGet getRequest = new HttpGet(url);
        getRequest.addHeader("accept", "application/dsd+xml");
        getRequest.addHeader(
                BasicScheme.authenticate(new UsernamePasswordCredentials(username, password), "UTF-8", false));
        HttpResponse response = httpClient.execute(getRequest);

        if (response.getStatusLine().getStatusCode() != 200) {
            log.error("Failed : HTTP error code : " + response.getStatusLine().getStatusCode());
        }

        InputStream is = response.getEntity().getContent();
        try {
            DHIS2ReportingService service = Context.getService(DHIS2ReportingService.class);
            service.unMarshallandSaveReportTemplates(is);
            session.setAttribute(WebConstants.OPENMRS_MSG_ATTR,
                    Context.getMessageSourceService().getMessage("dhisreport.uploadSuccess"));
        } catch (Exception ex) {
            log.error("Error loading file: " + ex);
            session.setAttribute(WebConstants.OPENMRS_ERROR_ATTR,
                    Context.getMessageSourceService().getMessage("dhisreport.uploadError"));
        } finally {
            is.close();
        }
        httpClient.getConnectionManager().shutdown();
        return "redirect:" + referer;
    } catch (ClientProtocolException ee) {
        log.debug("An error occured in the HTTP protocol." + ee.toString());
        ee.printStackTrace();
    } catch (IOException ee) {
        log.debug("Problem accessing DHIS2 server: " + ee.toString());
        session.setAttribute(WebConstants.OPENMRS_ERROR_ATTR,
                Context.getMessageSourceService().getMessage("dhisreport.checkConnectionWithDHIS2"));
    }
    return "redirect:" + referer;
}