Example usage for org.apache.http.impl.client DefaultHttpClient getCredentialsProvider

List of usage examples for org.apache.http.impl.client DefaultHttpClient getCredentialsProvider

Introduction

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

Prototype

public synchronized final CredentialsProvider getCredentialsProvider() 

Source Link

Usage

From source file:org.wso2.developerstudio.appfactory.core.client.HttpsJenkinsClient.java

public static HttpResponse getBulildinfo(String applicationId, String version, String builderBaseUrl,
        int lastBuildNo) {

    DefaultHttpClient client = new DefaultHttpClient();
    client = (DefaultHttpClient) HttpsJaggeryClient.wrapClient(client, builderBaseUrl);
    client.getCredentialsProvider().setCredentials(new AuthScope(AuthScope.ANY_HOST, AuthScope.ANY_PORT),
            new UsernamePasswordCredentials(Authenticator.getInstance().getCredentials().getUser(),
                    Authenticator.getInstance().getCredentials().getPassword()));

    // Generate BASIC scheme object and stick it to the execution context
    BasicScheme basicAuth = new BasicScheme();
    BasicHttpContext context = new BasicHttpContext();
    context.setAttribute("preemptive-auth", basicAuth);

    // Add as the first (because of the zero) request interceptor
    // It will first intercept the request and preemptively initialize the authentication scheme if there is not
    client.addRequestInterceptor(new PreemptiveAuth(), 0);
    String getUrl = builderBaseUrl + "/job/" + applicationId + "-" + version + "-default/" + lastBuildNo
            + "/consoleText";
    HttpGet get = new HttpGet(getUrl);

    try {/*  w w w . j a  va 2  s. com*/
        // Execute your request with the given context
        HttpResponse response = client.execute(get, context);
        return response;
    } catch (Exception e) {
        log.error("Jenkins Client err", e);
    }
    return null;
}

From source file:se.vgregion.util.HTTPUtils.java

public static HttpResponse basicAuthRequest(String url, String username, String password,
        DefaultHttpClient client) throws HttpUtilsException {
    HttpGet get = new HttpGet(url);

    client.getCredentialsProvider().setCredentials(new AuthScope(null, 443),
            new UsernamePasswordCredentials(username, password));

    BasicHttpContext localcontext = new BasicHttpContext();

    // Generate BASIC scheme object and stick it to the local
    // execution context
    BasicScheme basicAuth = new BasicScheme();
    localcontext.setAttribute("preemptive-auth", basicAuth);

    // Add as the first request interceptor
    client.addRequestInterceptor(new PreemptiveAuth(), 0);
    HttpResponse response;/*from   ww  w  .  ja  v a2  s. c om*/
    try {
        response = client.execute(get, localcontext);
    } catch (ClientProtocolException e) {
        throw new HttpUtilsException("Invalid http protocol", e);
    } catch (IOException e) {
        throw new HttpUtilsException(e.getMessage(), e);
    }
    return response;
}

From source file:org.deegree.maven.utils.HttpUtils.java

public static HttpClient getAuthenticatedHttpClient(ServiceIntegrationTestHelper helper) {
    DefaultHttpClient client = new DefaultHttpClient();
    HttpConnectionParams.setConnectionTimeout(client.getParams(), 30000);
    HttpConnectionParams.setSoTimeout(client.getParams(), 1200000);
    client.getCredentialsProvider().setCredentials(AuthScope.ANY,
            new UsernamePasswordCredentials("deegree", "deegree"));
    // preemptive authentication used to be easier in pre-4.x httpclient
    AuthCache authCache = new BasicAuthCache();
    BasicScheme basicAuth = new BasicScheme();
    HttpHost host = new HttpHost("localhost", Integer.parseInt(helper.getPort()));
    authCache.put(host, basicAuth);/*from   www .  j a va 2s . c  o  m*/
    BasicHttpContext localcontext = new BasicHttpContext();
    localcontext.setAttribute(AUTH_CACHE, authCache);
    return client;
}

From source file:org.apiwatch.util.IO.java

