Example usage for org.apache.http.impl.client BasicCredentialsProvider BasicCredentialsProvider

List of usage examples for org.apache.http.impl.client BasicCredentialsProvider BasicCredentialsProvider

Introduction

In this page you can find the example usage for org.apache.http.impl.client BasicCredentialsProvider BasicCredentialsProvider.

Prototype

public BasicCredentialsProvider() 

Source Link

Document

Default constructor.

Usage

From source file:org.alfresco.http.SharedHttpClientProvider.java

@Override
public HttpClient getHttpClient(String username, String password) {
    DefaultHttpClient client = (DefaultHttpClient) getHttpClient();

    CredentialsProvider credentialsProvider = new BasicCredentialsProvider();
    credentialsProvider.setCredentials(new AuthScope(AuthScope.ANY),
            new UsernamePasswordCredentials(username, password));
    client.setCredentialsProvider(credentialsProvider);

    return client;
}

From source file:com.socrata.ApiBase.java

/**
 * Sets up http authentication (BASIC) for default requests
 *///from w ww.  j  av a 2 s . c om
private void setupBasicAuthentication() {
    Credentials defaultcreds = new UsernamePasswordCredentials(username, password);
    CredentialsProvider credProvider = new BasicCredentialsProvider();

    credProvider.setCredentials(AuthScope.ANY, defaultcreds);

    AuthCache authCache = new BasicAuthCache();
    BasicScheme basicAuth = new BasicScheme();

    httpContext = new BasicHttpContext();
    httpContext.setAttribute(ClientContext.AUTH_CACHE, basicAuth);

    httpClient.setCredentialsProvider(credProvider);
}

From source file:pl.xsolve.verfluchter.rest.RestClient.java

private RestResponse executeRequest(HttpUriRequest request) throws IOException {
    Log.v(TAG, "Final request preperations...");

    HttpParams httpParams = new BasicHttpParams();
    httpParams.setParameter(ConnManagerPNames.MAX_TOTAL_CONNECTIONS, 1);
    httpParams.setParameter(ConnManagerPNames.MAX_CONNECTIONS_PER_ROUTE, new ConnPerRouteBean(1));
    httpParams.setParameter(HttpProtocolParams.USE_EXPECT_CONTINUE, false);
    HttpProtocolParams.setVersion(httpParams, HttpVersion.HTTP_1_1);
    HttpProtocolParams.setContentCharset(httpParams, Charsets.UTF_8.name());

    context = new BasicHttpContext();

    //        if (basicAuthCredentials != null) {
    // ignore that the ssl cert is self signed
    CredentialsProvider credentialsProvider = new BasicCredentialsProvider();
    credentialsProvider.setCredentials(new AuthScope(null, AuthScope.ANY_PORT), // null here means "any host is OK"
            new UsernamePasswordCredentials(basicAuthCredentials.first, basicAuthCredentials.second));
    clientConnectionManager = new ThreadSafeClientConnManager(httpParams, schemeRegistry);

    context.setAttribute("http.auth.credentials-provider", credentialsProvider);
    //        }/*from  www  . jav  a2s.  c  o  m*/

    //connection (client has to be created for every new connection)
    httpclient = new DefaultHttpClient(clientConnectionManager, httpParams);

    for (Cookie cookie : cookies) {
        Log.v(TAG, "Using cookie " + cookie.getName() + "=" + cookie.getValue() + "...");
        httpclient.getCookieStore().addCookie(cookie);
    }

    try {
        httpResponse = httpclient.execute(request, context);

        int responseCode = httpResponse.getStatusLine().getStatusCode();
        Header[] headers = httpResponse.getAllHeaders();
        String errorMessage = httpResponse.getStatusLine().getReasonPhrase();

        HttpEntity entity = httpResponse.getEntity();

        Log.v(TAG, "Got cookies:");
        cookies = httpclient.getCookieStore().getCookies();
        if (cookies.isEmpty()) {
            Log.v(TAG, "None");
        } else {
            for (Cookie cookie : cookies) {
                Log.v(TAG, "---- " + cookie.toString());
            }
        }

        String message = null;
        InputStream inStream = entity.getContent();
        message = SoulTools.convertStreamToString(inStream);

        // Closing the input stream will trigger connection release
        entity.consumeContent();
        inStream.close();

        return new RestResponse(responseCode, message, headers, cookies, errorMessage);
    } catch (ClientProtocolException e) {
        Log.v(TAG, "Encountered ClientProtocolException!");
        e.printStackTrace();
    } catch (IOException e) {
        Log.v(TAG, "Encountered IOException!");
        e.printStackTrace();
    } finally {
        //always shutdown the connection manager
        httpclient.getConnectionManager().shutdown();
    }

    Log.v(TAG, "Returning null RestResponse!");
    return null;
}

