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.qucosa.camel.component.fcrepo3.Fcrepo3APIAccess.java

public Fcrepo3APIAccess(String host, String port, String user, String password) {
    CredentialsProvider credentialsProvider = new BasicCredentialsProvider();
    credentialsProvider.setCredentials(AuthScope.ANY, new UsernamePasswordCredentials(user, password));

    this.host = host;
    this.port = port;

    httpClient = HttpClientBuilder.create().setConnectionManager(new PoolingHttpClientConnectionManager())
            .setDefaultCredentialsProvider(credentialsProvider).build();
}

From source file:pl.wavesoftware.wfirma.api.simple.mapper.SimpleGateway.java

private String get(@Nonnull HttpRequest httpRequest) throws WFirmaException {
    httpRequest.setHeader("Accept", "text/xml");
    HttpHost target = getTargetHost();/* www .  j  a v a2  s . c  om*/
    CredentialsProvider credsProvider = new BasicCredentialsProvider();
    credsProvider.setCredentials(new AuthScope(target.getHostName(), target.getPort()),
            new UsernamePasswordCredentials(credentials.getConsumerKey(), credentials.getConsumerSecret()));
    try (CloseableHttpClient httpclient = HttpClients.custom().setDefaultCredentialsProvider(credsProvider)
            .build()) {

        // Create AuthCache instance
        AuthCache authCache = new BasicAuthCache();
        // Generate BASIC scheme object and add it to the local
        // auth cache
        BasicScheme basicAuth = new BasicScheme();
        authCache.put(target, basicAuth);

        // Add AuthCache to the execution context
        HttpClientContext localContext = HttpClientContext.create();
        localContext.setAuthCache(authCache);

        try (CloseableHttpResponse response = httpclient.execute(target, httpRequest, localContext)) {
            return getContent(response);
        }
    } catch (IOException ioe) {
        throw new RemoteGatewayException(ioe);
    }
}

From source file:SubmitResults.java

