Example usage for org.apache.http.client AuthCache put

List of usage examples for org.apache.http.client AuthCache put

Introduction

In this page you can find the example usage for org.apache.http.client AuthCache put.

Prototype

void put(HttpHost host, AuthScheme authScheme);

Source Link

Usage

From source file:com.cloudbees.jenkins.plugins.bitbucket.client.BitbucketCloudApiClient.java

private void setClientProxyParams(String host, HttpClientBuilder builder) {
    Jenkins jenkins = Jenkins.getInstance();
    ProxyConfiguration proxyConfig = null;
    if (jenkins != null) {
        proxyConfig = jenkins.proxy;//from w  w  w  .j ava  2  s. com
    }

    Proxy proxy = Proxy.NO_PROXY;
    if (proxyConfig != null) {
        proxy = proxyConfig.createProxy(host);
    }

    if (proxy.type() != Proxy.Type.DIRECT) {
        final InetSocketAddress proxyAddress = (InetSocketAddress) proxy.address();
        LOGGER.fine("Jenkins proxy: " + proxy.address());
        builder.setProxy(new HttpHost(proxyAddress.getHostName(), proxyAddress.getPort()));
        String username = proxyConfig.getUserName();
        String password = proxyConfig.getPassword();
        if (username != null && !"".equals(username.trim())) {
            LOGGER.fine("Using proxy authentication (user=" + username + ")");
            CredentialsProvider credentialsProvider = new BasicCredentialsProvider();
            credentialsProvider.setCredentials(AuthScope.ANY,
                    new UsernamePasswordCredentials(username, password));
            AuthCache authCache = new BasicAuthCache();
            authCache.put(HttpHost.create(proxyAddress.getHostName()), new BasicScheme());
            context = HttpClientContext.create();
            context.setCredentialsProvider(credentialsProvider);
            context.setAuthCache(authCache);
        }
    }
}

From source file:com.sat.vcse.automation.utils.http.HttpClient.java

/**
 * Creates HttpClientContext required for basic authentication
 * @return//from w w w  . j  av a2s.c  o m
 */
private HttpClientContext getAuthContext() {

    //Create target host based on targetURL
    HttpHost targetHost = getTargetHost(this.targetURL);

    CredentialsProvider credsProvider = new BasicCredentialsProvider();
    credsProvider.setCredentials(new AuthScope(targetHost),
            new UsernamePasswordCredentials(this.basicAuthId, this.basicAuthPwd));

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

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

    return context;
}

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;/*from w w w .  j ava 2s .  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:com.cloudbees.jenkins.plugins.bitbucket.server.client.BitbucketServerAPIClient.java

private void setClientProxyParams(String host, HttpClientBuilder builder) {
    Jenkins jenkins = Jenkins.getInstance();
    ProxyConfiguration proxyConfig = null;
    if (jenkins != null) {
        proxyConfig = jenkins.proxy;// www . j av a  2s  .co m
    }

    final Proxy proxy;

    if (proxyConfig != null) {
        URI hostURI = URI.create(host);
        proxy = proxyConfig.createProxy(hostURI.getHost());
    } else {
        proxy = Proxy.NO_PROXY;
    }

    if (proxy.type() != Proxy.Type.DIRECT) {
        final InetSocketAddress proxyAddress = (InetSocketAddress) proxy.address();
        LOGGER.log(Level.FINE, "Jenkins proxy: {0}", proxy.address());
        builder.setProxy(new HttpHost(proxyAddress.getHostName(), proxyAddress.getPort()));
        String username = proxyConfig.getUserName();
        String password = proxyConfig.getPassword();
        if (username != null && !"".equals(username.trim())) {
            LOGGER.fine("Using proxy authentication (user=" + username + ")");
            CredentialsProvider credentialsProvider = new BasicCredentialsProvider();
            credentialsProvider.setCredentials(AuthScope.ANY,
                    new UsernamePasswordCredentials(username, password));
            AuthCache authCache = new BasicAuthCache();
            authCache.put(HttpHost.create(proxyAddress.getHostName()), new BasicScheme());
            context = HttpClientContext.create();
            context.setCredentialsProvider(credentialsProvider);
            context.setAuthCache(authCache);
        }
    }
}