From source file:com.predic8.membrane.test.AssertUtils.java

private static DefaultHttpClient getAuthenticatingHttpClient(String host, int port, String user, String pass) {
    DefaultHttpClient hc = new DefaultHttpClient();
    HttpRequestInterceptor preemptiveAuth = new HttpRequestInterceptor() {
        public void process(final HttpRequest request, final HttpContext context)
                throws HttpException, IOException {
            AuthState authState = (AuthState) context.getAttribute(ClientContext.TARGET_AUTH_STATE);
            CredentialsProvider credsProvider = (CredentialsProvider) context
                    .getAttribute(ClientContext.CREDS_PROVIDER);
            HttpHost targetHost = (HttpHost) context.getAttribute(ExecutionContext.HTTP_TARGET_HOST);
            if (authState.getAuthScheme() == null) {
                AuthScope authScope = new AuthScope(targetHost.getHostName(), targetHost.getPort());
                Credentials creds = credsProvider.getCredentials(authScope);
                if (creds != null) {
                    authState.update(new BasicScheme(), creds);
                }//from w w  w. j a  va2s .c  o  m
            }
        }
    };
    hc.addRequestInterceptor(preemptiveAuth, 0);
    Credentials defaultcreds = new UsernamePasswordCredentials(user, pass);
    BasicCredentialsProvider bcp = new BasicCredentialsProvider();
    bcp.setCredentials(new AuthScope(host, port, AuthScope.ANY_REALM), defaultcreds);
    hc.setCredentialsProvider(bcp);
    hc.setCookieStore(new BasicCookieStore());
    return hc;
}

From source file:org.apache.syncope.installer.utilities.HttpUtils.java

private HttpClientContext setAuth(final HttpHost targetHost, final AuthScheme authScheme) {
    final CredentialsProvider credsProvider = new BasicCredentialsProvider();
    credsProvider.setCredentials(new AuthScope(targetHost.getHostName(), targetHost.getPort()),
            new UsernamePasswordCredentials(username, password));
    final HttpClientContext context = HttpClientContext.create();
    final AuthCache authCache = new BasicAuthCache();
    authCache.put(targetHost, authScheme);
    context.setAuthCache(authCache);//from  ww  w .j  a v a2  s .  co m
    context.setCredentialsProvider(credsProvider);
    return context;
}

From source file:com.ibm.watson.developer_cloud.professor_languo.ingestion.RankerCreationUtil.java

/**
 * Creates an HttpClient/*  w w  w  . j  a  v a 2s  . c  o  m*/
 * 
 * @param auth {@link AuthScope} object specifying the scope of this client
 * @param creds {@link Credentials} for the client
 * @return {@link HttpClient} client to make http requests
 */
public static CloseableHttpClient createHttpClient(AuthScope auth, Credentials creds) {
    CredentialsProvider provider = new BasicCredentialsProvider();
    provider.setCredentials(auth, creds);
    CloseableHttpClient client = HttpClientBuilder.create().setDefaultCredentialsProvider(provider).build();
    return client;
}

From source file:eu.diacron.crawlservice.app.Util.java