public boolean sendFile(Main parent, String hostname, String instanceFilePath, String status, String user,
        String password, boolean encrypted, String newIdent) {

    boolean submit_status = false;
    File tempFile = null;// ww w. j  a va  2 s .  c  om

    // XSLT if ident needs to be changed
    final String changeIdXSLT = "<xsl:stylesheet version=\"1.0\" xmlns:xsl=\"http://www.w3.org/1999/XSL/Transform\">"
            + "<xsl:param name=\"surveyId\"/>" + "<xsl:template match=\"@*|node()\">" + "<xsl:copy>"
            + "<xsl:apply-templates select=\"@*|node()\"/>" + "</xsl:copy>" + "</xsl:template>"
            + "<xsl:template match=\"@id\">" + "<xsl:attribute name=\"id\">"
            + "<xsl:value-of select=\"$surveyId\"/>" + "</xsl:attribute>" + "</xsl:template>"
            + "</xsl:stylesheet>";

    //FileBody fb = null;
    ContentType ct = null;
    MultipartEntityBuilder entityBuilder = MultipartEntityBuilder.create();

    CredentialsProvider credsProvider = new BasicCredentialsProvider();
    String urlString = null;
    HttpHost targetHost = null;
    if (encrypted) {
        urlString = "https://" + hostname + "/submission";
        targetHost = new HttpHost(hostname, 443, "https");
        parent.appendToStatus("   Using https");
        //credsProvider.setCredentials(
        //        new AuthScope(hostname, 443, "smap", "digest"),
        //        new UsernamePasswordCredentials(user, password));
        credsProvider.setCredentials(new AuthScope(hostname, 443, "smap", "basic"),
                new UsernamePasswordCredentials(user, password));
    } else {
        urlString = "http://" + hostname + "/submission";
        targetHost = new HttpHost(hostname, 80, "http");
        parent.appendToStatus("   Using http (not encrypted)");
        credsProvider.setCredentials(new AuthScope(hostname, 80, "smap", "digest"),
                new UsernamePasswordCredentials(user, password));
    }

    CloseableHttpClient httpclient = HttpClients.custom().setDefaultCredentialsProvider(credsProvider).build();

    // get instance file
    File instanceFile = new File(instanceFilePath);

    if (!instanceFile.exists()) {
        parent.appendToStatus("   Error: Submission file " + instanceFilePath + " does not exist");
    } else {

        HttpPost req = new HttpPost(URI.create(urlString));
        //req.setHeader("form_status", status);                  // smap add form_status header

        tempFile = populateRequest(parent, status, instanceFilePath, req, changeIdXSLT, ct, entityBuilder,
                newIdent);

        // find all files in parent directory
        /*
        File[] allFiles = instanceFile.getParentFile().listFiles();
                
        // add media files ignoring invisible files and the submission file
        List<File> files = new ArrayList<File>();
        for (File f : allFiles) {
           String fileName = f.getName();
           if (!fileName.startsWith(".") && !fileName.equals(instanceFile.getName())) {   // ignore invisible files and instance xml file    
         files.add(f);
           }
        }
        */

        // add the submission file first...

        /*
        ct = ContentType.create("text/xml");
         //fb = new FileBody(instanceFile, ct);
         entity.addBinaryBody("xml_submission_file", instanceFile, ct, instanceFile.getPath());
         //entity.addPart("xml_submission_file", fb);
        */

        /*
        for (int j = 0; j < files.size(); j++) {
                  
                
            File f = files.get(j);
            String fileName = f.getName();
            int idx = fileName.lastIndexOf(".");
            String extension = "";
            if (idx != -1) {
           extension = fileName.substring(idx + 1);
            }
                
            // we will be processing every one of these, so
            // we only need to deal with the content type determination...
            if (extension.equals("xml")) {
          ct = ContentType.create("text/xml");
            } else if (extension.equals("jpg")) {
          ct = ContentType.create("image/jpeg");
            } else if (extension.equals("3gp")) {
          ct = ContentType.create("video/3gp");
            } else if (extension.equals("3ga")) {
          ct = ContentType.create("audio/3ga");
            } else if (extension.equals("mp4")) {
          ct = ContentType.create("video/mp4");
            } else if (extension.equals("m4a")) {
            ct = ContentType.create("audio/m4a");
            }else if (extension.equals("csv")) {
          ct = ContentType.create("text/csv");
            } else if (f.getName().endsWith(".amr")) {
          ct = ContentType.create("audio/amr");
            } else if (extension.equals("xls")) {
          ct = ContentType.create("application/vnd.ms-excel");
            }  else {
          ct = ContentType.create("application/octet-stream");
          parent.appendToStatus("   Info: unrecognised content type for extension " + extension);
                  
            }
                
            //fb = new FileBody(f, ct);
            //entity.addPart(f.getName(), fb);
            entity.addBinaryBody(f.getName(), f, ct, f.getName());
                 
           parent.appendToStatus("   Info: added file " + f.getName());
                
        }
        */

        //req.setEntity(entity.build());

        // prepare response and return uploaded
        HttpResponse response = null;
        try {

            // Create AuthCache instance
            AuthCache authCache = new BasicAuthCache();

            // Generate DIGEST scheme object, initialize it and add it to the local auth cache
            DigestScheme digestAuth = new DigestScheme();
            // Suppose we already know the realm name
            digestAuth.overrideParamter("realm", "smap");
            // Suppose we already know the expected nonce value
            digestAuth.overrideParamter("nonce", "whatever");
            authCache.put(targetHost, digestAuth);

            // Generate Basic scheme object
            BasicScheme basicAuth = new BasicScheme();
            authCache.put(targetHost, basicAuth);

            // Add AuthCache to the execution context
            HttpClientContext localContext = HttpClientContext.create();
            localContext.setAuthCache(authCache);

            parent.appendToStatus("   Info: submitting to: " + req.getURI().toString());
            response = httpclient.execute(targetHost, req, localContext);
            int responseCode = response.getStatusLine().getStatusCode();

            try {
                // have to read the stream in order to reuse the connection
                InputStream is = response.getEntity().getContent();
                // read to end of stream...
                final long count = 1024L;
                while (is.skip(count) == count)
                    ;
                is.close();
            } catch (IOException e) {
                e.printStackTrace();
            } catch (Exception e) {
                e.printStackTrace();
            }

            // verify that the response was a 201 or 202.
            // If it wasn't, the submission has failed.
            parent.appendToStatus("   Info: Response code: " + responseCode + " : "
                    + response.getStatusLine().getReasonPhrase());
            if (responseCode != HttpStatus.SC_CREATED && responseCode != HttpStatus.SC_ACCEPTED) {
                parent.appendToStatus("   Error: upload failed: ");
            } else {
                submit_status = true;
            }
        } catch (Exception e) {
            e.printStackTrace();
            parent.appendToStatus("   Error: Generic Exception. " + e.toString());
        }
    }

    try {
        httpclient.close();
    } catch (Exception e) {

    } finally {

    }

    if (tempFile != null) {
        tempFile.delete();
    }

    return submit_status;
}

