Example usage for org.apache.http.auth UsernamePasswordCredentials UsernamePasswordCredentials

List of usage examples for org.apache.http.auth UsernamePasswordCredentials UsernamePasswordCredentials

Introduction

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

Prototype

public UsernamePasswordCredentials(final String userName, final String password) 

Source Link

Document

The constructor with the username and password arguments.

Usage

From source file:ca.uhn.fhir.rest.client.HttpBasicAuthInterceptor.java

@Override
public void process(final HttpRequest request, final HttpContext context) throws HttpException, IOException {
    AuthState authState = (AuthState) context.getAttribute(HttpClientContext.TARGET_AUTH_STATE);

    if (authState.getAuthScheme() == null) {
        Credentials creds = new UsernamePasswordCredentials(myUsername, myPassword);
        authState.update(new BasicScheme(), creds);
    }//from  www .j  a  va  2  s  . c  om

}

From source file:org.altchain.neo4j.bitcoind.BitcoinD.java

private JSONObject invokeRPC(String JSONRequestString) throws BitcoindNotRunningException {
    DefaultHttpClient httpclient = new DefaultHttpClient();

    JSONObject responseJsonObj = null;//from w w  w .j a v a2 s .c  om

    try {

        httpclient.getCredentialsProvider().setCredentials(new AuthScope(bitcoindHost, bitcoindPort),
                new UsernamePasswordCredentials("generated_by_armory",
                        "6nkugwdEacEAgqjbCvvVyrgXcZj5Cxr38vTbZ513QJrf"));

        StringEntity myEntity = new StringEntity(JSONRequestString);
        logger.debug("JSON Request Object: " + JSONRequestString);

        HttpPost httppost = new HttpPost("http://" + this.bitcoindHost + ":" + this.bitcoindPort);
        httppost.setEntity(myEntity);

        logger.debug("executing request: " + httppost.getRequestLine());

        HttpEntity entity = null;

        try {

            HttpResponse response = httpclient.execute(httppost);
            entity = response.getEntity();

            logger.debug("HTTP response: " + response.getStatusLine());

        } catch (Exception e) {
            logger.error("CANNOT CONNECT TO BITCOIND.  IS BITCOIN RUNNING?");
            throw new BitcoindNotRunningException();
        }

        if (entity != null) {

            logger.debug("Response content length: " + entity.getContentLength());

        }

        JSONParser parser = new JSONParser();
        responseJsonObj = (JSONObject) parser.parse(EntityUtils.toString(entity));

    } catch (ClientProtocolException e) {
        e.printStackTrace();
    } catch (IOException e) {
        e.printStackTrace();
    } catch (ParseException e) {
        e.printStackTrace();
    } catch (org.json.simple.parser.ParseException e) {
        e.printStackTrace();
    } finally {

        httpclient.getConnectionManager().shutdown();

    }

    return responseJsonObj;

}

From source file:org.opendaylight.defense4all.framework.cli.ControlappsConnector.java

public ControlappsConnector(String username, String password, String restSubPath) throws Exception {

    this.username = username;
    this.password = password;
    restPrefix = "http://" + RESTSERVICE_HOSTNAME + ":" + RESTSERVICE_PORT + restSubPath;

    try {/* w ww.j  a  v  a2 s .  c  o m*/
        objMapper = new ObjectMapper();
        objMapper.configure(DeserializationConfig.Feature.FAIL_ON_UNKNOWN_PROPERTIES, false); // Ignore unknown fields

        // set authentication for rest template
        AuthScope authScope = new AuthScope(RESTSERVICE_HOSTNAME, RESTSERVICE_PORT, AuthScope.ANY_REALM);
        UsernamePasswordCredentials credentials = new UsernamePasswordCredentials(username, password);
        DefaultHttpClient client = new DefaultHttpClient();
        client.getCredentialsProvider().setCredentials(authScope, credentials);

        HttpComponentsClientHttpRequestFactory factory = new HttpComponentsClientHttpRequestFactory(client);
        restTemplate = new RestTemplate(factory);
        if (restTemplate == null)
            throw new Exception("");
    } catch (Throwable e) {
        throw new Exception("Failed to initialize connection with controlapps. Is it up?");
    }
}

