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

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

Introduction

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

Prototype

AuthScope ANY

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

Click Source Link

Document

Default scope matching any host, port, realm and authentication scheme.

Usage

From source file:com.pari.ic.ICManager.java

private String retriveICPackageFile(ICStorageServerSettings settings, ICPackage pkg, PollJobDetails details)
        throws Exception {
    String log = null;/*from w ww  .j  a v  a  2 s.c o m*/
    InputStream inStream = null;
    HttpClient httpclient = null;

    Customer customer = CustomerManager.getInstance().getCustomerById(pkg.getCustomerId());
    String customerName = customer.getCustomerName();

    if (settings.getConnectivityType() == ConnectivityTypeEnum.CONNECTIVITY) {
        // DefaultHttpClient httpclient = null;
        // For Standalone NCCM, send the request via Connectivity
        String tegHost = settings.getTegHost();
        if (tegHost == null) {
            log = "TEG URL is not configured.... ";
            logMsg(details, log, JobStageConstants.PollingStages.RUNNING, Priority.INFO_INT, null);
            return null;
        }

        String tegUrl = "http://" + tegHost + "/NccmCollector/ICDownloadServlet?";

        log = "URL to TEG : " + tegUrl;
        logMsg(details, log, JobStageConstants.PollingStages.RUNNING, Priority.INFO_INT, null);

        // Sample URL -
        // http://172.21.136.202:8090/NccmCollector/ICDownloadServlet?GET_IC_PACK=TRUE&PACK_ID=1234

        tegUrl = tegUrl + "GET_IC_PACK=TRUE";
        tegUrl = tegUrl + "&";
        tegUrl = tegUrl + "PACK_ID" + "=" + pkg.getPackageId();

        String request = new URL(getFullUrl(settings.getServerHost()) + "/NetworkManagerWS/getFile/forPackage/"
                + pkg.getPackageId() + "/" + pkg.getPackageVersion() + "/" + customerName + "/"
                + pkg.getInstance_name()).toString();

        request = request + "&&&";
        request = request + settings.getUserId();
        request = request + "&&&";
        request = request + settings.getPassword();

        log = "Request URL package download : " + request;
        logMsg(details, log, JobStageConstants.PollingStages.RUNNING, Priority.INFO_INT, null);

        try {
            httpclient = new DefaultHttpClient();
            httpclient.getParams().setParameter(CoreProtocolPNames.PROTOCOL_VERSION, HttpVersion.HTTP_1_1);
            tegUrl = tegUrl.replaceAll(" ", "%20");
            log = "Posting request to url: " + tegUrl;
            logMsg(details, log, JobStageConstants.PollingStages.RUNNING, Priority.INFO_INT, null);
            HttpPost httppost = new HttpPost(tegUrl);
            httppost.setEntity(new StringEntity(request, null, null));
            httppost.setHeader("Content-type", "text/xml");

            HttpResponse response = httpclient.execute(httppost);
            log = "Response from HTTP Client in retriveICPackageFile : " + response.toString();
            logMsg(details, log, JobStageConstants.PollingStages.RUNNING, Priority.INFO_INT, null);

            inStream = response.getEntity().getContent();
        } catch (Exception e) {
            log = "Error while posting request to TEG... ";
            logMsg(details, log, JobStageConstants.PollingStages.RUNNING, Priority.ERROR_INT, e);
        }
    } else {
        try {
            httpclient = new DefaultHttpClient();
            this.pasHttpRequestHandler.getSecuredHttpClient(httpclient);
            HttpGet request = new HttpGet(getFullUrl(settings.getServerHost())
                    + "/NetworkManagerWS/getFile/forPackage/" + pkg.getPackageId() + "/"
                    + pkg.getPackageVersion() + "/" + customerName + "/" + pkg.getInstance_name());
            ((AbstractHttpClient) httpclient).getCredentialsProvider().setCredentials(AuthScope.ANY,
                    new UsernamePasswordCredentials(settings.getUserId(), settings.getPassword()));
            HttpResponse response = httpclient.execute(request);
            inStream = response.getEntity().getContent();
        } catch (Exception e) {
            log = "Error while posting request to retrieve package... ";
            logMsg(details, log, JobStageConstants.PollingStages.RUNNING, Priority.ERROR_INT, e);
        }
    }

    try {
        if (inStream != null) {
            ReadableByteChannel rbc = Channels.newChannel(inStream);
            String filePath = ICF_UPLOAD_FOLDER + File.separatorChar + pkg.getPackageId();

            File file = new File(filePath);
            if (!file.getParentFile().exists()) {
                // ensure parent folder exists
                file.getParentFile().mkdir();
            }

            if (file.exists()) {
                file.delete();
            }
            FileOutputStream fos = null;
            try {
                fos = new FileOutputStream(file);
                fos.getChannel().transferFrom(rbc, 0, 1 << 24);
            } finally {
                try {
                    if (fos != null) {
                        fos.close();
                    }
                } catch (Exception ignore) {
                    log = "Error while closing FileOutputStream : ";
                    logMsg(details, log, JobStageConstants.PollingStages.RUNNING, Priority.ERROR_INT, ignore);
                }

                try {
                    inStream.close();
                } catch (Exception ignore) {
                    log = "Error while closing inStream : ";
                    logMsg(details, log, JobStageConstants.PollingStages.RUNNING, Priority.ERROR_INT, ignore);
                }
            }
            return filePath;
        }
    } finally {
        if (httpclient != null) {
            httpclient.getConnectionManager().shutdown();
        }
    }
    return null;
}

