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.mirth.connect.connectors.ws.WebServiceDispatcher.java

/**
 * Returns the URL for the passed in String. If the URL requires authentication, then the WSDL
 * is saved as a temp file and the URL for that file is returned.
 * //from   w  ww .java 2  s .  c  om
 * @param wsdlUrl
 * @param username
 * @param password
 * @return
 * @throws Exception
 */
private URL getWsdlUrl(DispatchContainer dispatchContainer) throws Exception {
    URI uri = new URI(dispatchContainer.getCurrentWsdlUrl());

    // If the URL points to file, just return it
    if (!uri.getScheme().equalsIgnoreCase("file")) {
        BasicHttpClientConnectionManager httpClientConnectionManager = new BasicHttpClientConnectionManager(
                socketFactoryRegistry.build());
        httpClientConnectionManager.setSocketConfig(SocketConfig.custom().setSoTimeout(timeout).build());
        HttpClientBuilder clientBuilder = HttpClients.custom()
                .setConnectionManager(httpClientConnectionManager);
        HttpUtil.configureClientBuilder(clientBuilder);
        CloseableHttpClient client = clientBuilder.build();

        try {
            clients.add(client);
            HttpClientContext context = HttpClientContext.create();

            if (dispatchContainer.getCurrentUsername() != null
                    && dispatchContainer.getCurrentPassword() != null) {
                CredentialsProvider credsProvider = new BasicCredentialsProvider();
                AuthScope authScope = new AuthScope(AuthScope.ANY_HOST, AuthScope.ANY_PORT,
                        AuthScope.ANY_REALM);
                Credentials credentials = new UsernamePasswordCredentials(
                        dispatchContainer.getCurrentUsername(), dispatchContainer.getCurrentPassword());
                credsProvider.setCredentials(authScope, credentials);
                AuthCache authCache = new BasicAuthCache();
                RegistryBuilder<AuthSchemeProvider> registryBuilder = RegistryBuilder
                        .<AuthSchemeProvider>create();
                registryBuilder.register(AuthSchemes.BASIC, new BasicSchemeFactory());

                context.setCredentialsProvider(credsProvider);
                context.setAuthSchemeRegistry(registryBuilder.build());
                context.setAuthCache(authCache);
            }

            RequestConfig requestConfig = RequestConfig.custom().setConnectTimeout(timeout)
                    .setSocketTimeout(timeout).setStaleConnectionCheckEnabled(true).build();
            context.setRequestConfig(requestConfig);

            return getWsdl(client, context, dispatchContainer, new HashMap<String, File>(),
                    dispatchContainer.getCurrentWsdlUrl()).toURI().toURL();
        } finally {
            HttpClientUtils.closeQuietly(client);
            clients.remove(client);
        }
    }

    return uri.toURL();
}

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

private void configureProxy(ProxyDescriptor proxy) {
    if (proxy != null) {
        config.setProxy(new HttpHost(proxy.getHost(), proxy.getPort()));
        if (proxy.getUsername() != null) {
            Credentials creds = null;//  w  w  w  .  j  ava 2  s  .  c o m
            if (proxy.getDomain() == null) {
                creds = new UsernamePasswordCredentials(proxy.getUsername(),
                        CryptoHelper.decryptIfNeeded(proxy.getPassword()));
                //This will demote the NTLM authentication scheme so that the proxy won't barf
                //when we try to give it traditional credentials. If the proxy doesn't do NTLM
                //then this won't hurt it (jcej at tragus dot org)
                List<String> authPrefs = Arrays.asList(AuthSchemes.DIGEST, AuthSchemes.BASIC, AuthSchemes.NTLM);
                config.setProxyPreferredAuthSchemes(authPrefs);
                // preemptive proxy authentication
                builder.addInterceptorFirst(new ProxyPreemptiveAuthInterceptor());
            } else {
                try {
                    String ntHost = StringUtils.isBlank(proxy.getNtHost())
                            ? InetAddress.getLocalHost().getHostName()
                            : proxy.getNtHost();
                    creds = new NTCredentials(proxy.getUsername(),
                            CryptoHelper.decryptIfNeeded(proxy.getPassword()), ntHost, proxy.getDomain());
                } catch (UnknownHostException e) {
                    log.error("Failed to determine required local hostname for NTLM credentials.", e);
                }
            }
            if (creds != null) {
                credsProvider.setCredentials(
                        new AuthScope(proxy.getHost(), proxy.getPort(), AuthScope.ANY_REALM), creds);
                if (proxy.getRedirectedToHostsList() != null) {
                    for (String hostName : proxy.getRedirectedToHostsList()) {
                        credsProvider.setCredentials(
                                new AuthScope(hostName, AuthScope.ANY_PORT, AuthScope.ANY_REALM), creds);
                    }
                }
            }
        }
    }
}