public static JSONArray getwarcsByCrawlid(String crawlid) {

    JSONArray warcsArray = null;// ww w  .  jav a  2 s.  c o m
    System.out.println("get crawlid");

    CredentialsProvider credsProvider = new BasicCredentialsProvider();
    /*        credsProvider.setCredentials(
     new AuthScope(AuthScope.ANY_HOST, AuthScope.ANY_PORT),
     new UsernamePasswordCredentials("diachron", "7nD9dNGshTtficn"));
     */

    credsProvider.setCredentials(new AuthScope(AuthScope.ANY_HOST, AuthScope.ANY_PORT),
            new UsernamePasswordCredentials(Configuration.REMOTE_CRAWLER_USERNAME,
                    Configuration.REMOTE_CRAWLER_PASS));
    CloseableHttpClient httpclient = HttpClients.custom().setDefaultCredentialsProvider(credsProvider).build();
    try {

        //HttpGet httpget = new HttpGet("http://diachron.hanzoarchives.com/warcs/" + crawlid);
        HttpGet httpget = new HttpGet(Configuration.REMOTE_CRAWLER_URL + crawlid);

        System.out.println("Executing request " + httpget.getRequestLine());
        CloseableHttpResponse response = httpclient.execute(httpget);
        try {
            System.out.println("----------------------------------------");
            System.out.println(response.getStatusLine());
            System.out.println("----------------------------------------");

            String result = "";

            BufferedReader in = new BufferedReader(new InputStreamReader(response.getEntity().getContent()));
            String inputLine;
            while ((inputLine = in.readLine()) != null) {
                System.out.println(inputLine);
                result += inputLine;
            }
            in.close();

            result = result.replace("u'", "'");
            result = result.replace("'", "\"");

            warcsArray = new JSONArray(result);

            for (int i = 0; i < warcsArray.length(); i++) {

                System.out.println("url to download: " + warcsArray.getString(i));

            }

            EntityUtils.consume(response.getEntity());
        } catch (JSONException ex) {
            Logger.getLogger(Util.class.getName()).log(Level.SEVERE, null, ex);
        } finally {
            response.close();
        }
    } catch (IOException ex) {
        Logger.getLogger(Util.class.getName()).log(Level.SEVERE, null, ex);
    } finally {
        try {
            httpclient.close();
        } catch (IOException ex) {
            Logger.getLogger(Util.class.getName()).log(Level.SEVERE, null, ex);
        }
    }

    return warcsArray;
}

From source file:com.ericsson.gerrit.plugins.syncindex.HttpClientProvider.java

private BasicCredentialsProvider buildCredentials() {
    URI uri = URI.create(cfg.getUrl());
    BasicCredentialsProvider creds = new BasicCredentialsProvider();
    creds.setCredentials(new AuthScope(uri.getHost(), uri.getPort()),
            new UsernamePasswordCredentials(cfg.getUser(), cfg.getPassword()));
    return creds;
}

From source file:aajavafx.DevicesController.java

@FXML
private void handleSaveButton(ActionEvent event) {
    //labelError.setText(null);
    try {//from  w  ww.j  av  a2 s. c o m

        String devName = DevName.getText();
        DevName.clear();
        String devID = deviceID.getText();
        deviceID.clear();
        System.out.println(customerBox.getValue());
        String string = (String) customerBox.getValue();
        System.out.println("STRING VALUE: " + string);
        int customerId = Integer.parseInt("" + string.charAt(0));
        System.out.println("CUSTOMER ID VALUE:" + customerId);
        Customers customer = getCustomerByID(customerId);

        Gson gson = new Gson();

        //......for ssl handshake....
        CredentialsProvider provider = new BasicCredentialsProvider();
        UsernamePasswordCredentials credentials = new UsernamePasswordCredentials("EMPLOYEE", "password");
        provider.setCredentials(AuthScope.ANY, credentials);
        //........
        HttpClient httpClient = HttpClientBuilder.create().build();
        HttpEntityEnclosingRequestBase HttpEntity = null; //this is the superclass for post, put, get, etc
        if (deviceID.isEditable()) { //then we are posting a new record
            HttpEntity = new HttpPost(DevicesCustomerRootURL); //so make a http post object
        } else { //we are editing a record 
            HttpEntity = new HttpPut(DevicesCustomerRootURL + devID); //so make a http put object
        }
        DevicesCustomers devCust = new DevicesCustomers(devID, devName, customer);

        String jsonString = new String(gson.toJson(devCust));
        System.out.println("json string: " + jsonString);
        StringEntity postString = new StringEntity(jsonString);

        HttpEntity.setEntity(postString);
        HttpEntity.setHeader("Content-type", "application/json");
        HttpResponse response = httpClient.execute(HttpEntity);
        int statusCode = response.getStatusLine().getStatusCode();
        if (statusCode == 204) {
            System.out.println("Device posted successfully");
        } else {
            System.out.println("Server error: " + response.getStatusLine());
        }
        DevName.setEditable(false);
        deviceID.setEditable(false);
        customerBox.setDisable(true);

    } catch (Exception ex) {
        System.out.println("Error: " + ex);
    }
    try {
        //refresh table
        tableCustomer.setItems(getDevicesCustomer());
    } catch (IOException ex) {
        Logger.getLogger(DevicesController.class.getName()).log(Level.SEVERE, null, ex);
    } catch (Exception ex) {
        Logger.getLogger(DevicesController.class.getName()).log(Level.SEVERE, null, ex);
    }

}