From source file:org.hyperledger.fabric_ca.sdk.HFCAClient.java

/**
 * Http Post Request./*from   ww w. j  a va2s. com*/
 *
 * @param url         Target URL to POST to.
 * @param body        Body to be sent with the post.
 * @param credentials Credentials to use for basic auth.
 * @return Body of post returned.
 * @throws Exception
 */
String httpPost(String url, String body, UsernamePasswordCredentials credentials) throws Exception {
    logger.debug(format("httpPost %s, body:%s", url, body));

    final HttpClientBuilder httpClientBuilder = HttpClientBuilder.create();
    CredentialsProvider provider = null;
    if (credentials != null) {
        provider = new BasicCredentialsProvider();

        provider.setCredentials(AuthScope.ANY, credentials);
        httpClientBuilder.setDefaultCredentialsProvider(provider);
    }

    if (registry != null) {

        httpClientBuilder.setConnectionManager(new PoolingHttpClientConnectionManager(registry));

    }

    HttpClient client = httpClientBuilder.build();

    HttpPost httpPost = new HttpPost(url);
    httpPost.setConfig(getRequestConfig());

    AuthCache authCache = new BasicAuthCache();

    HttpHost targetHost = new HttpHost(httpPost.getURI().getHost(), httpPost.getURI().getPort());

    if (credentials != null) {
        authCache.put(targetHost, new

        BasicScheme());

    }

    final HttpClientContext context = HttpClientContext.create();

    if (null != provider) {
        context.setCredentialsProvider(provider);
    }

    if (credentials != null) {
        context.setAuthCache(authCache);
    }

    httpPost.setEntity(new StringEntity(body));
    if (credentials != null) {
        httpPost.addHeader(new

        BasicScheme().

                authenticate(credentials, httpPost, context));
    }

    HttpResponse response = client.execute(httpPost, context);
    int status = response.getStatusLine().getStatusCode();

    HttpEntity entity = response.getEntity();
    logger.trace(format("httpPost %s  sending...", url));
    String responseBody = entity != null ? EntityUtils.toString(entity) : null;
    logger.trace(format("httpPost %s  responseBody %s", url, responseBody));

    if (status >= 400) {

        Exception e = new Exception(format(
                "POST request to %s  with request body: %s, " + "failed with status code: %d. Response: %s",
                url, body, status, responseBody));
        logger.error(e.getMessage());
        throw e;
    }
    logger.debug(format("httpPost Status: %d returning: %s ", status, responseBody));

    return responseBody;
}

From source file:com.enioka.jqm.api.HibernateClient.java