From source file:eu.esdihumboldt.util.http.ProxyUtil.java

/**
 * Set-up the given HTTP client to use the given proxy
 * // w  w w .  j av a  2 s . c om
 * @param builder the HTTP client builder
 * @param proxy the proxy
 * @return the client builder adapted with the proxy settings
 */
public static HttpClientBuilder applyProxy(HttpClientBuilder builder, Proxy proxy) {
    init();

    // check if proxy shall be used
    if (proxy != null && proxy.type() == Type.HTTP) {
        InetSocketAddress proxyAddress = (InetSocketAddress) proxy.address();

        // set the proxy
        HttpHost proxyHost = new HttpHost(proxyAddress.getHostName(), proxyAddress.getPort());
        builder = builder.setProxy(proxyHost);

        String user = System.getProperty("http.proxyUser"); //$NON-NLS-1$
        String password = System.getProperty("http.proxyPassword"); //$NON-NLS-1$
        boolean useProxyAuth = user != null && !user.isEmpty();

        if (useProxyAuth) {
            // set the proxy credentials
            CredentialsProvider credsProvider = new BasicCredentialsProvider();
            credsProvider.setCredentials(new AuthScope(proxyAddress.getHostName(), proxyAddress.getPort()),
                    new UsernamePasswordCredentials(user, password));
            builder = builder.setDefaultCredentialsProvider(credsProvider)
                    .setProxyAuthenticationStrategy(new ProxyAuthenticationStrategy());
        }

        _log.trace("Set proxy to " + proxyAddress.getHostName() + ":" + //$NON-NLS-1$ //$NON-NLS-2$
                proxyAddress.getPort() + ((useProxyAuth) ? (" as user " + user) : (""))); //$NON-NLS-1$ //$NON-NLS-2$
    }

    return builder;
}

From source file:org.jbpm.workbench.wi.backend.server.casemgmt.service.CaseProvisioningExecutor.java

protected int getManagementInterfaceStatus(String host, String managementPort, String password,
        String username) {/*from ww w . j  a va 2  s . com*/
    final CredentialsProvider provider = new BasicCredentialsProvider();
    provider.setCredentials(new AuthScope(host, Integer.valueOf(managementPort)),
            new UsernamePasswordCredentials(username, password));

    try (CloseableHttpClient httpClient = HttpClients.custom().setDefaultCredentialsProvider(provider)
            .build()) {
        final HttpGet httpget = new HttpGet("http://" + host + ":" + managementPort + "/management");
        return httpClient.execute(httpget).getStatusLine().getStatusCode();
    } catch (Exception ex) {
        LOGGER.error("Exception while trying to connect to Wildfly Management interface", ex);
        return -1;
    }
}

From source file:com.ibm.watson.developer_cloud.retrieve_and_rank.RetrieveAndRankSolrJExample.java

private static HttpClient createHttpClient(String uri, String username, String password) {
    final URI scopeUri = URI.create(uri);

    final BasicCredentialsProvider credentialsProvider = new BasicCredentialsProvider();
    credentialsProvider.setCredentials(new AuthScope(scopeUri.getHost(), scopeUri.getPort()),
            new UsernamePasswordCredentials(username, password));

    final HttpClientBuilder builder = HttpClientBuilder.create().setMaxConnTotal(128).setMaxConnPerRoute(32)
            .setDefaultRequestConfig(//from  ww  w.  j av a  2 s.  co m
                    RequestConfig.copy(RequestConfig.DEFAULT).setRedirectsEnabled(true).build())
            .setDefaultCredentialsProvider(credentialsProvider)
            .addInterceptorFirst(new PreemptiveAuthInterceptor());
    return builder.build();
}

From source file:ru.neverdark.yotta.parser.YottaParser.java

