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:imageLines.ImageHelpers.java

public static Boolean checkImageHeader(String imageURLString, String uname, String pass)
        throws ClientProtocolException {

    /*/*from ww  w. j av a2s.co m*/
    URLConnection conn=imageURL.openConnection();
    String userPassword=user+":"+ pass;
    String encoding = new sun.misc.BASE64Encoder().encode (userPassword.getBytes());
    conn.setRequestProperty ("Authorization", "Basic " + encoding);*/
    DefaultHttpClient httpclient = new DefaultHttpClient();

    ResponseHandler<String> responseHandler = new BasicResponseHandler();

    httpclient.getCredentialsProvider().setCredentials(new AuthScope(AuthScope.ANY),
            new UsernamePasswordCredentials(uname, pass));
    HttpHead head = new HttpHead(imageURLString);
    //HttpGet httpget = new HttpGet(imageURLString);
    System.out.println("executing head request" + head.getRequestLine());

    HttpResponse response;
    try {
        response = httpclient.execute(head);
        int code = response.getStatusLine().getStatusCode();
        if (code == 200 || code == 304)
            return true;
    } catch (IOException ex) {
        Logger.getLogger(ImageHelpers.class.getName()).log(Level.SEVERE, null, ex);
    }
    return false;

}

From source file:imageLines.ImageHelpers.java

/**Read a jpeg image from a url into a BufferedImage*/

public static BufferedImage readAsBufferedImage(String imageURLString, String user, String pass) {
    InputStream i = null;//from  ww  w  .  ja  v  a  2 s .c  om
    try {
        /*
        URLConnection conn=imageURL.openConnection();
        String userPassword=user+":"+ pass;
        String encoding = new sun.misc.BASE64Encoder().encode (userPassword.getBytes());
        conn.setRequestProperty ("Authorization", "Basic " + encoding);*/
        DefaultHttpClient httpclient = new DefaultHttpClient();

        ResponseHandler<String> responseHandler = new BasicResponseHandler();

        httpclient.getCredentialsProvider().setCredentials(new AuthScope(AuthScope.ANY),
                new UsernamePasswordCredentials(user, pass));

        HttpGet httpget = new HttpGet(imageURLString);
        System.out.println("executing request" + httpget.getRequestLine());

        HttpResponse response = httpclient.execute(httpget);

        HttpEntity en = response.getEntity();
        Header[] h = response.getAllHeaders();
        for (int c = 0; c < h.length; c++)
            System.out.print(h[c].getName() + ":" + h[c].getValue() + "\n");

        i = response.getEntity().getContent();
        //JPEGImageDecoder decoder = JPEGCodec.createJPEGDecoder(i);
        BufferedImage bi = ImageIO.read(i);//decoder.decodeAsBufferedImage();
        return bi;
    } catch (Exception e) {
        System.out.println(e);
        return null;
    } finally {
        try {
            if (i != null)
                i.close();
        } catch (IOException ex) {

        }
    }
}

From source file:org.openiot.gsn.utils.VSMonitor.java

public static void readStatus(GSNSessionAddress gsnSessionAddress) throws Exception {

    String httpAddress = gsnSessionAddress.getURL();

    DefaultHttpClient client = new DefaultHttpClient();

    if (gsnSessionAddress.needsPassword()) {
        client.getCredentialsProvider().setCredentials(
                new AuthScope(gsnSessionAddress.getHost(), gsnSessionAddress.getPort()/*, GSN_REALM*/),
                new UsernamePasswordCredentials(gsnSessionAddress.getUsername(),
                        gsnSessionAddress.getPassword()));
    }//from   w w  w.  java 2s .c om

    logger.warn("Querying server: " + httpAddress);
    HttpGet get = new HttpGet(httpAddress);

    try {
        // execute the GET, getting string directly
        ResponseHandler<String> responseHandler = new BasicResponseHandler();
        String responseBody = client.execute(get, responseHandler);

        parseXML(responseBody);

    } catch (HttpResponseException e) {
        errorsBuffer.append("HTTP 401 Authentication Needed for : ").append(httpAddress).append("\n");
    }

    catch (UnknownHostException e) {
        errorsBuffer.append("Unknown host: ").append(httpAddress).append("\n");
        nHostsDown++;
    } catch (ConnectException e) {
        errorsBuffer.append("Connection refused to host: ").append(httpAddress).append("\n");
        nHostsDown++;
    } finally {
        // release any connection resources used by the method
        client.getConnectionManager().shutdown();
    }
}

