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

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

Introduction

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

Prototype

int ANY_PORT

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

Click Source Link

Document

The -1 value represents any port.

Usage

From source file:com.untangle.app.web_filter.WebFilterDecisionEngine.java

/**
 * Get dia key//  w w  w.j  a v a 2  s.c  om
 * 
 * @return The dia key
 */
public String getDiaKey() {
    if (WebFilterDecisionEngine.diaKey != null)
        return WebFilterDecisionEngine.diaKey;

    /* otherwise synchronize and fetch a new one */

    if (logger.isDebugEnabled()) {
        logger.debug("start-getDiaKey");
    }
    synchronized (this) {
        long t = System.currentTimeMillis();

        if ((null == diaKey) || ((t - DIA_TIMEOUT) > lastDiaUpdate)) {
            if ((t - DIA_TRY_LIMIT) < lastDiaTry) {
                logger.warn("DIA_TRY_LIMIT has not expired, not getting key");
                return diaKey;
            }

            lastDiaTry = t;

            int timeout = 60 * 1000;
            RequestConfig defaultRequestConfig = RequestConfig.custom().setConnectTimeout(timeout)
                    .setSocketTimeout(timeout).setConnectionRequestTimeout(timeout).build();
            CloseableHttpClient httpClient = HttpClients.custom().setDefaultRequestConfig(defaultRequestConfig)
                    .build();
            CloseableHttpResponse response = null;
            CredentialsProvider credsProvider = new BasicCredentialsProvider();
            credsProvider.setCredentials(new AuthScope(AuthScope.ANY_HOST, AuthScope.ANY_PORT),
                    new UsernamePasswordCredentials("untangle", "wu+glev6"));
            HttpClientContext context = HttpClientContext.create();
            context.setCredentialsProvider(credsProvider);

            try {
                String url = "https://dl.zvelo.com/oem/dia.key";
                logger.debug("Fetch URL: \"" + url + "\"");
                HttpGet get = new HttpGet(url);
                response = httpClient.execute(get, context);
                logger.debug("Fetched URL: \"" + url + "\"");

                if (response != null && response.getStatusLine().getStatusCode() == 200) {
                    String s = EntityUtils.toString(response.getEntity(), "UTF-8");
                    s = s.trim();
                    logger.debug("DIA key response: " + s);

                    if (s.toUpperCase().startsWith("ERROR")) {
                        logger.warn("Could not get a dia key: " + s.substring(0, 10));
                    } else {
                        diaKey = s;
                        lastDiaUpdate = System.currentTimeMillis();
                    }
                } else {
                    logger.warn("Failed to get dia key: " + response);
                }
            } catch (Exception exn) {
                logger.warn("Could not get dia key", exn);
            } finally {
                try {
                    if (response != null)
                        response.close();
                } catch (Exception e) {
                    logger.warn("close", e);
                }
                try {
                    httpClient.close();
                } catch (Exception e) {
                    logger.warn("close", e);
                }
            }

        }
    }

    if (logger.isDebugEnabled()) {
        logger.debug("end-getDiaKey");
    }

    return diaKey;
}

From source file:com.bordercloud.sparql.Endpoint.java

private HashMap<String, HashMap> sendQueryPOSTwithAuth(String urlStr, String parameter, String query,
        String login, String password) throws EndpointException {

    int statusCode = 0;
    try {//  w  w  w .  java  2  s .c  om
        CredentialsProvider credsProvider = new BasicCredentialsProvider();
        credsProvider.setCredentials(new AuthScope(AuthScope.ANY_HOST, AuthScope.ANY_PORT),
                new UsernamePasswordCredentials(login, password));
        CloseableHttpClient httpclient = HttpClients.custom().setDefaultCredentialsProvider(credsProvider)
                .build();
        try {
            HttpPost httpPost = new HttpPost(urlStr);
            List<NameValuePair> nvps = new ArrayList<NameValuePair>();
            nvps.add(new BasicNameValuePair(parameter, query));
            httpPost.setEntity(new UrlEncodedFormEntity(nvps));
            CloseableHttpResponse response2 = httpclient.execute(httpPost);

            try {
                //System.out.println(response2.getStatusLine());
                statusCode = response2.getStatusLine().getStatusCode();
                if (statusCode < 200 || statusCode >= 300) {
                    throw new EndpointException(this, response2.getStatusLine().toString());
                }
                HttpEntity entity2 = response2.getEntity();
                // do something useful with the response body
                // and ensure it is fully consumed
                ////System.out.println(EntityUtils.toString(entity2));

                _response = EntityUtils.toString(entity2);
                //EntityUtils.consume(entity2);
            } finally {
                response2.close();
            }
        } finally {
            httpclient.close();
        }
    } catch (Exception e) {
        System.out.println(e.getMessage());
        e.printStackTrace();
    }

    return getResult();
}

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

