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

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

Introduction

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

Prototype

String ANY_REALM

To view the source code for org.apache.http.auth AuthScope ANY_REALM.

Click Source Link

Document

The null value represents any realm.

Usage

From source file:org.opennms.opennms.pris.plugins.defaults.source.HttpRequisitionMergeSource.java

private Requisition getRequisition(String url, String userName, String password) {
    Requisition requisition = null;//from  w ww .ja v  a  2  s  . com

    if (url != null) {
        try {
            HttpClientBuilder builder = HttpClientBuilder.create();

            // If username and password was found, inject the credentials
            if (userName != null && password != null) {

                CredentialsProvider provider = new BasicCredentialsProvider();

                // Create the authentication scope
                AuthScope scope = new AuthScope(AuthScope.ANY_HOST, AuthScope.ANY_PORT, AuthScope.ANY_REALM);

                // Create credential pair
                UsernamePasswordCredentials credentials = new UsernamePasswordCredentials(userName, password);

                // Inject the credentials
                provider.setCredentials(scope, credentials);

                // Set the default credentials provider
                builder.setDefaultCredentialsProvider(provider);
            }

            HttpClient client = builder.build();
            HttpGet request = new HttpGet(url);
            HttpResponse response = client.execute(request);
            try {

                BufferedReader bufferedReader = new BufferedReader(
                        new InputStreamReader(response.getEntity().getContent()));
                JAXBContext jaxbContext = JAXBContext.newInstance(Requisition.class);

                Unmarshaller jaxbUnmarshaller = jaxbContext.createUnmarshaller();
                requisition = (Requisition) jaxbUnmarshaller.unmarshal(bufferedReader);

            } catch (JAXBException e) {
                LOGGER.error("The response did not contain a valid requisition as xml.", e);
            }
            LOGGER.debug("Got Requisition {}", requisition);
        } catch (IOException ex) {
            LOGGER.error("Requesting requisition from {} failed", url, ex);
            return null;
        }
    } else {
        LOGGER.error("Parameter requisition.url is missing in requisition.properties");
        return null;
    }
    return requisition;
}

From source file:org.kaaproject.kaa.server.common.admin.HttpComponentsRequestFactoryBasicAuth.java

/**
 * Set credentials to field <code>credsProvider</code>.
 *
 * @param username the username, part of credentials
 * @param password the password, part of credentials
 *//*w ww.  j  a  v a 2 s .  c  o  m*/
public void setCredentials(String username, String password) {
    credsProvider.setCredentials(new AuthScope(host.getHostName(), host.getPort(), AuthScope.ANY_REALM),
            new UsernamePasswordCredentials(username, password));
}

From source file:org.fcrepo.apix.registry.HttpClientFactory.java

/**
 * Construct a new HttpClient./*from w ww  .  jav a  2 s .  c om*/
 *
 * @return HttpClient impl.
 */
public CloseableHttpClient getClient() {
    final RequestConfig config = RequestConfig.custom().setConnectTimeout(connectTimeout)
            .setSocketTimeout(socketTimeout).build();

    final CredentialsProvider provider = new BasicCredentialsProvider();

    for (final AuthSpec authSpec : getAuthSpecs()) {
        LOG.debug("Using basic auth to {}://{}:{} with client", authSpec.scheme, authSpec.host, authSpec.port);
        final HttpHost host = new HttpHost(authSpec.host, authSpec.port, authSpec.scheme);

        provider.setCredentials(new AuthScope(host, AuthScope.ANY_REALM, authSpec.scheme),
                new UsernamePasswordCredentials(authSpec.username(), authSpec.passwd()));
    }

    return HttpClientBuilder.create().setDefaultRequestConfig(config)
            .addInterceptorLast(new HttpRequestInterceptor() {

                @Override
                public void process(final HttpRequest req, final HttpContext cxt)
                        throws HttpException, IOException {
                    if (!req.containsHeader(HttpHeaders.AUTHORIZATION)) {
                        final String[] hostInfo = req.getFirstHeader(HttpHeaders.HOST).getValue().split(":");
                        final Credentials creds = provider.getCredentials(new AuthScope(
                                new HttpHost(hostInfo[0],
                                        hostInfo.length > 1 ? Integer.valueOf(hostInfo[1]) : 80),
                                AuthScope.ANY_REALM, "http"));

                        if (creds != null) {
                            req.addHeader(HttpHeaders.AUTHORIZATION,
                                    "Basic " + Base64.getEncoder().encodeToString(
                                            String.format("%s:%s", creds.getUserPrincipal().getName(),
                                                    creds.getPassword()).getBytes()));
                            LOG.debug("Added auth header");
                        }
                    }
                }
            }).setDefaultCredentialsProvider(provider).build();
}