From source file:net.homelinux.penecoptero.android.citybikes.app.RESTHelper.java

private static DefaultHttpClient setCredentials(DefaultHttpClient httpclient, String url, String username,
        String password) throws HttpException, IOException {
    HttpHost targetHost = new HttpHost(url);
    final UsernamePasswordCredentials access = new UsernamePasswordCredentials(username, password);

    httpclient.getCredentialsProvider()
            .setCredentials(new AuthScope(targetHost.getHostName(), targetHost.getPort()), access);

    httpclient.addRequestInterceptor(new HttpRequestInterceptor() {
        @Override/*ww  w . jav a2 s  . c o  m*/
        public void process(HttpRequest request, HttpContext context) throws HttpException, IOException {

            AuthState authState = (AuthState) context.getAttribute(ClientContext.TARGET_AUTH_STATE);
            if (authState.getAuthScheme() == null) {
                authState.setAuthScheme(new BasicScheme());
                authState.setCredentials(access);
            }
        }
    }, 0);
    return httpclient;
}

From source file:org.openiot.gsn.utils.GSNMonitor.java

public static void readStatus(GSNSessionAddress gsnSessionAddress) throws Exception {

    String httpAddress = gsnSessionAddress.getURL();

    DefaultHttpClient client = new DefaultHttpClient();

    if (gsnSessionAddress.needsPassword()) {
        client.getCredentialsProvider().setCredentials(
                new AuthScope(gsnSessionAddress.getHost(), gsnSessionAddress.getPort()/*, GSN_REALM*/),
                new UsernamePasswordCredentials(gsnSessionAddress.getUsername(),
                        gsnSessionAddress.getPassword()));
    }/*from ww  w .jav a  2  s .  co m*/

    logger.warn("Querying server: " + httpAddress);
    HttpGet get = new HttpGet(httpAddress);

    try {
        // execute the GET, getting string directly
        ResponseHandler<String> responseHandler = new BasicResponseHandler();
        String responseBody = client.execute(get, responseHandler);

        parseXML(responseBody);

    } catch (HttpResponseException e) {
        errorsBuffer.append("HTTP 401 Authentication Needed for : ").append(httpAddress).append("\n");
    } catch (UnknownHostException e) {
        errorsBuffer.append("Unknown host: ").append(httpAddress).append("\n");
        nHostsDown++;
    } catch (ConnectException e) {
        errorsBuffer.append("Connection refused to host: ").append(httpAddress).append("\n");
        raiseStatusTo(STATUS_CRITICAL);
        nHostsDown++;
    } finally {
        // release any connection resources used by the method
        client.getConnectionManager().shutdown();
    }
}

From source file:de.fuberlin.agcsw.heraclitus.svont.client.core.ChangeLog.java

