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.xwiki.wysiwyg.internal.plugin.alfresco.server.BasicAuthenticator.java

@Override
public void authenticate(HttpRequestBase request) {
    UsernamePasswordCredentials credentials = new UsernamePasswordCredentials(configuration.getUserName(),
            configuration.getPassword());
    request.addHeader(BasicScheme.authenticate(credentials, "US-ASCII", false));
}

From source file:com.pm.myshop.controller.CardController.java

@RequestMapping(value = "/validatecard", method = RequestMethod.GET)
public @ResponseBody String authenticateCard(@RequestParam("cardNo") String cardNo,
        @RequestParam("balance") double balance, @RequestParam("cvv") String cvv) throws IOException {

    DefaultHttpClient httpClient = new DefaultHttpClient();

    String encCard = encryptCardNumber(cardNo);

    HttpGet getRequest = new HttpGet("http://localhost:8080/Team4_CardValidator/validate?cardNo=" + encCard
            + "&balance=" + balance + "&cvv=" + cvv);

    getRequest.addHeader(/* ww  w.ja v  a2  s .  c  om*/
            BasicScheme.authenticate(new UsernamePasswordCredentials("admin", "admin"), "UTF-8", false));

    HttpResponse response = httpClient.execute(getRequest);

    if (response.getStatusLine().getStatusCode() != 200) {
        session.setAttribute("cardvalidation", "fail");
        return "fail";
    }

    BufferedReader br = new BufferedReader(new InputStreamReader((response.getEntity().getContent())));
    String output;

    while ((output = br.readLine()) != null) {
        session.setAttribute("cardvalidation", output);
        return output;
    }

    httpClient.getConnectionManager().shutdown();

    session.setAttribute("cardvalidation", "fail");
    return "fail";
}

From source file:org.peterbaldwin.vlcremote.net.ServerConnectionTest.java

@Override
protected Integer doInBackground(Server... servers) {
    if (servers == null || servers.length != 1) {
        return -1;
    }//from w w w . j av  a 2 s  .co m
    URL url;
    try {
        url = new URL("http://" + servers[0].getUri().getAuthority() + TEST_PATH);
        HttpURLConnection connection = (HttpURLConnection) url.openConnection();
        connection.setConnectTimeout(1000);
        try {
            Header auth = BasicScheme.authenticate(
                    new UsernamePasswordCredentials(servers[0].getUser(), servers[0].getPassword()), HTTP.UTF_8,
                    false);
            connection.setRequestProperty(auth.getName(), auth.getValue());
            return connection.getResponseCode();
        } finally {
            connection.disconnect();
        }
    } catch (IOException ex) {

    }
    return -1;
}

From source file:com.yaon.NewServlet.java

/**
 * Processes requests for both HTTP <code>GET</code> and <code>POST</code>
 * methods./*from   w w  w .  ja va2s  . c o m*/
 *
 * @param request servlet request
 * @param response servlet response
 * @throws ServletException if a servlet-specific error occurs
 * @throws IOException if an I/O error occurs
 */