/** Initialize the standard http poster.
*//*ww w .  j  a  v  a 2s.co  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.gs.tools.doc.extractor.core.util.HttpUtility.java

public static DefaultHttpClient getLoginHttpClient(String userName, String password) {
    try {//from w w w  . j  a v a  2 s . c om

        HttpParams params = new BasicHttpParams();
        HttpProtocolParams.setVersion(params, HttpVersion.HTTP_1_1);
        HttpProtocolParams.setContentCharset(params, HTTP.UTF_8);
        HttpConnectionParams.setConnectionTimeout(params, 300000);
        HttpConnectionParams.setSocketBufferSize(params, 10485760);
        HttpConnectionParams.setSoTimeout(params, 300000);

        SchemeRegistry registry = new SchemeRegistry();
        registry.register(new Scheme("http", PlainSocketFactory.getSocketFactory(), 80));

        ClientConnectionManager ccm = new ThreadSafeClientConnManager(params, registry);

        DefaultHttpClient httpClient = new DefaultHttpClient(ccm, params);
        httpClient.getCredentialsProvider().setCredentials(
                new AuthScope(AuthScope.ANY_HOST, AuthScope.ANY_PORT, AuthScope.ANY_REALM),
                new UsernamePasswordCredentials(userName, password));
        return httpClient;
    } catch (Exception e) {
        e.printStackTrace();
        return new DefaultHttpClient();
    }
}

From source file:gov.nasa.ensemble.common.io.RemotableFile.java

private File getConsistentFile(long modified, REMOTE_FILE_MODES myMode, int socketTimeout)
        throws SocketTimeoutException {
    Date modifiedDate = new Date(modified);
    DateFormat df = new SimpleDateFormat(DATE_FORMAT_STR);
    String formatedModifiedDate = df.format(modifiedDate);
    if (remoteFile == null) {
        return localFile;
    }//from  w w  w. j a v a2  s  .c  o m
    HttpConnectionParams.setSoTimeout(client.getParams(), socketTimeout);

    // tell the client to use the credential we got as parameter
    // if we have an authenticator
    Authenticator auth = AuthenticationUtil.getAuthenticator();
    if (auth != null) {
        if (client instanceof AbstractHttpClient) {
            ((AbstractHttpClient) client).getCredentialsProvider().setCredentials(
                    new AuthScope(null, AuthScope.ANY_PORT, null, AuthScope.ANY_SCHEME), auth.getCredentials());
        }
        //         state.setAuthenticationPreemptive(true);
    }

    HttpResponse response = null;
    HttpGet get = new HttpGet(remoteFile.toString());
    HttpClientParams.setRedirecting(get.getParams(), false);
    HttpClientParams.setAuthenticating(get.getParams(), true);
    try {
        get.setHeader(HttpHeaders.IF_MODIFIED_SINCE, formatedModifiedDate);
        response = client.execute(get);
        if (HttpStatus.SC_NOT_MODIFIED == response.getStatusLine().getStatusCode()) {
            return localFile;
        } else if (HttpStatus.SC_OK == response.getStatusLine().getStatusCode()) {
            InputStream is = response.getEntity().getContent();
            getRemoteFileFromStream(is);
            if (REMOTE_FILE_MODES.CHECK_CUSTOM_TIMESTAMP == myMode) {
                localFile.setLastModified(customTimeStamp);
            } else {
                setModifiedTime(get);
            }
            return localFile;
        } else if (HttpStatus.SC_NOT_FOUND == response.getStatusLine().getStatusCode()) {
            remoteFileNotFound();
        }
    } catch (SocketTimeoutException e1) {
        throw e1;
    } catch (IOException e1) {
        // HACK HACK HACK HACK
        if (e1.getMessage().contains("SocketTimeoutException"))
            throw new SocketTimeoutException();
        else
            trace.warn("Error connecting to server when " + "checking the file modified time ", e1);
    } finally {
        try {
            HttpUtils.consume(get, response);
        } catch (IOException e) {
            trace.error(e);
        }
    }
    return localFile;

}

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 w w  w.j av  a2 s .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:lucee.commons.net.http.httpclient4.HTTPEngine4Impl.java

public static void setNTCredentials(DefaultHttpClient client, String username, String password,
        String workStation, String domain) {
    // set Username and Password
    if (!StringUtil.isEmpty(username, true)) {
        if (password == null)
            password = "";
        CredentialsProvider cp = client.getCredentialsProvider();
        cp.setCredentials(new AuthScope(AuthScope.ANY_HOST, AuthScope.ANY_PORT),
                new NTCredentials(username, password, workStation, domain));
        //httpMethod.setDoAuthentication( true );
    }// ww w.  j  a va  2  s. c o m
}

From source file:org.artifactory.util.HttpClientConfigurator.java

public HttpClientConfigurator enableTokenAuthentication(boolean enableTokenAuthentication, String username,
        String password) {// w  w w .j a  v  a 2s  .  co m
    if (enableTokenAuthentication) {
        if (StringUtils.isBlank(host)) {
            throw new IllegalStateException("Cannot configure authentication when host is not set.");
        }

        config.setTargetPreferredAuthSchemes(Collections.singletonList("Bearer"));

        // We need dummy credentials otherwise we won't respond to a challenge properly
        AuthScope authScope = new AuthScope(host, AuthScope.ANY_PORT, AuthScope.ANY_REALM);
        // Dummy:dummy is the specification for forcing token authentication
        UsernamePasswordCredentials dummyCredentials = new UsernamePasswordCredentials("dummy", "dummy");
        credsProvider.setCredentials(authScope, dummyCredentials);

        // The real credentials are passed to the Bearer that will get the token with them
        UsernamePasswordCredentials realCredentials = null;
        if (StringUtils.isNotBlank(username)) {
            realCredentials = new UsernamePasswordCredentials(username, password);
        }
        Registry<AuthSchemeProvider> bearerRegistry = RegistryBuilder.<AuthSchemeProvider>create()
                .register("Bearer", new BearerSchemeFactory(realCredentials)).build();

        builder.setDefaultAuthSchemeRegistry(bearerRegistry);
    }
    return this;
}

From source file:org.janusgraph.diskstorage.es.rest.RestClientSetupTest.java

@Test
public void testHttpBasicAuthConfiguration() throws Exception {

    // testing that the appropriate values are passed to the client builder via credentials provider
    final String testRealm = "testRealm";
    final String testUser = "testUser";
    final String testPassword = "testPassword";

    final CredentialsProvider cp = basicAuthTestBase(ImmutableMap.<String, String>builder().build(), testRealm,
            testUser, testPassword);//from www.j av  a2  s  . c o m

    final Credentials credentials = cp
            .getCredentials(new AuthScope(AuthScope.ANY_HOST, AuthScope.ANY_PORT, testRealm));
    assertNotNull(credentials);
    assertEquals(testUser, credentials.getUserPrincipal().getName());
    assertEquals(testPassword, credentials.getPassword());
}

From source file:lucee.commons.net.http.httpclient.HTTPEngine4Impl.java

public static void setNTCredentials(HttpClientBuilder builder, String username, String password,
        String workStation, String domain) {
    // set Username and Password
    if (!StringUtil.isEmpty(username, true)) {
        if (password == null)
            password = "";
        CredentialsProvider cp = new BasicCredentialsProvider();
        builder.setDefaultCredentialsProvider(cp);

        cp.setCredentials(new AuthScope(AuthScope.ANY_HOST, AuthScope.ANY_PORT),
                new NTCredentials(username, password, workStation, domain));
    }//  www  .  j  a  v  a  2s. com
}