From source file:org.codelibs.fess.es.config.exentity.DataConfig.java

private AuthScope getAuthScope(final String webAuthName, final String scheme,
        final Map<String, String> paramMap) {
    final String hostname = paramMap.get(CRAWLER_WEB_AUTH + "." + webAuthName + ".host");
    final String port = paramMap.get(CRAWLER_WEB_AUTH + "." + webAuthName + ".port");
    final String realm = paramMap.get(CRAWLER_WEB_AUTH + "." + webAuthName + ".realm");
    AuthScope authScope;/*from www . ja  va 2 s .c  o  m*/
    if (StringUtil.isBlank(hostname)) {
        authScope = AuthScope.ANY;
    } else {
        int p = AuthScope.ANY_PORT;
        if (StringUtil.isNotBlank(port)) {
            try {
                p = Integer.parseInt(port);
            } catch (final NumberFormatException e) {
                logger.warn("Failed to parse " + port, e);
            }
        }

        String r = realm;
        if (StringUtil.isBlank(realm)) {
            r = AuthScope.ANY_REALM;
        }

        String s = scheme;
        if (StringUtil.isBlank(scheme) || Constants.NTLM.equals(scheme)) {
            s = AuthScope.ANY_SCHEME;
        }
        authScope = new AuthScope(hostname, p, r, s);
    }
    return authScope;
}

From source file:org.apache.abdera2.common.protocol.Session.java

public void usePreemptiveAuthentication(String target, String realm) throws URISyntaxException {
    AuthCache cache = (AuthCache) localContext.getAttribute(ClientContext.AUTH_CACHE);
    if (cache == null) {
        String host = AuthScope.ANY_HOST;
        int port = AuthScope.ANY_PORT;
        if (target != null) {
            URI uri = new URI(target);
            host = uri.getHost();/*from  w w w.ja  v a 2s . c  o m*/
            port = uri.getPort();
        }
        BasicScheme basicAuth = new BasicScheme();
        HttpHost targetHost = new HttpHost(host, port, basicAuth.getSchemeName());
        cache = new BasicAuthCache();
        cache.put(targetHost, basicAuth);
        localContext.setAttribute(ClientContext.AUTH_CACHE, cache);
    }
}

From source file:com.soundcloud.playerapi.ApiWrapper.java