private void parse(Array array) {
    final String URL = String.format("http://%s/hierarch.htm", array.getIp());
    final StringBuffer result = new StringBuffer();

    CredentialsProvider credsProvider = new BasicCredentialsProvider();
    credsProvider.setCredentials(new AuthScope(array.getIp(), 80),
            new UsernamePasswordCredentials(array.getUser(), array.getPassword()));
    CloseableHttpClient httpClient = HttpClients.custom().setDefaultCredentialsProvider(credsProvider).build();
    try {/* w  w w . j a v a2 s .  co m*/
        HttpGet httpget = new HttpGet(URL);
        CloseableHttpResponse response = httpClient.execute(httpget);
        System.err.printf("%s\t%s\n", array.getIp(), response.getStatusLine());
        try {
            BufferedReader rd = new BufferedReader(new InputStreamReader(response.getEntity().getContent()));

            String line = "";
            while ((line = rd.readLine()) != null) {
                result.append(line);
            }

            Document doc = Jsoup.parse(result.toString());
            Elements tables = doc.getElementsByAttribute("vspace");
            // skip first
            for (int i = 1; i < tables.size(); i++) {
                parseTable(tables.get(i), array.getType());
            }

        } finally {
            response.close();
        }

    } catch (ClientProtocolException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    } catch (IOException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    } finally {
        try {
            httpClient.close();
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
    }

}

From source file:org.jboss.as.test.integration.web.security.jaspi.WebSecurityJaspiTestCase.java

protected void makeCall(String user, String pass, int expectedStatusCode) throws Exception {
    CredentialsProvider credentialsProvider = new BasicCredentialsProvider();
    credentialsProvider.setCredentials(new AuthScope(url.getHost(), url.getPort()),
            new UsernamePasswordCredentials(user, pass));
    try (CloseableHttpClient httpclient = HttpClients.custom()
            .setDefaultCredentialsProvider(credentialsProvider).build()) {

        HttpGet httpget = new HttpGet(url.toExternalForm() + "secured/");

        HttpResponse response = httpclient.execute(httpget);
        HttpEntity entity = response.getEntity();

        StatusLine statusLine = response.getStatusLine();
        if (entity != null) {
            log.trace("Response content length: " + entity.getContentLength());
        }//w ww  .j  a  va  2  s  .com
        assertEquals(expectedStatusCode, statusLine.getStatusCode());
        EntityUtils.consume(entity);
    }
}

From source file:org.fuin.esc.eshttp.ESHttpEventStoreIT.java

@Before
public void setup() throws MalformedURLException {

    final ThreadFactory threadFactory = Executors.defaultThreadFactory();
    final URL url = new URL("http://127.0.0.1:2113/");
    final XmlDeSerializer xmlDeSer = new XmlDeSerializer(false, MyMeta.class, MyEvent.class, EscEvent.class,
            EscEvents.class, EscMeta.class);

    final SimpleSerializerDeserializerRegistry registry = new SimpleSerializerDeserializerRegistry();
    registry.add(new SerializedDataType(MyEvent.TYPE.asBaseType()), "application/xml", xmlDeSer);
    registry.add(new SerializedDataType(MyMeta.TYPE.asBaseType()), "application/xml", xmlDeSer);
    registry.add(new SerializedDataType(EscEvent.TYPE.asBaseType()), "application/xml", xmlDeSer);
    registry.add(new SerializedDataType(EscEvents.TYPE.asBaseType()), "application/xml", xmlDeSer);
    registry.add(new SerializedDataType(EscMeta.TYPE.asBaseType()), "application/xml", xmlDeSer);

    registry.add(new SerializedDataType(CUSTOMER_CREATED.asBaseType()), "application/xml", xmlDeSer);
    registry.add(new SerializedDataType(CUSTOMER_RENAMED.asBaseType()), "application/xml", xmlDeSer);

    final CredentialsProvider credentialsProvider = new BasicCredentialsProvider();
    final UsernamePasswordCredentials credentials = new UsernamePasswordCredentials("admin", "changeit");
    credentialsProvider.setCredentials(AuthScope.ANY, credentials);

    testee = new ESHttpEventStore(threadFactory, url, ESEnvelopeType.XML, registry, registry,
            credentialsProvider);//ww  w  . jav  a2  s  .c o m
    testee.open();

}