protected void processRequest(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {
    response.setContentType("text");
    PrintWriter out = response.getWriter();
    String ip = request.getParameter("ip");
    String port = request.getParameter("port");
    String uname = request.getParameter("uname");
    String pass = request.getParameter("pass");
    StringWriter sw = new StringWriter();
    if ("null".equals(ip) && "null".equals(port) && "null".equals(uname) && "null".equals(pass)) {

        out.println("Null Argument Passed !!");
    } else {
        try {

            DefaultHttpClient httpClient = new DefaultHttpClient();
            HttpPost postRequest = new HttpPost("http://" + ip + ":" + port + "/Yaon/GetInfo");
            postRequest.addHeader(
                    BasicScheme.authenticate(new UsernamePasswordCredentials(uname, pass), "UTF-8", false));
            HttpResponse res = httpClient.execute(postRequest);

            if (res.getStatusLine().getStatusCode() == 401) {
                throw new Exception("Http Authentication Failed !");
            }

            BufferedReader br = new BufferedReader(new InputStreamReader((res.getEntity().getContent())));

            String output;
            System.out.println("Output from Server.... \n");
            while ((output = br.readLine()) != null) {

                System.out.println(output);
                sw.append(output);
                sw.append("\n");
            }
            httpClient.getConnectionManager().shutdown();

        } catch (HttpHostConnectException e) {
            out.println(e.getMessage());
        } catch (Exception e) {
            out.println(e.getMessage());
        }

        out.println(sw.toString());
    }
}

From source file:com.serena.rlc.provider.schedule.client.ScheduleWaiter.java

@Override
public void run() {
    logger.debug("ScheduleWaiter is sleeping for " + waitTime + " milliseconds, until " + endDate);
    try {/*from  www .  jav  a 2  s  .com*/
        Thread.sleep(waitTime);
    } catch (InterruptedException ex) {
        logger.error("ScheduleWaiter was interrupted: " + ex.getLocalizedMessage());
    } catch (CancellationException ex) {
        logger.error("ScheduleWaiter thread has been cancelled: ", ex.getLocalizedMessage());
    }
    synchronized (executionId) {
        logger.debug("ScheduleWaiter has finished sleeping at " + new Date());

        try {
            String uri = callbackUrl + executionId + "/COMPLETED";
            logger.info("Start executing RLC PUT request to url=\"{}\"", uri);
            DefaultHttpClient rlcParams = new DefaultHttpClient();
            HttpPut put = new HttpPut(uri);
            UsernamePasswordCredentials credentials = new UsernamePasswordCredentials(callbackUsername,
                    callbackPassword);
            put.addHeader(BasicScheme.authenticate(credentials, "US-ASCII", false));
            //put.addHeader("Content-Type", "application/x-www-form-urlencoded");
            //put.addHeader("Accept", "application/json");
            logger.info(credentials.toString());
            HttpResponse response = rlcParams.execute(put);
            if (response.getStatusLine().getStatusCode() != 200) {
                logger.error("HTTP Status Code: " + response.getStatusLine().getStatusCode());
            }
        } catch (IOException ex) {
            logger.error(ex.getLocalizedMessage());
        }

        executionId.notify();
    }

}

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

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

    try {/*from   w  w w .ja v a  2 s .c om*/
        HttpClient httpclient = new DefaultHttpClient();

        UsernamePasswordCredentials creds = new UsernamePasswordCredentials(username, password);
        HttpGet httpget = new HttpGet(baseAddress + "/api/2.0/credits");
        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("credits") == null) {
                logger.error("Error retrieving data. " + obj);
                return;
            }
            Map json = (Map) parser.parse(obj.get("credits").toString(), containerFactory);

            if (json.containsKey("autofillsms")) {
                if (json.get("autofillsms").toString().equals("false")) {
                    metrics.put("Credits|autofillsms", 0);
                } else if (json.get("autofillsms").toString().equals("true")) {
                    metrics.put("Credits|autofillsms", 1);
                } else {
                    logger.error("can't determine whether Credits|autofillsms is true or false!");
                }
            }

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

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

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

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

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

    } catch (IOException e1) {
        logger.error(e1.getMessage());
    } catch (Throwable t) {
        logger.error(t.getMessage());
    }

}

From source file:com.appdynamics.monitors.varnish.VarnishWrapper.java

/**
 * Gets the JsonObject by parsing the JSON return from hitting the /stats url
 * @return  JsonObject containing the response from hitting the /stats url for Varnish
 * @throws  Exception//from w w  w  .j  av  a2  s . c o m
 */
private JsonObject getResponseData() throws Exception {
    String metricsURL = constructVarnishStatsURL();
    HttpGet httpGet = new HttpGet(metricsURL);
    httpGet.addHeader(
            BasicScheme.authenticate(new UsernamePasswordCredentials(username, password), "UTF-8", false));

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

From source file:org.apache.hadoop.gateway.hive.HiveHttpClientDispatch.java

protected void addCredentialsToRequest(HttpUriRequest request) {
    if (isBasicAuthPreemptive()) {
        Principal principal = getPrimaryPrincipal();
        if (principal != null) {

            UsernamePasswordCredentials credentials = new UsernamePasswordCredentials(principal.getName(),
                    PASSWORD_PLACEHOLDER);

            request.addHeader(BasicScheme.authenticate(credentials, "US-ASCII", false));
        }/* w ww.ja v a 2 s  . c  o m*/
    }
}

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

/**
 * Returns HTTP GET response entity string from given url using admin credentials
 *
 * @param url request url suffix//from ww  w . j ava2s  .  c o m
 * @return HttpResponse from get request
 */
public static String getRequest(String url) throws IOException {

    String restUrl = getRestEndPoint(url);
    log.info("Sending HTTP GET request: " + restUrl);
    client = new DefaultHttpClient();
    request = new HttpGet(restUrl);

    request.addHeader(BasicScheme.authenticate(new UsernamePasswordCredentials("admin", "admin"),
            Charset.defaultCharset().toString(), false));
    client.getConnectionManager().closeExpiredConnections();
    HttpResponse response = client.execute(request);
    return EntityUtils.toString(response.getEntity());
}

From source file:com.ibm.watson.developer_cloud.android.text_to_speech.v1.TextToSpeech.java

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 {/*w  w w . java2 s  . c  o m*/
        Log.d(TAG, "using basic authentication");
        httpGet.setHeader(BasicScheme
                .authenticate(new UsernamePasswordCredentials(this.username, this.password), "UTF-8", false));
    }
}