public static void putAPIData(APIScope scope, String format, String encoding, String location, String username,
        String password) throws SerializationError, IOException, HttpException {
    if (URL_RX.matcher(location).matches()) {
        DefaultHttpClient client = new DefaultHttpClient();
        if (username != null && password != null) {
            client.getCredentialsProvider().setCredentials(new AuthScope(null, -1),
                    new UsernamePasswordCredentials(username, password));
        }//from  w w  w.j av a 2s. c o m
        HttpPost req = new HttpPost(location);
        StringWriter writer = new StringWriter();
        Serializers.dumpAPIScope(scope, writer, format);
        HttpEntity entity = new StringEntity(writer.toString(), encoding);
        req.setEntity(entity);
        req.setHeader("content-type", format);
        req.setHeader("content-encoding", encoding);
        HttpResponse response = client.execute(req);
        client.getConnectionManager().shutdown();
        if (response.getStatusLine().getStatusCode() >= 400) {
            throw new HttpException(response.getStatusLine().getReasonPhrase());
        }
        LOGGER.info("Sent results to URL: " + location);
    } else {
        File dir = new File(location);
        dir.mkdirs();
        File file = new File(dir, "api." + format);
        OutputStream out = new FileOutputStream(file);
        Writer writer = new OutputStreamWriter(out, encoding);
        Serializers.dumpAPIScope(scope, writer, format);
        writer.flush();
        writer.close();
        out.close();
        LOGGER.info("Wrote results to file: " + file);
    }
}

From source file:org.apiwatch.util.IO.java

public static APIScope getAPIData(String source, String format, String encoding, String username,
        String password) throws IOException, SerializationError, HttpException {
    File file = new File(source);
    APIScope scope = null;//from   w  w w . j  a va  2s .  c  o  m
    if (file.isFile()) {
        if (format == null) {
            /* get format from file extension */
            format = source.substring(source.lastIndexOf('.') + 1);
        }
        InputStream in = new FileInputStream(file);
        Reader reader = new InputStreamReader(in, encoding);
        scope = Serializers.loadAPIScope(reader, format);
        reader.close();
        in.close();
    } else {
        /* maybe source is a URL */
        DefaultHttpClient client = new DefaultHttpClient();
        if (username != null && password != null) {
            client.getCredentialsProvider().setCredentials(new AuthScope(null, -1),
                    new UsernamePasswordCredentials(username, password));
        }
        HttpResponse response = client.execute(new HttpGet(source));
        if (response.getStatusLine().getStatusCode() >= 400) {
            throw new HttpException(response.getStatusLine().getReasonPhrase());
        }
        HttpEntity entity = response.getEntity();
        ContentType contentType = ContentType.fromHeader(entity.getContentType().getValue());
        if (entity.getContentEncoding() != null) {
            encoding = entity.getContentEncoding().getValue();
        } else if (contentType.charset != null) {
            encoding = contentType.charset;
        }
        if (format == null) {
            format = contentType.type;
        }
        InputStream in = entity.getContent();
        Reader reader = new InputStreamReader(in, encoding);
        scope = Serializers.loadAPIScope(reader, format);
        reader.close();
        in.close();
        client.getConnectionManager().shutdown();
    }
    return scope;
}

From source file:com.codebutler.rsp.Util.java

public static String getURL(URL url, String password) throws Exception {
    Log.i("Util.getURL", url.toString());

    DefaultHttpClient client = new DefaultHttpClient();

    if (password != null && password.length() > 0) {
        UsernamePasswordCredentials creds;
        creds = new UsernamePasswordCredentials("user", password);
        client.getCredentialsProvider().setCredentials(AuthScope.ANY, creds);
    }//from   ww w .j  a v a 2 s .c o  m

    HttpGet method = new HttpGet(url.toURI());
    BasicResponseHandler responseHandler = new BasicResponseHandler();
    return client.execute(method, responseHandler);
}

From source file:org.wso2.developerstudio.appfactory.core.client.RssClient.java

public static String getDBinfo(String operation, String dsBaseUrl) {
    String url = dsBaseUrl + "NDataSourceAdmin";
    DefaultHttpClient client = new DefaultHttpClient();
    client = (DefaultHttpClient) HttpsJaggeryClient.wrapClient(client, url);
    client.getCredentialsProvider().setCredentials(new AuthScope(AuthScope.ANY_HOST, AuthScope.ANY_PORT),
            new UsernamePasswordCredentials(Authenticator.getInstance().getCredentials().getUser(),
                    Authenticator.getInstance().getCredentials().getPassword()));

    // Generate BASIC scheme object and stick it to the execution context
    BasicScheme basicAuth = new BasicScheme();
    BasicHttpContext context = new BasicHttpContext();
    context.setAttribute("preemptive-auth", basicAuth);
    client.addRequestInterceptor(new PreemptiveAuth(), 0);

    HttpPost post = new HttpPost(url);
    String sopactionValue = "urn:" + operation;
    post.addHeader("SOAPAction", sopactionValue);
    String body = createPayLoad(operation);
    try {/*from w  ww  . j a v a  2 s .co m*/
        StringEntity entity = new StringEntity(body.toString(), "text/xml", HTTP.DEFAULT_CONTENT_CHARSET);
        post.setEntity(entity);
        HttpResponse response = client.execute(post);
        if (200 == response.getStatusLine().getStatusCode()) {
            HttpEntity entityGetAppsOfUser = response.getEntity();
            BufferedReader rd = new BufferedReader(new InputStreamReader(entityGetAppsOfUser.getContent()));
            StringBuilder sb = new StringBuilder();
            String line = "";
            while ((line = rd.readLine()) != null) {
                sb.append(line);
            }
            String respond = sb.toString();
            EntityUtils.consume(entityGetAppsOfUser);
            return respond;
        }
    } catch (Exception e) {
        // log.error("Jenkins Client err", e);
    }
    return null;
}