public static void updateChangeLog(OntologyStore os, SVoNtProject sp, String user, String pwd) {

    //load the change log from server

    try {//from  w  w w .j  ava 2s . co  m

        //1. fetch Changelog URI

        URI u = sp.getChangelogURI();

        //2. search for change log owl files
        DefaultHttpClient client = new DefaultHttpClient();

        client.getCredentialsProvider().setCredentials(
                new AuthScope(u.getHost(), AuthScope.ANY_PORT, AuthScope.ANY_SCHEME),
                new UsernamePasswordCredentials(user, pwd));

        HttpGet httpget = new HttpGet(u);

        System.out.println("executing request" + httpget.getRequestLine());

        ResponseHandler<String> responseHandler = new BasicResponseHandler();
        String response = client.execute(httpget, responseHandler);
        System.out.println(response);
        List<String> files = ChangeLog.extractChangeLogFiles(response);

        ArrayList<ChangeLogElement> changelog = sp.getChangelog();
        changelog.clear();

        //4. sort the revisions

        for (int i = 0; i < files.size(); i++) {
            String fileName = files.get(i);
            System.out.println("rev sort: " + fileName);
            int rev = Integer.parseInt(fileName.split("\\.")[0]);
            changelog.add(new ChangeLogElement(URI.create(u + fileName), rev));
        }

        Collections.sort(changelog, new SortChangeLogsElementsByRev());

        //show sorted changelog

        System.out.print("[");
        for (ChangeLogElement cle : changelog) {
            System.out.print(cle.getRev() + ",");
        }
        System.out.println("]");

        //5. map revision with SVN revisionInformations
        mapRevisionInformation(os, sp, changelog);

        //6. load change log files
        System.out.println("Load Changelog Files");
        for (String s : files) {
            System.out.println(s);
            String req = u + s;
            httpget = new HttpGet(req);
            response = client.execute(httpget, responseHandler);
            //            System.out.println(response);

            // save the changelog File persistent
            IFolder chlFold = sp.getChangeLogFolder();
            IFile chlFile = chlFold.getFile(s);
            if (!chlFile.exists()) {
                chlFile.create(new ByteArrayInputStream(response.getBytes()), true, null);
            }

            os.getOntologyManager().loadOntology(new ReaderInputSource(new StringReader(response)));

        }
        System.out.println("Changelog Ontology successfully loaded");

        //Show loaded onts
        Set<OWLOntology> onts = os.getOntologyManager().getOntologies();
        for (OWLOntology o : onts) {
            System.out.println("loaded ont: " + o.getURI());
        }

        //7 refresh possibly modified Mainontology
        os.getOntologyManager().reloadOntology(os.getMainOntologyLocalURI());

        //8. recalculate Revision Information of the concept of this ontology
        sp.setRevisionMap(createConceptRevisionMap(os, sp));
        sp.saveRevisionMap();

        sp.saveRevisionInformationMap();

        //9. show MetaInfos on ConceptTree

        ConceptTree.refreshConceptTree(os, os.getMainOntologyURI());
        OntologyInformation.refreshOntologyInformation(os, os.getMainOntologyURI());

        //shutdown http connection

        client.getConnectionManager().shutdown();

    } catch (ClientProtocolException e1) {
        // TODO Auto-generated catch block
        e1.printStackTrace();
    } catch (IOException e1) {
        // TODO Auto-generated catch block
        e1.printStackTrace();
    } catch (OWLOntologyCreationException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    } catch (OWLReasonerException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    } catch (SVNException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    } catch (SVNClientException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    } catch (ParseException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    } catch (CoreException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }

}

From source file:com.gs.tools.doc.extractor.core.util.HttpUtility.java

public static DefaultHttpClient getLoginHttpClient(String userName, String password) {
    try {/*  ww  w.j  av a2 s  . c  o m*/

        HttpParams params = new BasicHttpParams();
        HttpProtocolParams.setVersion(params, HttpVersion.HTTP_1_1);
        HttpProtocolParams.setContentCharset(params, HTTP.UTF_8);
        HttpConnectionParams.setConnectionTimeout(params, 300000);
        HttpConnectionParams.setSocketBufferSize(params, 10485760);
        HttpConnectionParams.setSoTimeout(params, 300000);

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

        ClientConnectionManager ccm = new ThreadSafeClientConnManager(params, registry);

        DefaultHttpClient httpClient = new DefaultHttpClient(ccm, params);
        httpClient.getCredentialsProvider().setCredentials(
                new AuthScope(AuthScope.ANY_HOST, AuthScope.ANY_PORT, AuthScope.ANY_REALM),
                new UsernamePasswordCredentials(userName, password));
        return httpClient;
    } catch (Exception e) {
        e.printStackTrace();
        return new DefaultHttpClient();
    }
}

From source file:org.openml.knime.OpenMLWebservice.java

/**
 * Upload a run./*from w w w.  ja va  2  s  .  com*/
 * 
 * @param description Description to the run
 * @param files Run files
 * @param user Name of the user
 * @param password Password of the user
 * @return Response from the server
 * @throws Exception
 */