From source file:annis.libgui.Helper.java

/**
 * Creates an authentificiated REST client 
 * @param userName/* w  w  w.j  a v a  2s  .c  om*/
 * @param password
 * @return A newly created client.
 */
public static Client createRESTClient(String userName, String password) {

    DefaultApacheHttpClient4Config rc = new DefaultApacheHttpClient4Config();
    rc.getClasses().add(SaltProjectProvider.class);

    rc.getProperties().put(ApacheHttpClient4Config.PROPERTY_CONNECTION_MANAGER,
            new ThreadSafeClientConnManager());

    if (userName != null && password != null) {
        CredentialsProvider credentialsProvider = new BasicCredentialsProvider();
        credentialsProvider.setCredentials(AuthScope.ANY, new UsernamePasswordCredentials(userName, password));

        rc.getProperties().put(ApacheHttpClient4Config.PROPERTY_CREDENTIALS_PROVIDER, credentialsProvider);
        rc.getProperties().put(ApacheHttpClient4Config.PROPERTY_PREEMPTIVE_BASIC_AUTHENTICATION, true);

    }

    Client c = ApacheHttpClient4.create(rc);
    return c;
}

From source file:com.yaon.NewServlet.java

/**
 * Processes requests for both HTTP <code>GET</code> and <code>POST</code>
 * methods./*from  www. ja  v  a2 s  .com*/
 *
 * @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.jimdo.graylog.net.Request.java

/**
 * Set Credentials for HTTPAuth/*from www. j  a  va 2s  .  c o m*/
 */
public void setHttpAuth(String username, String password) {
    UsernamePasswordCredentials credentials = new UsernamePasswordCredentials(username, password);

    BasicCredentialsProvider credentialsProvider = new BasicCredentialsProvider();
    credentialsProvider.setCredentials(AuthScope.ANY, credentials);

    httpClient.setCredentialsProvider(credentialsProvider);
}

From source file:fr.gael.dhus.util.http.BasicAuthHttpClientProducer.java

@Override
public CloseableHttpAsyncClient generateClient() {
    CredentialsProvider credsProvider = new BasicCredentialsProvider();
    credsProvider.setCredentials(new AuthScope(AuthScope.ANY),
            new UsernamePasswordCredentials(username, password));

    RequestConfig.Builder requestConfigBuilder = RequestConfig.custom();
    if (timeout == 0) {
        requestConfigBuilder.setSocketTimeout(Timeouts.SOCKET_TIMEOUT)
                .setConnectTimeout(Timeouts.CONNECTION_TIMEOUT)
                .setConnectionRequestTimeout(Timeouts.CONNECTION_REQUEST_TIMEOUT);
    } else {//from  w w  w  .j  a  v a 2  s.c o m
        requestConfigBuilder.setSocketTimeout(timeout).setConnectTimeout(timeout)
                .setConnectionRequestTimeout(timeout);
    }

    requestConfigBuilder.setCookieSpec(CookieSpecs.DEFAULT);

    CloseableHttpAsyncClient res = HttpAsyncClients.custom().setDefaultCredentialsProvider(credsProvider)
            .setDefaultRequestConfig(requestConfigBuilder.build()).build();
    res.start();

    return res;
}

From source file:org.tnova.service.catalog.client.RestTemplateFactory.java

@Override
public void afterPropertiesSet() throws Exception {
    final int timeout = 5;

    final RequestConfig requestConfig = RequestConfig.custom().setConnectTimeout(timeout * 1000)
            .setSocketTimeout(timeout * 1000).build();

    final BasicCredentialsProvider credentialsProvider = new BasicCredentialsProvider();
    credentialsProvider.setCredentials(new AuthScope("localhost", 8080, AuthScope.ANY_REALM),
            new UsernamePasswordCredentials("user1", "user1Pass"));
    final CloseableHttpClient client = HttpClientBuilder.create().setDefaultRequestConfig(requestConfig)
            .setDefaultCredentialsProvider(credentialsProvider).build();

    final ClientHttpRequestFactory requestFactory = new HttpComponentsClientHttpRequestFactory(client);
    restTemplate = new RestTemplate(requestFactory);

}