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:org.exoplatform.addons.es.client.ElasticClient.java

private HttpClient getHttpClient() {
    // Check if Basic Authentication need to be used
    if (StringUtils.isNotBlank(getEsUsernameProperty())) {
        DefaultHttpClient httpClient = new DefaultHttpClient(getClientConnectionManager());
        httpClient.getCredentialsProvider().setCredentials(
                new AuthScope(AuthScope.ANY_HOST, AuthScope.ANY_PORT),
                new UsernamePasswordCredentials(getEsUsernameProperty(), getEsPasswordProperty()));
        LOG.debug("Basic authentication for ES activated with username = {} and password = {}",
                getEsUsernameProperty(), getEsPasswordProperty());
        return httpClient;
    } else {//from   w w w.ja  va  2 s. c o  m
        LOG.debug("Basic authentication for ES not activated");
        return new DefaultHttpClient(getClientConnectionManager());
    }
}

From source file:org.elasticsearch.xpack.security.authc.kerberos.SpnegoHttpClientConfigCallbackHandler.java

private void setupSpnegoAuthSchemeSupport(HttpAsyncClientBuilder httpClientBuilder) {
    final Lookup<AuthSchemeProvider> authSchemeRegistry = RegistryBuilder.<AuthSchemeProvider>create()
            .register(AuthSchemes.SPNEGO, new SPNegoSchemeFactory()).build();

    final GSSManager gssManager = GSSManager.getInstance();
    try {//from ww  w .j a v a2s  .  co m
        final GSSName gssUserPrincipalName = gssManager.createName(userPrincipalName, GSSName.NT_USER_NAME);
        login();
        final AccessControlContext acc = AccessController.getContext();
        final GSSCredential credential = doAsPrivilegedWrapper(loginContext.getSubject(),
                (PrivilegedExceptionAction<GSSCredential>) () -> gssManager.createCredential(
                        gssUserPrincipalName, GSSCredential.DEFAULT_LIFETIME, SPNEGO_OID,
                        GSSCredential.INITIATE_ONLY),
                acc);

        final KerberosCredentialsProvider credentialsProvider = new KerberosCredentialsProvider();
        credentialsProvider.setCredentials(
                new AuthScope(AuthScope.ANY_HOST, AuthScope.ANY_PORT, AuthScope.ANY_REALM, AuthSchemes.SPNEGO),
                new KerberosCredentials(credential));
        httpClientBuilder.setDefaultCredentialsProvider(credentialsProvider);
    } catch (GSSException e) {
        throw new RuntimeException(e);
    } catch (PrivilegedActionException e) {
        throw new RuntimeException(e.getCause());
    }
    httpClientBuilder.setDefaultAuthSchemeRegistry(authSchemeRegistry);
}

From source file:org.geosdi.geoplatform.gui.server.service.impl.PublisherService.java

@PostConstruct
public void init() {
    logger.info("Reload publisher parameters: URL CLUSTER RELOAD " + urlClusterReload
            + " - HOST URL CLUSTER RELOAD " + hostUrlClusterReload + " - USERNAME CLUSTER RELOAD "
            + userNameClusterReload + " - PASSWORD CLUSTER RELOAD " + passwordClusterReload);
    localContext = new BasicHttpContext();
    HttpParams params = new BasicHttpParams();
    HttpConnectionParams.setConnectionTimeout(params, 60000);
    HttpConnectionParams.setSoTimeout(params, 60000);

    this.httpclient = new DefaultHttpClient(params);
    CredentialsProvider credsProvider = new BasicCredentialsProvider();
    credsProvider.setCredentials(new AuthScope(AuthScope.ANY_HOST, AuthScope.ANY_PORT),
            new UsernamePasswordCredentials(userNameClusterReload, passwordClusterReload));
    httpclient.setCredentialsProvider(credsProvider);
}

From source file:de.simu.decomap.component.polling.impl.helper.IcingaDataConnectionRest.java

/**
 * preparing rest request and getting data
 * /*  w  w  w.j ava2 s. com*/
 * @return data from rest request
 */
public String getData() {
    try {
        StringBuilder url = new StringBuilder();

        url.append("http://" + ip + path + file + ".cgi?");
        for (String filter : filters) {
            url.append("&" + filter);
        }
        url.append("&jsonoutput");

        CredentialsProvider credsProvider = new BasicCredentialsProvider();
        credsProvider.setCredentials(new AuthScope(ip, AuthScope.ANY_PORT),
                new UsernamePasswordCredentials(username, password));

        CloseableHttpClient httpClient = HttpClientBuilder.create().setDefaultCredentialsProvider(credsProvider)
                .build();

        // specify the get request
        HttpGet getRequest = new HttpGet(url.toString());

        CloseableHttpResponse httpResponse = httpClient.execute(getRequest);
        HttpEntity entity = httpResponse.getEntity();

        if (entity != null) {
            return EntityUtils.toString(entity);
        }
    } catch (ParseException | IOException e) {
        logger.error("Error while getting data over rest", e);
        IfMapClient.criticalError(e);
    }

    return null;
}