public static String sendRuns(final File description, final File[] files, final String user,
        final String password) throws Exception {
    String result = "";
    DefaultHttpClient httpclient = new DefaultHttpClient();
    Credentials credentials = new UsernamePasswordCredentials(user, password);
    AuthScope scope = new AuthScope(new URI(WEBSERVICEURL).getHost(), 80);
    httpclient.getCredentialsProvider().setCredentials(scope, credentials);
    try {
        String url = WEBSERVICEURL + "?f=openml.run.upload";
        HttpPost httppost = new HttpPost(url);
        MultipartEntity reqEntity = new MultipartEntity();
        FileBody descriptionBin = new FileBody(description);
        reqEntity.addPart("description", descriptionBin);
        for (int i = 0; i < files.length; i++) {
            FileBody bin = new FileBody(files[i]);
            reqEntity.addPart("predictions", bin);
        }
        httppost.setEntity(reqEntity);
        HttpResponse response = httpclient.execute(httppost);
        HttpEntity resEntity = response.getEntity();
        if (response.getStatusLine().getStatusCode() < 200) {
            throw new Exception(response.getStatusLine().getReasonPhrase());
        }
        if (resEntity != null) {
            result = convertStreamToString(resEntity.getContent());
        }
        ErrorDocument errorDoc = null;
        try {
            errorDoc = ErrorDocument.Factory.parse(result);
        } catch (Exception e) {
            // no error XML should mean no error
        }
        if (errorDoc != null && errorDoc.validate()) {
            ErrorDocument.Error error = errorDoc.getError();
            String errorMessage = error.getCode() + " : " + error.getMessage();
            if (error.isSetAdditionalInformation()) {
                errorMessage += " : " + error.getAdditionalInformation();
            }
            throw new Exception(errorMessage);
        }
        EntityUtils.consume(resEntity);
    } finally {
        try {
            httpclient.getConnectionManager().shutdown();
        } catch (Exception ignore) {
            // ignore
        }
    }
    return result;
}

From source file:com.gs.tools.doc.extractor.core.util.HttpUtility.java

public static DefaultHttpClient getLoginHttpsClient(String userName, String password) {
    try {//ww  w  . j  a v a  2  s  .  c  om
        KeyStore trustStore = KeyStore.getInstance(KeyStore.getDefaultType());
        trustStore.load(null, null);

        SSLSocketFactory sf = new DefaultSecureSocketFactory(trustStore);
        sf.setHostnameVerifier(SSLSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER);

        HttpParams params = new BasicHttpParams();
        HttpProtocolParams.setVersion(params, HttpVersion.HTTP_1_1);
        HttpProtocolParams.setContentCharset(params, HTTP.UTF_8);
        HttpConnectionParams.setConnectionTimeout(params, 300000);
        HttpConnectionParams.setSocketBufferSize(params, 10485760);
        HttpConnectionParams.setSoTimeout(params, 300000);

        SchemeRegistry registry = new SchemeRegistry();
        registry.register(new Scheme("http", PlainSocketFactory.getSocketFactory(), 80));
        registry.register(new Scheme("https", sf, 443));

        ClientConnectionManager ccm = new ThreadSafeClientConnManager(params, registry);

        DefaultHttpClient httpClient = new DefaultHttpClient(ccm, params);
        httpClient.getCredentialsProvider().setCredentials(
                new AuthScope(AuthScope.ANY_HOST, AuthScope.ANY_PORT, AuthScope.ANY_REALM),
                new UsernamePasswordCredentials(userName, password));
        return httpClient;
    } catch (Exception e) {
        e.printStackTrace();
        return new DefaultHttpClient();
    }
}

From source file:be.uclouvain.multipathcontrol.stats.HttpUtils.java

public static HttpClient getHttpClient(int timeout) {
    if (ConfigServer.hostname.isEmpty())
        return null;

    DefaultHttpClient defaultHttpClient;
    if (timeout > 0)
        defaultHttpClient = new DefaultHttpClient(getParamTimeout(timeout));
    else/*from   w w w.  java 2 s.c o m*/
        defaultHttpClient = new DefaultHttpClient();
    if (ConfigServer.username != null && !ConfigServer.username.isEmpty()) {
        Credentials creds = new UsernamePasswordCredentials(ConfigServer.username, ConfigServer.password);
        AuthScope scope = new AuthScope(ConfigServer.hostname, ConfigServer.port);
        CredentialsProvider credProvider = defaultHttpClient.getCredentialsProvider();
        credProvider.setCredentials(scope, creds);
    }
    return defaultHttpClient;
}