Example usage for org.apache.http.auth AuthScope AuthScope

List of usage examples for org.apache.http.auth AuthScope AuthScope

Introduction

In this page you can find the example usage for org.apache.http.auth AuthScope AuthScope.

Prototype

public AuthScope(final String host, final int port, final String realm, final String scheme) 

Source Link

Document

Creates a new credentials scope for the given host, port, realm, and authentication scheme.

Usage

From source file:net.oauth.client.httpclient4.PreemptiveAuthorizer.java

/**
 * If no auth scheme has been selected for the given context, consider each
 * of the preferred auth schemes and select the first one for which an
 * AuthScheme and matching Credentials are available.
 *//*from  w w  w .  ja v  a  2  s. co  m*/
public void process(HttpRequest request, HttpContext context) throws HttpException, IOException {
    AuthState authState = (AuthState) context.getAttribute(ClientContext.TARGET_AUTH_STATE);
    if (authState != null && authState.getAuthScheme() != null) {
        return;
    }
    HttpHost target = (HttpHost) context.getAttribute(ExecutionContext.HTTP_TARGET_HOST);
    CredentialsProvider creds = (CredentialsProvider) context.getAttribute(ClientContext.CREDS_PROVIDER);
    AuthSchemeRegistry schemes = (AuthSchemeRegistry) context.getAttribute(ClientContext.AUTHSCHEME_REGISTRY);
    for (Object schemeName : (Iterable) context.getAttribute(ClientContext.AUTH_SCHEME_PREF)) {
        AuthScheme scheme = schemes.getAuthScheme(schemeName.toString(), request.getParams());
        if (scheme != null) {
            AuthScope targetScope = new AuthScope(target.getHostName(), target.getPort(), scheme.getRealm(),
                    scheme.getSchemeName());
            Credentials cred = creds.getCredentials(targetScope);
            if (cred != null) {
                authState.setAuthScheme(scheme);
                authState.setCredentials(cred);
                return;
            }
        }
    }
}

From source file:org.opentravel.schemacompiler.repository.impl.NTLMSystemCredentialsProviderTest.java

private AuthScope createAuthScope(String schema) {
    AuthScope scope = new AuthScope("dummyHost", 80, null, schema);
    return scope;
}

From source file:com.datatorrent.stram.util.WebServicesClient.java

private static void setupUserPassAuthScheme(AuthScheme scheme, String httpScheme, AuthSchemeProvider provider,
        ConfigProvider configuration) {/* w w w  .j  a v a  2s.com*/
    String username = configuration.getProperty(scheme, "username");
    String password = configuration.getProperty(scheme, "password");
    if ((username != null) && (password != null)) {
        LOG.info("Setting up scheme {}", scheme);
        AuthScope authScope = new AuthScope(AuthScope.ANY_HOST, AuthScope.ANY_PORT, AuthScope.ANY_REALM,
                httpScheme);
        Credentials credentials = new UsernamePasswordCredentials(username, password);
        setupHttpAuthScheme(httpScheme, provider, authScope, credentials);
    } else if ((username != null) || (password != null)) {
        LOG.warn("Not setting up scheme {}, missing credentials {}", scheme,
                (username == null) ? "username" : "password");
    }
}

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  a va 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.mpower.daktar.android.utilities.WebUtils.java

public static final AuthScope buildAuthScopes(final String host) {

    AuthScope a;//  ww  w.j  a  v  a2s .c  om
    // allow digest auth on any port...
    a = new AuthScope(host, -1, null, AuthPolicy.DIGEST);

    return a;
}

From source file:org.jboss.as.test.integration.management.interfaces.HttpManagementInterface.java

private static HttpClient createHttpClient(String host, int port, String username, String password) {
    PoolingClientConnectionManager connectionPool = new PoolingClientConnectionManager();
    DefaultHttpClient httpClient = new DefaultHttpClient(connectionPool);
    SchemeRegistry schemeRegistry = httpClient.getConnectionManager().getSchemeRegistry();
    schemeRegistry.register(new Scheme("http", 80, PlainSocketFactory.getSocketFactory()));
    try {/*from www . j  av a  2 s . c o  m*/
        schemeRegistry.register(new Scheme("https", 443, new SSLSocketFactory(new TrustStrategy() {
            @Override
            public boolean isTrusted(X509Certificate[] chain, String authType) throws CertificateException {
                return true;
            }
        }, new AllowAllHostnameVerifier())));
    } catch (Exception e) {
        throw new RuntimeException(e);
    }
    httpClient.setHttpRequestRetryHandler(new StandardHttpRequestRetryHandler(5, true));
    httpClient.getCredentialsProvider().setCredentials(
            new AuthScope(host, port, MANAGEMENT_REALM, AuthPolicy.DIGEST),
            new UsernamePasswordCredentials(username, password));

    return httpClient;
}

From source file:mobi.jenkinsci.server.core.net.PooledHttpClientFactory.java

private CredentialsProvider getCredentialsProvider(final URL url, final String user, final String password) {
    CredentialsProvider provider = new BasicCredentialsProvider();
    provider.setCredentials(new AuthScope(url.getHost(), url.getPort(), AuthScope.ANY_REALM, "BASIC"),
            new UsernamePasswordCredentials(user, password));
    return provider;
}

From source file:majordodo.client.http.HTTPClientConnection.java

private HttpClientContext getContext() throws IOException {
    if (context == null) {
        BrokerAddress broker = getBroker();
        String scheme = broker.getProtocol();
        HttpHost targetHost = new HttpHost(broker.getAddress(), broker.getPort(), scheme);

        context = HttpClientContext.create();
        if (configuration.getUsername() != null && !configuration.getUsername().isEmpty()) {
            UsernamePasswordCredentials creds = new UsernamePasswordCredentials(configuration.getUsername(),
                    configuration.getPassword());
            CredentialsProvider credsProvider = new BasicCredentialsProvider();
            credsProvider.setCredentials(new AuthScope(targetHost.getHostName(), targetHost.getPort(),
                    AuthScope.ANY_REALM, AuthScope.ANY_SCHEME), creds);
            BasicAuthCache authCache = new BasicAuthCache();
            BasicScheme basicAuth = new BasicScheme();
            authCache.put(targetHost, basicAuth);
            context.setCredentialsProvider(credsProvider);
            context.setAuthCache(authCache);
        }//from  w  w  w .j a  va 2  s  .  c om

    }
    return context;
}