From source file:org.bedework.synch.shared.cnctrs.AbstractConnectorInstance.java

protected CloseableHttpClient getClient() throws SynchException {
    if (client != null) {
        return client;
    }//from www.  j a va2s. c om

    final CloseableHttpClient cl = HttpClients.createDefault();

    final HttpClientContext context = HttpClientContext.create();
    if (info.getPrincipalHref() != null) {
        final CredentialsProvider credsProvider = new BasicCredentialsProvider();
        credsProvider.setCredentials(new AuthScope(AuthScope.ANY_HOST, AuthScope.ANY_PORT),
                new UsernamePasswordCredentials(info.getPrincipalHref(),
                        cnctr.getSyncher().decrypt(info.getPassword())));
        context.setCredentialsProvider(credsProvider);
    }

    client = cl;

    return cl;
}

From source file:org.modelio.vbasic.net.ApacheUriConnection.java

@objid("f8e1a3e4-45b3-4065-8838-90de7fe64eaa")
private void openConnection() throws IOException, IllegalStateException {
    this.context = HttpClientContext.create();

    CredentialsProvider credsProvider = new SystemDefaultCredentialsProvider();
    this.context.setCredentialsProvider(credsProvider);

    if (this.auth != null) {
        switch (this.auth.getSchemeId()) {
        case UserPasswordAuthData.USERPASS_SCHEME_ID:
            UserPasswordAuthData authData = (UserPasswordAuthData) this.auth;

            if (authData.getUser() == null)
                throw new ClientProtocolException(this.uri + ": User name may not be null.");

            UsernamePasswordCredentials credentials = new UsernamePasswordCredentials(authData.getUser(),
                    authData.getPassword());
            AuthScope authscope = new AuthScope(this.uri.getHost(), AuthScope.ANY_PORT);
            credsProvider.setCredentials(authscope, credentials);

            break;
        case NoneAuthData.AUTH_NONE_SCHEME_ID:
            break;

        default://  w  w w. java 2s  .c o  m
            throw new UnknownServiceException(this.auth + " not supported for " + this.uri);
        }
    }

    /** support different proxy */
    configProxy(credsProvider);

    getRequest().setConfig(this.configBuilder.build());

    try {
        this.res = httpclient.execute(getRequest(), this.context);
        int statusCode = this.res.getStatusLine().getStatusCode();

        if (statusCode >= 200 && statusCode < 300) {
            // Try to get content now to get an exception on failure immediately
            this.res.getEntity().getContent();
        } else {
            handleConnectionFailure();
        }

    } catch (ClientProtocolException e) {
        throw new IOException(e.getLocalizedMessage(), e);
    }
}

From source file:com.googlecode.sardine.SardineImpl.java

/**
 * Main constructor.//from ww  w .j  a v  a  2s  . c  o  m
 */
public SardineImpl(Factory factory, String username, String password, SSLSocketFactory sslSocketFactory,
        HttpRoutePlanner routePlanner, Integer port) throws SardineException {
    this.factory = factory;

    HttpParams params = new BasicHttpParams();
    ConnManagerParams.setMaxTotalConnections(params, 100);
    HttpProtocolParams.setVersion(params, HttpVersion.HTTP_1_1);
    HttpProtocolParams.setUserAgent(params, "Sardine/" + Version.getSpecification());

    SchemeRegistry schemeRegistry = new SchemeRegistry();
    schemeRegistry
            .register(new Scheme("http", PlainSocketFactory.getSocketFactory(), port != null ? port : 80));
    if (sslSocketFactory != null)
        schemeRegistry.register(new Scheme("https", sslSocketFactory, port != null ? port : 443));
    else
        schemeRegistry
                .register(new Scheme("https", SSLSocketFactory.getSocketFactory(), port != null ? port : 443));

    ClientConnectionManager cm = new ThreadSafeClientConnManager(params, schemeRegistry);
    this.client = new DefaultHttpClient(cm, params);

    // for proxy configurations
    if (routePlanner != null)
        this.client.setRoutePlanner(routePlanner);

    if ((username != null) && (password != null)) {
        this.client.getCredentialsProvider().setCredentials(
                new AuthScope(AuthScope.ANY_HOST, AuthScope.ANY_PORT),
                new UsernamePasswordCredentials(username, password));

        this.authEnabled = true;
    }
}