/** @return The HttpClient instance used to make the calls */
public HttpClient getHttpClient() {
    if (httpClient == null) {
        final HttpParams params = getParams();
        HttpClientParams.setRedirecting(params, false);
        HttpProtocolParams.setUserAgent(params, getUserAgent());

        final SchemeRegistry registry = new SchemeRegistry();
        registry.register(new Scheme("http", getSocketFactory(), 80));
        final SSLSocketFactory sslFactory = getSSLSocketFactory();
        registry.register(new Scheme("https", sslFactory, 443));
        httpClient = new DefaultHttpClient(new ThreadSafeClientConnManager(params, registry), params) {
            {//from   w  w  w .  ja v a2 s .c om
                setKeepAliveStrategy(new ConnectionKeepAliveStrategy() {
                    @Override
                    public long getKeepAliveDuration(HttpResponse httpResponse, HttpContext httpContext) {
                        return KEEPALIVE_TIMEOUT;
                    }
                });

                getCredentialsProvider().setCredentials(
                        new AuthScope(AuthScope.ANY_HOST, AuthScope.ANY_PORT, CloudAPI.REALM, OAUTH_SCHEME),
                        OAuth2Scheme.EmptyCredentials.INSTANCE);

                getAuthSchemes().register(CloudAPI.OAUTH_SCHEME, new OAuth2Scheme.Factory(ApiWrapper.this));

                addResponseInterceptor(new HttpResponseInterceptor() {
                    @Override
                    public void process(HttpResponse response, HttpContext context)
                            throws HttpException, IOException {
                        if (response == null || response.getEntity() == null)
                            return;

                        HttpEntity entity = response.getEntity();
                        Header header = entity.getContentEncoding();
                        if (header != null) {
                            for (HeaderElement codec : header.getElements()) {
                                if (codec.getName().equalsIgnoreCase("gzip")) {
                                    response.setEntity(new GzipDecompressingEntity(entity));
                                    break;
                                }
                            }
                        }
                    }
                });
            }

            @Override
            protected HttpContext createHttpContext() {
                HttpContext ctxt = super.createHttpContext();
                ctxt.setAttribute(ClientContext.AUTH_SCHEME_PREF,
                        Arrays.asList(CloudAPI.OAUTH_SCHEME, "digest", "basic"));
                return ctxt;
            }

            @Override
            protected BasicHttpProcessor createHttpProcessor() {
                BasicHttpProcessor processor = super.createHttpProcessor();
                processor.addInterceptor(new OAuth2HttpRequestInterceptor());
                return processor;
            }

            // for testability only
            @Override
            protected RequestDirector createClientRequestDirector(HttpRequestExecutor requestExec,
                    ClientConnectionManager conman, ConnectionReuseStrategy reustrat,
                    ConnectionKeepAliveStrategy kastrat, HttpRoutePlanner rouplan, HttpProcessor httpProcessor,
                    HttpRequestRetryHandler retryHandler, RedirectHandler redirectHandler,
                    AuthenticationHandler targetAuthHandler, AuthenticationHandler proxyAuthHandler,
                    UserTokenHandler stateHandler, HttpParams params) {
                return getRequestDirector(requestExec, conman, reustrat, kastrat, rouplan, httpProcessor,
                        retryHandler, redirectHandler, targetAuthHandler, proxyAuthHandler, stateHandler,
                        params);
            }
        };
    }
    return httpClient;
}

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

/**
 * This method will download the specified localFile to the local cache. Any
 * directories that need to be created will be generated as a side-effect of
 * this action. There is no discretion regarding whether the localFile
 * currently exists or not, if a localFile exists in the specified location,
 * it will be overwritten.//ww  w .java  2  s. com
 * 
 * If the localFile does not exist in the central repository, this method
 * will throw an IOException and will not create a zero length localFile.
 * However the directories that would have contained the localFile will be
 * created.
 * 
 * @return a copy of the remote localFile specified
 * @throws IOException
 *             Exception will be thrown if the remote localFile does not
 *             exist.
 */
private void downloadRemoteFile(int socketTimeout) throws Exception {
    if (remoteFile == null)
        return;

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

    final HttpGet get = new HttpGet(remoteFile.toString());
    HttpClientParams.setAuthenticating(get.getParams(), true);
    HttpClientParams.setRedirecting(get.getParams(), false);
    HttpUtils.execute(client, get, new HttpUtils.HttpResponseHandler() {
        @Override
        public void handleResponse(HttpResponse response) throws Exception {
            int status = response.getStatusLine().getStatusCode();
            if (status == HttpStatus.SC_OK) {
                getRemoteFileFromStream(response.getEntity().getContent());
                setModifiedTime(get);
            }
        }
    });
}

From source file:uk.org.openeyes.oink.itest.adapters.ITProxyAdapter.java

@Test
public void testCreatePatient() throws Exception {

    Thread.sleep(10000);//from   w w w .  ja v a2 s. com

    OINKRequestMessage req = new OINKRequestMessage();
    req.setResourcePath("/Patient");
    req.setMethod(HttpMethod.POST);

    InputStream is = ITProxyAdapter.class.getResourceAsStream("/example-messages/fhir/patient2.json");
    Parser parser = new JsonParser();
    Patient p = (Patient) parser.parse(is);

    FhirBody body = new FhirBody(p);
    req.setBody(body);

    RabbitClient client = new RabbitClient(props.getProperty("rabbit.host"),
            Integer.parseInt(props.getProperty("rabbit.port")), props.getProperty("rabbit.vhost"),
            props.getProperty("rabbit.username"), props.getProperty("rabbit.password"));

    OINKResponseMessage resp = client.sendAndRecieve(req, props.getProperty("rabbit.routingKey"),
            props.getProperty("rabbit.defaultExchange"));

    assertEquals(201, resp.getStatus());

    String locationHeader = resp.getLocationHeader();
    assertNotNull(locationHeader);
    assertFalse(locationHeader.isEmpty());
    log.info("Posted to " + locationHeader);

    // Check exists on server
    // See if Patient exists
    DefaultHttpClient httpClient = new DefaultHttpClient();

    httpClient.getCredentialsProvider().setCredentials(new AuthScope(AuthScope.ANY_HOST, AuthScope.ANY_PORT),
            new UsernamePasswordCredentials("admin", "admin"));

    HttpGet httpGet = new HttpGet(locationHeader);
    httpGet.setHeader("Accept", "application/fhir+json");
    HttpResponse response1 = httpClient.execute(httpGet);
    assertEquals(200, response1.getStatusLine().getStatusCode());
}

