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:org.hyperledger.fabric.sdk.MemberServicesFabricCAImpl.java

/**
 * Http Post Request./* w w w.  ja  v  a  2  s.c  o  m*/
 * @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
 */

private static String httpPost(String url, String body, UsernamePasswordCredentials credentials)
        throws Exception {
    CredentialsProvider provider = new BasicCredentialsProvider();

    provider.setCredentials(AuthScope.ANY, credentials);

    HttpClient client = HttpClientBuilder.create().setDefaultCredentialsProvider(provider).build();

    HttpPost httpPost = new HttpPost(url);

    AuthCache authCache = new BasicAuthCache();

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

    authCache.put(targetHost, new BasicScheme());

    final HttpClientContext context = HttpClientContext.create();
    context.setCredentialsProvider(provider);
    context.setAuthCache(authCache);

    httpPost.setEntity(new StringEntity(body));

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

    HttpEntity entity = response.getEntity();
    String responseBody = entity != null ? EntityUtils.toString(entity) : null;

    if (status >= 400) {

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

    return responseBody;
}

From source file:org.apache.aurora.scheduler.http.api.security.HttpSecurityIT.java

private HttpResponse callH2Console(Credentials credentials) throws Exception {
    DefaultHttpClient defaultHttpClient = new DefaultHttpClient();

    CredentialsProvider credentialsProvider = new BasicCredentialsProvider();
    credentialsProvider.setCredentials(AuthScope.ANY, credentials);
    defaultHttpClient.setCredentialsProvider(credentialsProvider);
    return defaultHttpClient.execute(new HttpPost(formatUrl(H2_PATH + "/")));
}

From source file:org.apache.manifoldcf.agents.output.solr.HttpPoster.java

/** Initialize the standard http poster.
*//*  www  .  j a  va2 s  .  c o  m*/
public HttpPoster(String protocol, String server, int port, String webapp, String core, int connectionTimeout,
        int socketTimeout, String updatePath, String removePath, String statusPath, String realm, String userID,
        String password, String allowAttributeName, String denyAttributeName, String idAttributeName,
        String modifiedDateAttributeName, String createdDateAttributeName, String indexedDateAttributeName,
        String fileNameAttributeName, String mimeTypeAttributeName, String contentAttributeName,
        IKeystoreManager keystoreManager, Long maxDocumentLength, String commitWithin,
        boolean useExtractUpdateHandler) throws ManifoldCFException {
    // These are the paths to the handlers in Solr that deal with the actions we need to do
    this.postUpdateAction = updatePath;
    this.postRemoveAction = removePath;
    this.postStatusAction = statusPath;

    this.commitWithin = commitWithin;

    this.allowAttributeName = allowAttributeName;
    this.denyAttributeName = denyAttributeName;
    this.idAttributeName = idAttributeName;
    this.modifiedDateAttributeName = modifiedDateAttributeName;
    this.createdDateAttributeName = createdDateAttributeName;
    this.indexedDateAttributeName = indexedDateAttributeName;
    this.fileNameAttributeName = fileNameAttributeName;
    this.mimeTypeAttributeName = mimeTypeAttributeName;
    this.contentAttributeName = contentAttributeName;
    this.useExtractUpdateHandler = useExtractUpdateHandler;

    this.maxDocumentLength = maxDocumentLength;

    String location = "";
    if (webapp != null)
        location = "/" + webapp;
    if (core != null) {
        if (webapp == null)
            throw new ManifoldCFException("Webapp must be specified if core is specified.");
        location += "/" + core;
    }

    // Initialize standard solr-j.
    // First, we need an HttpClient where basic auth is properly set up.
    connectionManager = new PoolingHttpClientConnectionManager();
    connectionManager.setMaxTotal(1);

    SSLConnectionSocketFactory myFactory;
    if (keystoreManager != null) {
        myFactory = new SSLConnectionSocketFactory(keystoreManager.getSecureSocketFactory(),
                SSLConnectionSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER);
    } else {
        // Use the "trust everything" one
        myFactory = new SSLConnectionSocketFactory(KeystoreManagerFactory.getTrustingSecureSocketFactory(),
                SSLConnectionSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER);
    }

    RequestConfig.Builder requestBuilder = RequestConfig.custom().setCircularRedirectsAllowed(true)
            .setSocketTimeout(socketTimeout).setStaleConnectionCheckEnabled(true).setExpectContinueEnabled(true)
            .setConnectTimeout(connectionTimeout).setConnectionRequestTimeout(socketTimeout);

    HttpClientBuilder clientBuilder = HttpClients.custom().setConnectionManager(connectionManager)
            .setMaxConnTotal(1).disableAutomaticRetries().setDefaultRequestConfig(requestBuilder.build())
            .setRedirectStrategy(new DefaultRedirectStrategy()).setSSLSocketFactory(myFactory)
            .setRequestExecutor(new HttpRequestExecutor(socketTimeout)).setDefaultSocketConfig(
                    SocketConfig.custom().setTcpNoDelay(true).setSoTimeout(socketTimeout).build());

    if (userID != null && userID.length() > 0 && password != null) {
        CredentialsProvider credentialsProvider = new BasicCredentialsProvider();
        Credentials credentials = new UsernamePasswordCredentials(userID, password);
        if (realm != null)
            credentialsProvider.setCredentials(new AuthScope(AuthScope.ANY_HOST, AuthScope.ANY_PORT, realm),
                    credentials);
        else
            credentialsProvider.setCredentials(AuthScope.ANY, credentials);

        clientBuilder.setDefaultCredentialsProvider(credentialsProvider);
    }

    HttpClient localClient = clientBuilder.build();

    String httpSolrServerUrl = protocol + "://" + server + ":" + port + location;
    solrServer = new ModifiedHttpSolrServer(httpSolrServerUrl, localClient, new XMLResponseParser());
}

From source file:com.streamsets.datacollector.credential.cyberark.TestWebServicesFetcher.java

@Test
public void testInitializationCustomNoSslDigestAuth() throws Exception {
    Properties props = new Properties();
    props.setProperty(WebServicesFetcher.URL_KEY, "http://foo");
    props.setProperty(WebServicesFetcher.APP_ID_KEY, "appId");
    props.setProperty(WebServicesFetcher.KEYSTORE_FILE_KEY, "");
    props.setProperty(WebServicesFetcher.KEYSTORE_PASSWORD_KEY, "");
    props.setProperty(WebServicesFetcher.KEY_PASSWORD_KEY, "");
    props.setProperty(WebServicesFetcher.TRUSTSTORE_FILE_KEY, "");
    props.setProperty(WebServicesFetcher.TRUSTSTORE_PASSWORD_KEY, "");
    props.setProperty(WebServicesFetcher.SUPPORTED_PROTOCOLS_KEY, "");
    props.setProperty(WebServicesFetcher.HOSTNAME_VERIFIER_SKIP_KEY, "");
    props.setProperty(WebServicesFetcher.MAX_CONCURRENT_CONNECTIONS_KEY, "1");
    props.setProperty(WebServicesFetcher.VALIDATE_AFTER_INACTIVITY_KEY, "2");
    props.setProperty(WebServicesFetcher.CONNECTION_TIMEOUT_KEY, "5000");
    props.setProperty(WebServicesFetcher.NAME_SEPARATOR_KEY, "+");
    props.setProperty(WebServicesFetcher.HTTP_AUTH_TYPE_KEY, "digest");
    props.setProperty(WebServicesFetcher.HTTP_AUTH_USER_KEY, "user");
    props.setProperty(WebServicesFetcher.HTTP_AUTH_PASSWORD_KEY, "password");
    Configuration conf = createConfig(props);

    WebServicesFetcher fetcher = new WebServicesFetcher();
    try {/* ww w  .  j a  v  a2 s  . co  m*/
        fetcher.init(conf);
        Assert.assertNotNull(fetcher.getConfig());

        Assert.assertEquals("http://foo", fetcher.getUrl());
        Assert.assertEquals("appId", fetcher.getAppId());
        Assert.assertEquals(5000, fetcher.getConnectionTimeout());
        Assert.assertEquals("+", fetcher.getSeparator());
        Assert.assertEquals("digest", fetcher.getHttpAuth());
        Assert.assertEquals("user", fetcher.getHttpAuthUser());
        Assert.assertEquals("password", fetcher.getHttpAuthPassword());
        Assert.assertNotNull(fetcher.getCredentialsProvider());
        Assert.assertEquals("user",
                fetcher.getCredentialsProvider().getCredentials(AuthScope.ANY).getUserPrincipal().getName());
        Assert.assertEquals("password",
                fetcher.getCredentialsProvider().getCredentials(AuthScope.ANY).getPassword());
        Assert.assertTrue(fetcher.getAuthCache().get(new HttpHost(fetcher.getUrl())) instanceof DigestScheme);

        PoolingHttpClientConnectionManager connectionManager = fetcher.getConnectionManager();
        Assert.assertEquals(1, connectionManager.getMaxTotal());
        Assert.assertEquals(1, connectionManager.getDefaultMaxPerRoute());
        Assert.assertEquals(2, connectionManager.getValidateAfterInactivity());

        Assert.assertNull(fetcher.getSslConnectionSocketFactory());
    } finally {
        fetcher.destroy();
    }
}

From source file:com.ibm.watson.developer_cloud.professor_languo.endpoints.AskAQuestionResource.java

/**
 * Read the credentials and urls from the properties
 * /*from  w ww . j a  va 2 s . co m*/
 * @param appProperties properties object to read from
 */
private void initialize(Properties appProperties) {

    logger.debug(appProperties.entrySet().toString());

    // read credentials and endpoint urls
    username = appProperties.getProperty(RetrieveAndRankConstants.USERNAME, "");
    password = appProperties.getProperty(RetrieveAndRankConstants.PASSWORD, "");
    final String retrieve_and_rank_endpoint = appProperties.getProperty(RetrieveAndRankConstants.RNR_ENDPOINT,
            "");
    ranker_id = appProperties.getProperty(RetrieveAndRankConstants.RANKER_ID, "");
    ranker_url = retrieve_and_rank_endpoint + RetrieveAndRankConstants.RNR_ENDPOINT_VERSION
            + RetrieveAndRankConstants.RANKERS_URL + ranker_id + RetrieveAndRankConstants.RERANK_URL;
    checkStrings(username, password, retrieve_and_rank_endpoint, ranker_id, ranker_url);

    // connect the client
    client = RankerCreationUtil.createHttpClient(AuthScope.ANY,
            new UsernamePasswordCredentials(username, password));
}

From source file:com.sun.jersey.client.apache4.impl.AuthTest.java

public void testAuthDelete() {
    ResourceConfig rc = new DefaultResourceConfig(AuthResource.class);
    rc.getProperties().put(ResourceConfig.PROPERTY_CONTAINER_REQUEST_FILTERS, LoggingFilter.class.getName());
    rc.getProperties().put(ResourceConfig.PROPERTY_CONTAINER_RESPONSE_FILTERS, LoggingFilter.class.getName());
    startServer(rc);/*from  w w w .j  av  a 2 s.  com*/

    CredentialsProvider credentialsProvider = new org.apache.http.impl.client.BasicCredentialsProvider();
    credentialsProvider.setCredentials(AuthScope.ANY, new UsernamePasswordCredentials("name", "password"));

    DefaultApacheHttpClient4Config config = new DefaultApacheHttpClient4Config();
    config.getProperties().put(ApacheHttpClient4Config.PROPERTY_CREDENTIALS_PROVIDER, credentialsProvider);
    ApacheHttpClient4 c = ApacheHttpClient4.create(config);

    WebResource r = c.resource(getUri().path("test").build());
    ClientResponse response = r.delete(ClientResponse.class);
    assertEquals(response.getStatus(), 204);
}

From source file:org.apache.manifoldcf.crawler.connectors.wiki.WikiConnector.java

protected void getSession() throws ManifoldCFException, ServiceInterruption {
    if (hasBeenSetup == false) {
        String emailAddress = params.getParameter(WikiConfig.PARAM_EMAIL);
        if (emailAddress != null)
            userAgent = "Mozilla/5.0 (ApacheManifoldCFWikiReader; "
                    + ((emailAddress == null) ? "" : emailAddress) + ")";
        else//from   ww  w .  jav  a2s  .c o m
            userAgent = null;

        String protocol = params.getParameter(WikiConfig.PARAM_PROTOCOL);
        if (protocol == null || protocol.length() == 0)
            protocol = "http";
        String portString = params.getParameter(WikiConfig.PARAM_PORT);
        if (portString == null || portString.length() == 0)
            portString = null;
        String path = params.getParameter(WikiConfig.PARAM_PATH);
        if (path == null)
            path = "/w";

        baseURL = protocol + "://" + server + ((portString != null) ? ":" + portString : "") + path
                + "/api.php?format=xml&";

        int socketTimeout = 900000;
        int connectionTimeout = 300000;

        javax.net.ssl.SSLSocketFactory httpsSocketFactory = KeystoreManagerFactory
                .getTrustingSecureSocketFactory();
        SSLConnectionSocketFactory myFactory = new SSLConnectionSocketFactory(
                new InterruptibleSocketFactory(httpsSocketFactory, connectionTimeout),
                SSLConnectionSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER);

        // Set up connection manager
        connectionManager = new PoolingHttpClientConnectionManager();

        CredentialsProvider credentialsProvider = new BasicCredentialsProvider();

        if (accessUser != null && accessUser.length() > 0 && accessPassword != null) {
            Credentials credentials = new UsernamePasswordCredentials(accessUser, accessPassword);
            if (accessRealm != null && accessRealm.length() > 0)
                credentialsProvider.setCredentials(
                        new AuthScope(AuthScope.ANY_HOST, AuthScope.ANY_PORT, accessRealm), credentials);
            else
                credentialsProvider.setCredentials(AuthScope.ANY, credentials);
        }

        RequestConfig.Builder requestBuilder = RequestConfig.custom().setCircularRedirectsAllowed(true)
                .setSocketTimeout(socketTimeout).setStaleConnectionCheckEnabled(true)
                .setExpectContinueEnabled(true).setConnectTimeout(connectionTimeout)
                .setConnectionRequestTimeout(socketTimeout);

        // If there's a proxy, set that too.
        if (proxyHost != null && proxyHost.length() > 0) {

            int proxyPortInt;
            if (proxyPort != null && proxyPort.length() > 0) {
                try {
                    proxyPortInt = Integer.parseInt(proxyPort);
                } catch (NumberFormatException e) {
                    throw new ManifoldCFException("Bad number: " + e.getMessage(), e);
                }
            } else
                proxyPortInt = 8080;

            // Configure proxy authentication
            if (proxyUsername != null && proxyUsername.length() > 0) {
                if (proxyPassword == null)
                    proxyPassword = "";
                if (proxyDomain == null)
                    proxyDomain = "";

                credentialsProvider.setCredentials(new AuthScope(proxyHost, proxyPortInt),
                        new NTCredentials(proxyUsername, proxyPassword, currentHost, proxyDomain));
            }

            HttpHost proxy = new HttpHost(proxyHost, proxyPortInt);
            requestBuilder.setProxy(proxy);
        }

        httpClient = HttpClients.custom().setConnectionManager(connectionManager).setMaxConnTotal(1)
                .disableAutomaticRetries().setDefaultRequestConfig(requestBuilder.build())
                .setDefaultSocketConfig(
                        SocketConfig.custom().setTcpNoDelay(true).setSoTimeout(socketTimeout).build())
                .setDefaultCredentialsProvider(credentialsProvider).setSSLSocketFactory(myFactory)
                .setRequestExecutor(new HttpRequestExecutor(socketTimeout)).build();

        /*
        BasicHttpParams params = new BasicHttpParams();
        params.setBooleanParameter(CoreProtocolPNames.USE_EXPECT_CONTINUE,true);
        params.setIntParameter(CoreProtocolPNames.WAIT_FOR_CONTINUE,socketTimeout);
        params.setBooleanParameter(CoreConnectionPNames.TCP_NODELAY,true);
        params.setBooleanParameter(CoreConnectionPNames.STALE_CONNECTION_CHECK,true);
        params.setIntParameter(CoreConnectionPNames.SO_TIMEOUT,socketTimeout);
        params.setIntParameter(CoreConnectionPNames.CONNECTION_TIMEOUT,connectionTimeout);
        params.setBooleanParameter(ClientPNames.ALLOW_CIRCULAR_REDIRECTS,true);
        DefaultHttpClient localHttpClient = new DefaultHttpClient(connectionManager,params);
        // No retries
        localHttpClient.setHttpRequestRetryHandler(new HttpRequestRetryHandler()
          {
            public boolean retryRequest(
              IOException exception,
              int executionCount,
              HttpContext context)
            {
              return false;
            }
                 
          });
        */

        loginToAPI();

        hasBeenSetup = true;
    }
}

From source file:org.botlibre.util.Utils.java

public static String httpAuthPOST(String url, String user, String password, String type, String data)
        throws Exception {
    HttpPost request = new HttpPost(url);
    StringEntity params = new StringEntity(data, "utf-8");
    request.addHeader("content-type", type);
    request.setEntity(params);/*from w  w w  .  j  a  va  2s . c o  m*/
    DefaultHttpClient client = new DefaultHttpClient();
    client.getCredentialsProvider().setCredentials(new AuthScope(AuthScope.ANY),
            new UsernamePasswordCredentials(user, password));
    HttpResponse response = client.execute(request);
    return fetchResponse(response);
}

From source file:es.auth.plugin.AbstractUnitTest.java

protected final JestHttpClient getJestClient(final String serverUri, final String username,
        final String password) throws Exception {
    final CredentialsProvider credsProvider = new BasicCredentialsProvider();
    final HttpClientConfig clientConfig1 = new HttpClientConfig.Builder(serverUri).multiThreaded(true).build();
    // Construct a new Jest client according to configuration via factory
    final JestClientFactory factory1 = new JestClientFactory();
    factory1.setHttpClientConfig(clientConfig1);
    final JestHttpClient c = factory1.getObject();
    final HttpClientBuilder hcb = HttpClients.custom();
    credsProvider.setCredentials(new AuthScope(AuthScope.ANY),
            new UsernamePasswordCredentials(username, password));
    hcb.setDefaultCredentialsProvider(credsProvider);
    hcb.setDefaultSocketConfig(SocketConfig.custom().setSoTimeout(60 * 1000).build());
    final CloseableHttpClient httpClient = hcb.build();
    c.setHttpClient(httpClient);/*from  w  w  w  . j  a  v  a 2s.c  om*/
    return c;
}

From source file:aajavafx.EmployeeController.java

public void change(int id) throws IOException, JSONException {
    Employees myEmployee = new Employees();

    Gson gson = new Gson();
    Employees employeeNew = null;//  ww  w .  ja va2s .c  om
    JSONObject jo = new JSONObject();
    CredentialsProvider provider = new BasicCredentialsProvider();
    UsernamePasswordCredentials credentials = new UsernamePasswordCredentials("EMPLOYEE", "password");
    provider.setCredentials(AuthScope.ANY, credentials);
    HttpClient client = HttpClientBuilder.create().setDefaultCredentialsProvider(provider).build();
    HttpGet get = new HttpGet("http://localhost:8080/MainServerREST/api/employees");

    HttpResponse response = client.execute(get);
    System.out.println("RESPONSE IS: " + response);
    boolean register = true;
    JSONArray jsonArray = new JSONArray(
            IOUtils.toString(response.getEntity().getContent(), Charset.forName("UTF-8")));
    System.out.println(jsonArray);
    for (int i = 0; i < jsonArray.length(); i++) {
        jo = (JSONObject) jsonArray.getJSONObject(i);
        myEmployee = gson.fromJson(jo.toString(), Employees.class);
        if (myEmployee.getEmpId().equals(id)) {
            employeeNew = new Employees(1, myEmployee.getEmpFirstname(), myEmployee.getEmpLastname(),
                    myEmployee.getEmpUsername(), myEmployee.getEmpPassword(), myEmployee.getEmpEmail(),
                    myEmployee.getEmpPhone(), manager, register);
        }

    }
    deleteRow(id);
    validate(employeeNew);
}