From source file:com.globo.aclapi.client.ClientAclAPI.java

private static HttpClient newDefaultHttpClient(SSLSocketFactory socketFactory, HttpParams params,
        ProxySelector proxySelector) {
    SchemeRegistry registry = new SchemeRegistry();
    registry.register(new Scheme("http", PlainSocketFactory.getSocketFactory(), 80));
    registry.register(new Scheme("https", socketFactory, 443));

    ClientConnectionManager connectionManager = new ThreadSafeClientConnManager(params, registry);

    DefaultHttpClient httpClient = new DefaultHttpClient(connectionManager, params) {
        @Override/*from ww w .j  ava2s  .  c o  m*/
        protected HttpContext createHttpContext() {
            HttpContext httpContext = super.createHttpContext();
            AuthSchemeRegistry authSchemeRegistry = new AuthSchemeRegistry();
            authSchemeRegistry.register("Bearer", new BearerAuthSchemeFactory());
            httpContext.setAttribute(ClientContext.AUTHSCHEME_REGISTRY, authSchemeRegistry);
            AuthScope sessionScope = new AuthScope(AuthScope.ANY_HOST, AuthScope.ANY_PORT, AuthScope.ANY_REALM,
                    "Bearer");

            Credentials credentials = new TokenCredentials("");
            CredentialsProvider credentialsProvider = new BasicCredentialsProvider();
            credentialsProvider.setCredentials(sessionScope, credentials);
            httpContext.setAttribute(ClientContext.CREDS_PROVIDER, credentialsProvider);
            return httpContext;
        }
    };
    httpClient.setHttpRequestRetryHandler(new DefaultHttpRequestRetryHandler(0, false));
    httpClient.setRoutePlanner(new ProxySelectorRoutePlanner(registry, proxySelector));

    return httpClient;
}

From source file:com.marvelution.hudson.plugins.apiv2.client.connectors.HttpClient4Connector.java

/**
 * Get the {@link AuthScope} for the {@link #server}
 * //from www  . ja  v a2s .  com
 * @return the {@link AuthScope}
 */
private AuthScope getAuthScope() {
    String host = AuthScope.ANY_HOST;
    int port = AuthScope.ANY_PORT;
    try {
        final URI hostUri = new URI(server.getHost());
        host = hostUri.getHost();
        if (hostUri.getPort() > -1) {
            port = hostUri.getPort();
        } else if ("http".equalsIgnoreCase(hostUri.getScheme())) {
            port = 80;
        } else if ("https".equalsIgnoreCase(hostUri.getScheme())) {
            port = 443;
        }
    } catch (URISyntaxException e) {
        // Failed to parse the server host URI
        // Fall-back on preset defaults
        log.error("Failed to parse the Server host url to an URI", e);
    }
    return new AuthScope(host, port, "realm");
}

From source file:com.mediaportal.ampdroid.api.JsonClient.java

private String executeRequest(HttpUriRequest request, int _timeout, String url) {
    HttpParams httpParameters = new BasicHttpParams();
    HttpConnectionParams.setConnectionTimeout(httpParameters, _timeout);
    HttpConnectionParams.setSoTimeout(httpParameters, _timeout);
    HttpConnectionParams.setTcpNoDelay(httpParameters, true);

    DefaultHttpClient client = new DefaultHttpClient(httpParameters);
    request.setHeader("User-Agent", Constants.USER_AGENT);

    if (mUseAuth) {
        CredentialsProvider credProvider = new BasicCredentialsProvider();
        credProvider.setCredentials(new AuthScope(AuthScope.ANY_HOST, AuthScope.ANY_PORT),
                new UsernamePasswordCredentials(mUser, mPass));
        client.setCredentialsProvider(credProvider);
    }/*  w w  w. j a va  2 s  .  co  m*/

    HttpResponse httpResponse;

    try {
        httpResponse = client.execute(request);
        responseCode = httpResponse.getStatusLine().getStatusCode();
        message = httpResponse.getStatusLine().getReasonPhrase();

        HttpEntity entity = httpResponse.getEntity();

        if (entity != null) {

            InputStream instream = entity.getContent();
            response = convertStreamToString(instream);

            // Closing the input stream will trigger connection release
            instream.close();

            return response;
        }

    } catch (ClientProtocolException e) {
        client.getConnectionManager().shutdown();
        e.printStackTrace();
    } catch (IOException e) {
        client.getConnectionManager().shutdown();
        e.printStackTrace();
    }
    return null;
}