From source file:org.cvasilak.jboss.mobile.app.service.UploadToJBossServerService.java

@Override
protected void onHandleIntent(Intent intent) {
    // initialize

    // extract details
    Server server = intent.getParcelableExtra("server");
    String directory = intent.getStringExtra("directory");
    String filename = intent.getStringExtra("filename");

    // get the json parser from the application
    JsonParser jsonParser = new JsonParser();

    // start the ball rolling...
    final NotificationManager mgr = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);
    final NotificationCompat.Builder builder = new NotificationCompat.Builder(this);

    builder.setTicker(String.format(getString(R.string.notif_ticker), filename))
            .setLargeIcon(BitmapFactory.decodeResource(getResources(), R.drawable.ic_stat_notif_large))
            .setSmallIcon(R.drawable.ic_stat_notif_small)
            .setContentTitle(String.format(getString(R.string.notif_title), filename))
            .setContentText(getString(R.string.notif_content_init))
            // to avoid NPE on android 2.x where content intent is required
            // set an empty content intent
            .setContentIntent(PendingIntent.getActivity(this, 0, new Intent(), 0)).setOngoing(true);

    // notify user that upload is starting
    mgr.notify(NOTIFICATION_ID, builder.build());

    // reset ticker for any subsequent notifications
    builder.setTicker(null);//w w  w  .  jav a  2 s. c  om

    AbstractHttpClient client = CustomHTTPClient.getHttpClient();

    // enable digest authentication
    if (server.getUsername() != null && !server.getUsername().equals("")) {
        Credentials credentials = new UsernamePasswordCredentials(server.getUsername(), server.getPassword());

        client.getCredentialsProvider().setCredentials(
                new AuthScope(server.getHostname(), server.getPort(), AuthScope.ANY_REALM), credentials);
    }

    final File file = new File(directory, filename);
    final long length = file.length();

    try {
        CustomMultiPartEntity multipart = new CustomMultiPartEntity(HttpMultipartMode.BROWSER_COMPATIBLE,
                new CustomMultiPartEntity.ProgressListener() {
                    @Override
                    public void transferred(long num) {
                        // calculate percentage

                        //System.out.println("transferred: " + num);

                        int progress = (int) ((num * 100) / length);

                        builder.setContentText(String.format(getString(R.string.notif_content), progress));

                        mgr.notify(NOTIFICATION_ID, builder.build());
                    }
                });

        multipart.addPart(file.getName(), new FileBody(file));

        HttpPost httpRequest = new HttpPost(server.getHostPort() + "/management/add-content");
        httpRequest.setEntity(multipart);

        HttpResponse serverResponse = client.execute(httpRequest);

        BasicResponseHandler handler = new BasicResponseHandler();
        JsonObject reply = jsonParser.parse(handler.handleResponse(serverResponse)).getAsJsonObject();

        if (!reply.has("outcome")) {
            throw new RuntimeException(getString(R.string.invalid_response));
        } else {
            // remove the 'upload in-progress' notification
            mgr.cancel(NOTIFICATION_ID);

            String outcome = reply.get("outcome").getAsString();

            if (outcome.equals("success")) {

                String BYTES_VALUE = reply.get("result").getAsJsonObject().get("BYTES_VALUE").getAsString();

                Intent resultIntent = new Intent(this, UploadCompletedActivity.class);
                // populate it
                resultIntent.putExtra("server", server);
                resultIntent.putExtra("BYTES_VALUE", BYTES_VALUE);
                resultIntent.putExtra("filename", filename);
                resultIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TASK);

                // the notification id for the 'completed upload' notification
                // each completed upload will have a different id
                int notifCompletedID = (int) System.currentTimeMillis();

                builder.setContentTitle(getString(R.string.notif_title_uploaded))
                        .setContentText(String.format(getString(R.string.notif_content_uploaded), filename))
                        .setContentIntent(
                                // we set the (2nd param request code to completedID)
                                // see http://tinyurl.com/kkcedju
                                PendingIntent.getActivity(this, notifCompletedID, resultIntent,
                                        PendingIntent.FLAG_UPDATE_CURRENT))
                        .setAutoCancel(true).setOngoing(false);

                mgr.notify(notifCompletedID, builder.build());

            } else {
                JsonElement elem = reply.get("failure-description");

                if (elem.isJsonPrimitive()) {
                    throw new RuntimeException(elem.getAsString());
                } else if (elem.isJsonObject())
                    throw new RuntimeException(
                            elem.getAsJsonObject().get("domain-failure-description").getAsString());
            }
        }

    } catch (Exception e) {
        builder.setContentText(e.getMessage()).setAutoCancel(true).setOngoing(false);

        mgr.notify(NOTIFICATION_ID, builder.build());
    }
}

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