private InputStream getFile(String url) {
    EntityManager em = getEm();/* www  . j a  v a 2  s.  co m*/
    File file = null;
    FileOutputStream fos = null;
    CloseableHttpClient cl = null;
    CloseableHttpResponse rs = null;
    String nameHint = null;

    File destDir = new File(System.getProperty("java.io.tmpdir"));
    if (!destDir.isDirectory() && !destDir.mkdir()) {
        throw new JqmClientException("could not create temp directory " + destDir.getAbsolutePath());
    }
    jqmlogger.trace("File will be copied into " + destDir);

    try {
        file = new File(destDir + "/" + UUID.randomUUID().toString());

        CredentialsProvider credsProvider = null;
        if (SimpleApiSecurity.getId(em).usr != null) {
            credsProvider = new BasicCredentialsProvider();
            credsProvider.setCredentials(AuthScope.ANY, new UsernamePasswordCredentials(
                    SimpleApiSecurity.getId(em).usr, SimpleApiSecurity.getId(em).pass));
        }
        SSLContext ctx = null;
        if (getFileProtocol(em).equals("https://")) {
            try {
                if (p.containsKey("com.enioka.jqm.ws.truststoreFile")) {
                    KeyStore trust = null;
                    InputStream trustIs = null;

                    try {
                        trust = KeyStore
                                .getInstance(this.p.getProperty("com.enioka.jqm.ws.truststoreType", "JKS"));
                    } catch (KeyStoreException e) {
                        throw new JqmInvalidRequestException("Specified trust store type ["
                                + this.p.getProperty("com.enioka.jqm.ws.truststoreType", "JKS")
                                + "] is invalid", e);
                    }

                    try {
                        trustIs = new FileInputStream(this.p.getProperty("com.enioka.jqm.ws.truststoreFile"));
                    } catch (FileNotFoundException e) {
                        throw new JqmInvalidRequestException("Trust store file ["
                                + this.p.getProperty("com.enioka.jqm.ws.truststoreFile") + "] cannot be found",
                                e);
                    }

                    String trustp = this.p.getProperty("com.enioka.jqm.ws.truststorePass", null);
                    try {
                        trust.load(trustIs, (trustp == null ? null : trustp.toCharArray()));
                    } catch (Exception e) {
                        throw new JqmInvalidRequestException("Could not load the trust store file", e);
                    } finally {
                        try {
                            trustIs.close();
                        } catch (IOException e) {
                            // Nothing to do.
                        }
                    }
                    ctx = SSLContexts.custom().loadTrustMaterial(trust).build();
                } else {
                    ctx = SSLContexts.createSystemDefault();
                }
            } catch (Exception e) {
                // Cannot happen - not trust store is actually loaded!
                jqmlogger.error(
                        "An supposedly impossible error has happened. Downloading files through the API may not work.",
                        e);
            }
        }
        cl = HttpClients.custom().setDefaultCredentialsProvider(credsProvider).setSslcontext(ctx).build();

        // Run HTTP request
        HttpUriRequest rq = new HttpGet(url.toString());
        rs = cl.execute(rq);
        if (rs.getStatusLine().getStatusCode() != HttpStatus.SC_OK) {
            throw new JqmClientException(
                    "Could not retrieve file from JQM node. The file may have been purged, or the node may be unreachable. HTTP code was: "
                            + rs.getStatusLine().getStatusCode());
        }

        // There may be a filename hint inside the response
        Header[] hs = rs.getHeaders("Content-Disposition");
        if (hs.length == 1) {
            Header h = hs[0];
            if (h.getValue().contains("filename=")) {
                nameHint = h.getValue().split("=")[1];
            }
        }

        // Save the file to a temp local file
        fos = new FileOutputStream(file);
        rs.getEntity().writeTo(fos);
        jqmlogger.trace("File was downloaded to " + file.getAbsolutePath());
    } catch (IOException e) {
        throw new JqmClientException(
                "Could not create a webserver-local copy of the file. The remote node may be down.", e);
    } finally {
        closeQuietly(em);
        closeQuietly(fos);
        closeQuietly(rs);
        closeQuietly(cl);
    }

    SelfDestructFileStream res = null;
    try {
        res = new SelfDestructFileStream(file);
    } catch (IOException e) {
        throw new JqmClientException("File seems not to be present where it should have been downloaded", e);
    }
    res.nameHint = nameHint;
    return res;
}