From source file:org.nuxeo.scim.server.tests.ScimServerTest.java

protected static ClientConfig createHttpBasicClientConfig(final String userName, final String password) {

    final HttpParams params = new BasicHttpParams();
    DefaultHttpClient.setDefaultHttpParams(params);
    params.setBooleanParameter(CoreConnectionPNames.SO_REUSEADDR, true);
    params.setBooleanParameter(CoreProtocolPNames.USE_EXPECT_CONTINUE, true);
    params.setBooleanParameter(CoreConnectionPNames.STALE_CONNECTION_CHECK, true);

    final SchemeRegistry schemeRegistry = new SchemeRegistry();
    schemeRegistry.register(new Scheme("http", 80, PlainSocketFactory.getSocketFactory()));

    final PoolingClientConnectionManager mgr = new PoolingClientConnectionManager(schemeRegistry);
    mgr.setMaxTotal(200);/*ww  w .  j  a v  a  2  s.  c o  m*/
    mgr.setDefaultMaxPerRoute(20);

    final DefaultHttpClient httpClient = new DefaultHttpClient(mgr, params);

    final Credentials credentials = new UsernamePasswordCredentials(userName, password);
    httpClient.getCredentialsProvider().setCredentials(AuthScope.ANY, credentials);
    httpClient.addRequestInterceptor(new PreemptiveAuthInterceptor(), 0);

    ClientConfig clientConfig = new ApacheHttpClientConfig(httpClient);
    clientConfig.setBypassHostnameVerification(true);

    return clientConfig;
}

From source file:net.bioclipse.dbxp.business.DbxpManager.java

public static HttpResponse postValues(HashMap<String, String> postvars, String url)
        throws NoSuchAlgorithmException, ClientProtocolException, IOException {
    DefaultHttpClient httpclient = new DefaultHttpClient();
    httpclient.getCredentialsProvider().setCredentials(new AuthScope(AuthScope.ANY_HOST, AuthScope.ANY_PORT),
            new UsernamePasswordCredentials(userName, password));

    List<NameValuePair> formparams = new ArrayList<NameValuePair>();
    Iterator<Entry<String, String>> it = postvars.entrySet().iterator();
    while (it.hasNext()) {
        Map.Entry<String, String> next = (Map.Entry<String, String>) it.next();
        Map.Entry<String, String> pairs = next;
        formparams.add(new BasicNameValuePair(pairs.getKey(), pairs.getValue()));
    }//from  w ww . jav  a 2  s.com
    UrlEncodedFormEntity entity = new UrlEncodedFormEntity(formparams, "UTF-8");
    HttpPost httppost = new HttpPost(url);
    httppost.setEntity(entity);
    HttpContext localContext = new BasicHttpContext();
    return httpclient.execute(httppost, localContext);
}

From source file:net.bioclipse.dbxp.business.DbxpManager.java

public static Map<String, String> authenticate() throws IOException, NoSuchAlgorithmException {
    DefaultHttpClient httpclient = new DefaultHttpClient();
    httpclient.getCredentialsProvider().setCredentials(new AuthScope(AuthScope.ANY_HOST, AuthScope.ANY_PORT),
            new UsernamePasswordCredentials(userName, password));

    List<NameValuePair> formparams = new ArrayList<NameValuePair>();
    HashMap<String, String> formvars = new HashMap<String, String>();
    formvars.put("deviceID", getDeviceId());
    HttpResponse response = postValues(formvars, baseApiUrl + "authenticate");
    BufferedReader stdInput = new BufferedReader(new InputStreamReader(response.getEntity().getContent()));
    String json = "";
    String s = "";
    while ((s = stdInput.readLine()) != null) {
        json += s;/*  w  w w  .j a  va2 s  .  c o  m*/
    }

    Gson gson = new Gson();
    Map<String, String> loginData = gson.fromJson(json, new TypeToken<Map<String, String>>() {
    }.getType());

    token = loginData.get("token");
    sequence = Integer.valueOf(loginData.get("sequence"));

    return loginData;
}