From source file:com.imense.imenseANPRsdkProAUNZ.ImenseLicenseServer.java

@Override
protected Boolean doInBackground(Void... arg0) {

    try {/*from w  w w.  j  a v a 2 s. co  m*/

        int[] uid_success = { 0 };
        //generate unique device ID
        String device_uid = ImenseOCRTask.getUniqueDeviceID(androidAppContext, uid_success);

        if (device_uid == null || device_uid.length() < VALID_UID_LENGTH) {
            throw new Exception("Invalid UID");
        }

        // Instantiate the custom HttpClient
        DefaultHttpClient client = new MyHttpClient(androidAppContext.getApplicationContext());

        //see http://hc.apache.org/httpcomponents-client/httpclient/xref/index.html
        CredentialsProvider credsProvider = new BasicCredentialsProvider();
        credsProvider.setCredentials(new AuthScope(AuthScope.ANY_HOST, AuthScope.ANY_PORT),
                new UsernamePasswordCredentials(ImenseLicenseServerLogin, ImenseLicenseServerPassword));
        client.setCredentialsProvider(credsProvider);

        HttpGet httpget = new HttpGet(ImenseLicenseServerURL + device_uid);

        // Execute the GET call and obtain the response
        HttpResponse httpresponse = client.execute(httpget);
        HttpEntity resEntity = httpresponse.getEntity();

        //System.out.println("Response Status: <"+httpresponse.getStatusLine()+">");
        if (resEntity != null) {
            String resS = EntityUtils.toString(resEntity);
            resS = resS.trim();

            if (resS.length() == VALID_KEY_LENGTH && !resS.startsWith("Error:")) {
                //this should be a valid key!
                licensekey = resS;
            } else {
                if (resS.startsWith("Error:")) {
                    serverResponseMessage = resS; //human readable error message
                }
            }
        }
        if (resEntity != null) {
            resEntity.consumeContent();
        }

        // When HttpClient instance is no longer needed,
        // shut down the connection manager to ensure
        // immediate deallocation of all system resources
        client.getConnectionManager().shutdown();

    } catch (Exception ex) {
        ex.printStackTrace();
    }

    if (licensekey != null && licensekey.length() == VALID_KEY_LENGTH) {
        //verify license key

        int verificationResponse = ImenseOCRTask.verifyLicenseKey(androidAppContext, licensekey);

        //"verificationResponse" may take on the following values:
        //0: license key invalid or expired
        //1: license key valid for more than 14 days
        //>1: license key valid for "verificationResponse-1" number of days

        if (verificationResponse < 1) {
            licensekey = null;
            return false;
        }

        return true;
    } //if (licensekey != null && licensekey.length()==VALID_KEY_LENGTH) {

    return false;
}

From source file:io.cloudsoft.marklogic.nodes.MarkLogicNodeSshDriver.java

@Override
public Set<String> scanDatabases() {
    LOG.debug("Scanning databases");

    DefaultHttpClient httpClient = new DefaultHttpClient();
    try {//from   w  w w .ja va2  s. c o m
        httpClient.getCredentialsProvider().setCredentials(new AuthScope(null, AuthScope.ANY_PORT),
                new UsernamePasswordCredentials(getEntity().getUser(), getEntity().getPassword()));

        String adminUrl = getEntity().getAdminConnectUrl();
        String uri = adminUrl + "/database_list.xqy";
        HttpGet httpget = new HttpGet(uri);

        HttpResponse response = httpClient.execute(httpget);
        HttpEntity entity = response.getEntity();
        String result = IOUtils.toString(entity.getContent());
        EntityUtils.consume(entity);

        Set<String> forests = Sets.newHashSet();
        String[] split = result.split("\n");
        Collections.addAll(forests, split);
        return forests;
    } catch (IOException e) {
        throw new RuntimeException(e);
    } finally {
        httpClient.getConnectionManager().shutdown();
    }
}