From source file:org.apache.maven.plugin.javadoc.JavadocUtil.java

/**
 * Creates a new {@code HttpClient} instance.
 *
 * @param settings The settings to use for setting up the client or {@code null}.
 * @param url The {@code URL} to use for setting up the client or {@code null}.
 *
 * @return A new {@code HttpClient} instance.
 *
 * @see #DEFAULT_TIMEOUT//from  w w w.  ja va  2 s  . c o  m
 * @since 2.8
 */
private static HttpClient createHttpClient(Settings settings, URL url) {
    DefaultHttpClient httpClient = new DefaultHttpClient(new PoolingClientConnectionManager());
    httpClient.getParams().setIntParameter(CoreConnectionPNames.SO_TIMEOUT, DEFAULT_TIMEOUT);
    httpClient.getParams().setIntParameter(CoreConnectionPNames.CONNECTION_TIMEOUT, DEFAULT_TIMEOUT);
    httpClient.getParams().setBooleanParameter(ClientPNames.ALLOW_CIRCULAR_REDIRECTS, true);

    // Some web servers don't allow the default user-agent sent by httpClient
    httpClient.getParams().setParameter(CoreProtocolPNames.USER_AGENT,
            "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.0)");

    if (settings != null && settings.getActiveProxy() != null) {
        Proxy activeProxy = settings.getActiveProxy();

        ProxyInfo proxyInfo = new ProxyInfo();
        proxyInfo.setNonProxyHosts(activeProxy.getNonProxyHosts());

        if (StringUtils.isNotEmpty(activeProxy.getHost())
                && (url == null || !ProxyUtils.validateNonProxyHosts(proxyInfo, url.getHost()))) {
            HttpHost proxy = new HttpHost(activeProxy.getHost(), activeProxy.getPort());
            httpClient.getParams().setParameter(ConnRoutePNames.DEFAULT_PROXY, proxy);

            if (StringUtils.isNotEmpty(activeProxy.getUsername()) && activeProxy.getPassword() != null) {
                Credentials credentials = new UsernamePasswordCredentials(activeProxy.getUsername(),
                        activeProxy.getPassword());

                httpClient.getCredentialsProvider().setCredentials(AuthScope.ANY, credentials);
            }
        }
    }

    return httpClient;
}

From source file:ddf.test.itests.platform.TestSecurity.java

private CredentialsProvider createBasicAuth(String username, String password) {
    CredentialsProvider credentialsProvider = new BasicCredentialsProvider();
    UsernamePasswordCredentials usernamePasswordCredentials = new UsernamePasswordCredentials(username,
            password);//  w ww  .j a  v a 2  s  . co  m
    credentialsProvider.setCredentials(AuthScope.ANY, usernamePasswordCredentials);
    return credentialsProvider;
}

From source file:org.talend.mdm.webapp.browserecords.server.actions.BrowseRecordsAction.java

@Override
public String bulkUpdateItem(String baseUrl, String concept, String xml, String language)
        throws ServiceException {
    try {/*w w w. ja v  a2 s . c o m*/
        String url = baseUrl + "services/rest/data/" + getCurrentDataCluster() + "/" + concept + "/bulk";
        DefaultHttpClient httpClient = new DefaultHttpClient();
        httpClient.getCredentialsProvider().setCredentials(AuthScope.ANY, new UsernamePasswordCredentials(
                LocalUser.getLocalUser().getUsername(), LocalUser.getLocalUser().getPassword()));
        HttpPatch httpPatch = new HttpPatch(url);
        httpPatch.setHeader("Content-Type", "text/xml; charset=utf8"); //$NON-NLS-1$ //$NON-NLS-2$
        HttpEntity entity = new StringEntity(xml);
        httpPatch.setEntity(entity);
        HttpResponse response = httpClient.execute(httpPatch);
        return readRestErroMessage(response);
    } catch (Exception e) {
        return e.getCause().getLocalizedMessage();
    }
}

From source file:no.kantega.publishing.modules.linkcheck.check.LinkCheckerJob.java