private static void setupUserPassAuthScheme(AuthScheme scheme, String httpScheme, AuthSchemeProvider provider,
        ConfigProvider configuration) {/*  w w w  .ja v  a2  s.c o m*/
    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:org.gradle.api.internal.artifacts.repositories.transport.http.HttpClientConfigurer.java

private void useCredentials(DefaultHttpClient httpClient, PasswordCredentials credentials, String host,
        int port) {
    Credentials basicCredentials = new UsernamePasswordCredentials(credentials.getUsername(),
            credentials.getPassword());// www  .  j a  v  a 2 s  .  c om
    httpClient.getCredentialsProvider().setCredentials(new AuthScope(host, port), basicCredentials);

    NTLMCredentials ntlmCredentials = new NTLMCredentials(credentials);
    Credentials ntCredentials = new NTCredentials(ntlmCredentials.getUsername(), ntlmCredentials.getPassword(),
            ntlmCredentials.getWorkstation(), ntlmCredentials.getDomain());
    httpClient.getCredentialsProvider()
            .setCredentials(new AuthScope(host, port, AuthScope.ANY_REALM, AuthPolicy.NTLM), ntCredentials);

    LOGGER.debug("Using {} and {} for authenticating against '{}:{}'",
            new Object[] { credentials, ntlmCredentials, host, port });
}

From source file:org.kaaproject.kaa.server.flume.sink.hdfs.AvroSchemaSource.java

private void initHttpRestClient() {
    httpClient = new DefaultHttpClient();
    restHost = new HttpHost(kaaRestHost, kaaRestPort, "http");

    AuthCache authCache = new BasicAuthCache();
    BasicScheme basicAuth = new BasicScheme();
    authCache.put(restHost, basicAuth);//  w w w  . ja  v  a2 s .c  o  m

    CredentialsProvider credsProvider = new BasicCredentialsProvider();
    credsProvider.setCredentials(new AuthScope(kaaRestHost, kaaRestPort, AuthScope.ANY_REALM),
            new UsernamePasswordCredentials(kaaRestUser, kaaRestPassword));

    httpContext = new BasicHttpContext();
    httpContext.setAttribute(ClientContext.AUTH_CACHE, authCache);
    httpContext.setAttribute(ClientContext.CREDS_PROVIDER, credsProvider);

}

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  ww  .ja  v  a2  s  . c o m

    }
    return context;
}

From source file:org.transdroid.daemon.util.HttpHelper.java

/**
 * Creates a standard Apache HttpClient that is thread safe, supports different SSL auth methods and basic
 * authentication/*from  www .ja  v a  2  s.  com*/
 * @param sslTrustAll Whether to trust all SSL certificates
 * @param sslTrustkey A specific SSL key to accept exclusively
 * @param timeout The connection timeout for all requests
 * @param authAddress The authentication domain address
 * @param authPort The authentication domain port number
 * @return An HttpClient that should be stored locally and reused for every new request
 * @throws DaemonException Thrown when information (such as username/password) is missing
 */
public static DefaultHttpClient createStandardHttpClient(boolean userBasicAuth, String username,
        String password, boolean sslTrustAll, String sslTrustkey, int timeout, String authAddress, int authPort)
        throws DaemonException {

    // Register http and https sockets
    SchemeRegistry registry = new SchemeRegistry();
    registry.register(new Scheme("http", new PlainSocketFactory(), 80));
    SocketFactory https_socket = sslTrustAll ? new FakeSocketFactory()
            : sslTrustkey != null ? new FakeSocketFactory(sslTrustkey) : SSLSocketFactory.getSocketFactory();
    registry.register(new Scheme("https", https_socket, 443));

    // Standard parameters
    HttpParams httpparams = new BasicHttpParams();
    HttpConnectionParams.setConnectionTimeout(httpparams, timeout);
    HttpConnectionParams.setSoTimeout(httpparams, timeout);
    if (userAgent != null) {
        HttpProtocolParams.setUserAgent(httpparams, userAgent);
    }

    DefaultHttpClient httpclient = new DefaultHttpClient(new ThreadSafeClientConnManager(httpparams, registry),
            httpparams);

    // Authentication credentials
    if (userBasicAuth) {
        if (username == null || password == null) {
            throw new DaemonException(ExceptionType.AuthenticationFailure,
                    "No username or password was provided while we hadauthentication enabled");
        }
        httpclient.getCredentialsProvider().setCredentials(
                new AuthScope(authAddress, authPort, AuthScope.ANY_REALM),
                new UsernamePasswordCredentials(username, password));
    }

    return httpclient;

}