private void init() {
    if (isNotBlank(proxyHost)) {
        HttpHost proxy = new HttpHost(proxyHost, proxyPort);

        httpClientBuilder = HttpClients.custom()
                .setDefaultRequestConfig(RequestConfig.custom().setRedirectsEnabled(true)
                        .setConnectTimeout(CONNECTION_TIMEOUT).setConnectionRequestTimeout(CONNECTION_TIMEOUT)
                        .setSocketTimeout(CONNECTION_TIMEOUT).build())
                .setProxy(proxy);/* w w w.  java 2s. c o  m*/

        if (isNotBlank(proxyUser)) {
            CredentialsProvider credsProvider = new BasicCredentialsProvider();
            credsProvider.setCredentials(AuthScope.ANY,
                    new UsernamePasswordCredentials(proxyUser, proxyPassword));
            httpClientBuilder.setDefaultCredentialsProvider(credsProvider);
        }
    } else {
        httpClientBuilder = HttpClients.custom()
                .setDefaultRequestConfig(RequestConfig.custom().setRedirectsEnabled(true)
                        .setConnectionRequestTimeout(CONNECTION_TIMEOUT).setConnectTimeout(CONNECTION_TIMEOUT)
                        .setSocketTimeout(CONNECTION_TIMEOUT).build());
    }
}

From source file:org.alfresco.dataprep.AlfrescoHttpClient.java

/**
 * Get basic http client with basic credential.
 * @param username String username //  www .j a v  a 2  s .c om
 * @param password String password
 * @return {@link CloseableHttpClient} client
 */
public CloseableHttpClient getHttpClientWithBasicAuth(String username, String password) {
    CredentialsProvider provider = new BasicCredentialsProvider();
    UsernamePasswordCredentials credentials = new UsernamePasswordCredentials(username, password);
    provider.setCredentials(AuthScope.ANY, credentials);
    CloseableHttpClient client = HttpClientBuilder.create().setDefaultCredentialsProvider(provider).build();
    return client;
}

From source file:org.apache.hadoop.hbase.rest.TestSecureRESTServer.java

private Pair<CloseableHttpClient, HttpClientContext> getClient() {
    HttpClientConnectionManager pool = new PoolingHttpClientConnectionManager();
    HttpHost host = new HttpHost("localhost", REST_TEST.getServletPort());
    Registry<AuthSchemeProvider> authRegistry = RegistryBuilder.<AuthSchemeProvider>create()
            .register(AuthSchemes.SPNEGO, new SPNegoSchemeFactory(true, true)).build();
    CredentialsProvider credentialsProvider = new BasicCredentialsProvider();
    credentialsProvider.setCredentials(AuthScope.ANY, EmptyCredentials.INSTANCE);
    AuthCache authCache = new BasicAuthCache();

    CloseableHttpClient client = HttpClients.custom().setDefaultAuthSchemeRegistry(authRegistry)
            .setConnectionManager(pool).build();

    HttpClientContext context = HttpClientContext.create();
    context.setTargetHost(host);// ww  w .  j  a  va2 s .c o  m
    context.setCredentialsProvider(credentialsProvider);
    context.setAuthSchemeRegistry(authRegistry);
    context.setAuthCache(authCache);

    return new Pair<>(client, context);
}

From source file:org.apache.kylin.common.restclient.RestClient.java

private void init(String host, int port, String userName, String password) {
    this.host = host;
    this.port = port;
    this.userName = userName;
    this.password = password;
    this.baseUrl = SCHEME_HTTP + host + ":" + port + KYLIN_API_PATH;

    final HttpParams httpParams = new BasicHttpParams();
    HttpConnectionParams.setSoTimeout(httpParams, HTTP_SOCKET_TIMEOUT_MS);
    HttpConnectionParams.setConnectionTimeout(httpParams, HTTP_CONNECTION_TIMEOUT_MS);

    client = new DefaultHttpClient(httpParams);

    if (userName != null && password != null) {
        CredentialsProvider provider = new BasicCredentialsProvider();
        UsernamePasswordCredentials credentials = new UsernamePasswordCredentials(userName, password);
        provider.setCredentials(AuthScope.ANY, credentials);
        client.setCredentialsProvider(provider);
    }//from  w  ww .j a va 2  s  . c o m
}