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

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

Introduction

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

Prototype

String ANY_HOST

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

Click Source Link

Document

The null value represents any host.

Usage

From source file:org.jfrog.build.client.PreemptiveHttpClient.java

private DefaultHttpClient createHttpClient(String userName, String password, int timeout) {
    BasicHttpParams params = new BasicHttpParams();
    int timeoutMilliSeconds = timeout * 1000;
    HttpConnectionParams.setConnectionTimeout(params, timeoutMilliSeconds);
    HttpConnectionParams.setSoTimeout(params, timeoutMilliSeconds);
    DefaultHttpClient client = new DefaultHttpClient(params);

    if (userName != null && !"".equals(userName)) {
        client.getCredentialsProvider().setCredentials(new AuthScope(AuthScope.ANY_HOST, AuthScope.ANY_PORT),
                new UsernamePasswordCredentials(userName, password));
        localContext = new BasicHttpContext();

        // Generate BASIC scheme object and stick it to the local execution context
        BasicScheme basicAuth = new BasicScheme();
        localContext.setAttribute("preemptive-auth", basicAuth);

        // Add as the first request interceptor
        client.addRequestInterceptor(new PreemptiveAuth(), 0);
    }//from w w w .  ja v a  2  s  .  c o  m
    boolean requestSentRetryEnabled = Boolean.parseBoolean(System.getProperty("requestSentRetryEnabled"));
    if (requestSentRetryEnabled) {
        client.setHttpRequestRetryHandler(new DefaultHttpRequestRetryHandler(3, requestSentRetryEnabled));
    }
    // set the following user agent with each request
    String userAgent = "ArtifactoryBuildClient/" + CLIENT_VERSION;
    HttpProtocolParams.setUserAgent(client.getParams(), userAgent);
    return client;
}

From source file:osh.busdriver.mielegateway.MieleGatewayDispatcher.java

/**
 * CONSTRUCTOR//w  ww .ja  v  a 2  s. co  m
 * @param logger
 * @param address
 * @throws MalformedURLException
 */
public MieleGatewayDispatcher(String gatewayHostAndPort, String username, String password,
        OSHGlobalLogger logger) {
    super();

    this.homebusUrl = "http://" + gatewayHostAndPort + "/homebus/?language=en";

    this.httpCredsProvider = new BasicCredentialsProvider();
    this.httpCredsProvider.setCredentials(new AuthScope(AuthScope.ANY_HOST, AuthScope.ANY_PORT),
            new UsernamePasswordCredentials(username, password));
    this.httpcontext = new BasicHttpContext();
    this.httpcontext.setAttribute(ClientContext.CREDS_PROVIDER, httpCredsProvider);

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

    ClientConnectionManager cm = new PoolingClientConnectionManager(schemeRegistry);

    this.httpclient = new DefaultHttpClient(cm);
    this.httpclient.getParams().setParameter(CoreProtocolPNames.PROTOCOL_VERSION, HttpVersion.HTTP_1_1); // Default to HTTP 1.1 (connection persistence)
    this.httpclient.getParams().setParameter(CoreProtocolPNames.HTTP_CONTENT_CHARSET, "UTF-8");
    this.httpclient.getParams().setParameter(CoreConnectionPNames.SO_TIMEOUT, 1000);
    this.httpclient.getParams().setParameter(CoreConnectionPNames.CONNECTION_TIMEOUT, 1000);

    this.logger = logger;

    //this.parser = new MieleGatewayParser("http://" + device + "/homebus");
    this.deviceData = new HashMap<Integer, MieleDeviceHomeBusData>();

    new Thread(this, "MieleGatewayDispatcher for " + gatewayHostAndPort).start();
}

From source file:org.opensaml.security.httpclient.HttpClientSecurityParameters.java

/**
 * A convenience method to set a (single) username and password used for BASIC authentication.
 * To disable BASIC authentication pass null for the credentials instance.
 * //from w  w w. j  a v a  2  s .com
 * <p>
 * If the <code>authScope</code> is null, an {@link AuthScope} will be generated which specifies
 * any host, port, scheme and realm.
 * </p>
 * 
 * <p>To specify multiple usernames and passwords for multiple host, port, scheme, and realm combinations, instead 
 * provide an instance of {@link CredentialsProvider} via {@link #setCredentialsProvider(CredentialsProvider)}.</p>
 * 
 * @param credentials the username and password credentials
 * @param scope the HTTP client auth scope with which to scope the credentials, may be null
 */
public void setBasicCredentialsWithScope(@Nullable final UsernamePasswordCredentials credentials,
        @Nullable final AuthScope scope) {

    if (credentials != null) {
        AuthScope authScope = scope;
        if (authScope == null) {
            authScope = new AuthScope(AuthScope.ANY_HOST, AuthScope.ANY_PORT);
        }
        BasicCredentialsProvider provider = new BasicCredentialsProvider();
        provider.setCredentials(authScope, credentials);
        credentialsProvider = provider;
    } else {
        credentialsProvider = null;
    }

}

From source file:com.microsoft.teamfoundation.plugin.impl.TfsClient.java

private Client getClient(URI uri, TfsClientFactoryImpl.ServiceProvider provider, String username,
        TfsSecret password) {//w  w w  .  ja va  2  s .  c  om
    ClientConfig clientConfig = new ClientConfig();

    CredentialsProvider credentialsProvider = new BasicCredentialsProvider();

    if (TfsClientFactoryImpl.ServiceProvider.TFS == provider) {
        /* NTLM auth for on premise installation */
        credentialsProvider.setCredentials(
                new AuthScope(uri.getHost(), uri.getPort(), AuthScope.ANY_REALM, AuthSchemes.NTLM),
                new NTCredentials(username, password.getSecret(), uri.getHost(), ""));

        logger.info("Using NTLM authentication for on premise TeamFoundationServer");

    } else if (TfsClientFactoryImpl.ServiceProvider.VSO == provider) {
        // Basic Auth for VSO services
        credentialsProvider.setCredentials(new AuthScope(AuthScope.ANY_HOST, AuthScope.ANY_PORT),
                new UsernamePasswordCredentials(username, password.getSecret()));

        logger.info("Using user/pass authentication for Visual Studio Online services");

        // Preemptive send basic auth header, or we will be redirected for oauth login
        clientConfig.property(ApacheClientProperties.PREEMPTIVE_BASIC_AUTHENTICATION, true);
    }

    clientConfig.property(ClientProperties.REQUEST_ENTITY_PROCESSING, RequestEntityProcessing.BUFFERED);

    if (System.getProperty(PROXY_URL_PROPERTY) != null) {
        clientConfig.property(ClientProperties.PROXY_URI, System.getProperty(PROXY_URL_PROPERTY));
        clientConfig.property(ApacheClientProperties.SSL_CONFIG, getSslConfigurator());
    }

    clientConfig.property(ApacheClientProperties.CREDENTIALS_PROVIDER, credentialsProvider);
    clientConfig.connectorProvider(new ApacheConnectorProvider());

    return ClientBuilder.newClient(clientConfig);
}

From source file:com.datatorrent.stram.util.WebServicesClient.java

private static void setupUserPassAuthScheme(AuthScheme scheme, String httpScheme, AuthSchemeProvider provider,
        ConfigProvider configuration) {//from w  ww  . ja  v  a2s  . c om
    String username = configuration.getProperty(scheme, "username");
    String password = configuration.getProperty(scheme, "password");
    if ((username != null) && (password != null)) {
        LOG.info("Setting up scheme {}", scheme);
        AuthScope authScope = new AuthScope(AuthScope.ANY_HOST, AuthScope.ANY_PORT, AuthScope.ANY_REALM,
                httpScheme);
        Credentials credentials = new UsernamePasswordCredentials(username, password);
        setupHttpAuthScheme(httpScheme, provider, authScope, credentials);
    } else if ((username != null) || (password != null)) {
        LOG.warn("Not setting up scheme {}, missing credentials {}", scheme,
                (username == null) ? "username" : "password");
    }
}

From source file:eu.diacron.crawlservice.app.Util.java

public static String getCrawlStatusById(String crawlid) {

    String status = "";
    System.out.println("get crawlid");

    CredentialsProvider credsProvider = new BasicCredentialsProvider();
    credsProvider.setCredentials(new AuthScope(AuthScope.ANY_HOST, AuthScope.ANY_PORT),
            new UsernamePasswordCredentials(Configuration.REMOTE_CRAWLER_USERNAME,
                    Configuration.REMOTE_CRAWLER_PASS));

    CloseableHttpClient httpclient = HttpClients.custom().setDefaultCredentialsProvider(credsProvider).build();
    try {//from ww  w .  ja  va 2  s  . com
        //HttpGet httpget = new HttpGet("http://diachron.hanzoarchives.com/crawl/" + crawlid);
        HttpGet httpget = new HttpGet(Configuration.REMOTE_CRAWLER_URL_CRAWL + crawlid);

        System.out.println("Executing request " + httpget.getRequestLine());
        CloseableHttpResponse response = httpclient.execute(httpget);
        try {
            System.out.println("----------------------------------------");
            System.out.println(response.getStatusLine());
            System.out.println("----------------------------------------");

            String result = "";

            BufferedReader in = new BufferedReader(new InputStreamReader(response.getEntity().getContent()));
            String inputLine;
            while ((inputLine = in.readLine()) != null) {
                System.out.println(inputLine);
                result += inputLine;
            }
            in.close();

            // TO-DO should be removed in the future and handle it more gracefully
            result = result.replace("u'", "'");
            result = result.replace("'", "\"");

            JSONObject crawljson = new JSONObject(result);
            System.out.println("myObject " + crawljson.toString());

            status = crawljson.getString("status");

            EntityUtils.consume(response.getEntity());
        } catch (JSONException ex) {
            Logger.getLogger(Util.class.getName()).log(Level.SEVERE, null, ex);
        } finally {
            response.close();
        }
    } catch (IOException ex) {
        Logger.getLogger(Util.class.getName()).log(Level.SEVERE, null, ex);
    } finally {
        try {
            httpclient.close();
        } catch (IOException ex) {
            Logger.getLogger(Util.class.getName()).log(Level.SEVERE, null, ex);
        }
    }

    return status;
}

From source file:net.bioclipse.dbxp.business.DbxpManager.java

public static Map<String, String> authenticate() throws IOException, NoSuchAlgorithmException {
    DefaultHttpClient httpclient = new DefaultHttpClient();
    httpclient.getCredentialsProvider().setCredentials(new AuthScope(AuthScope.ANY_HOST, AuthScope.ANY_PORT),
            new UsernamePasswordCredentials(userName, password));

    List<NameValuePair> formparams = new ArrayList<NameValuePair>();
    HashMap<String, String> formvars = new HashMap<String, String>();
    formvars.put("deviceID", getDeviceId());
    HttpResponse response = postValues(formvars, baseApiUrl + "authenticate");
    BufferedReader stdInput = new BufferedReader(new InputStreamReader(response.getEntity().getContent()));
    String json = "";
    String s = "";
    while ((s = stdInput.readLine()) != null) {
        json += s;/*from ww w.  j  a va 2  s .c o  m*/
    }

    Gson gson = new Gson();
    Map<String, String> loginData = gson.fromJson(json, new TypeToken<Map<String, String>>() {
    }.getType());

    token = loginData.get("token");
    sequence = Integer.valueOf(loginData.get("sequence"));

    return loginData;
}

From source file:com.ibm.twitter.TwitterInsights.java

public Sentiment getSentimentCount(String bookTitle, String bookAuthor, String sentimentType) {
    SentimentSearch returnedSentiment = new SentimentSearch();

    try {//from   w  ww  .  j ava  2s .co  m
        CredentialsProvider credentialsProvider = new BasicCredentialsProvider();
        credentialsProvider.setCredentials(new AuthScope(AuthScope.ANY_HOST, AuthScope.ANY_PORT),
                new UsernamePasswordCredentials(usernameTwitter, passwordTwitter));

        CookieStore cookieStore = new BasicCookieStore();
        CookieSpecProvider csf = new CookieSpecProvider() {
            @Override
            public CookieSpec create(HttpContext context) {
                return new DefaultCookieSpec() {
                    @Override
                    public void validate(Cookie cookie, CookieOrigin origin) throws MalformedCookieException {
                        // Allow all cookies
                    }
                };
            }
        };

        RequestConfig requestConfig = RequestConfig.custom().setCookieSpec("easy").setSocketTimeout(15 * 1000)
                .setConnectTimeout(15 * 1000).build();

        CloseableHttpClient httpClient = HttpClientBuilder.create()
                .setDefaultCredentialsProvider(credentialsProvider).setDefaultCookieStore(cookieStore)
                .setDefaultCookieSpecRegistry(RegistryBuilder.<CookieSpecProvider>create()
                        .register(CookieSpecs.DEFAULT, csf).register("easy", csf).build())
                .setDefaultRequestConfig(requestConfig).build();

        URIBuilder builder = new URIBuilder();
        builder.setScheme("https").setHost(baseURLTwitter).setPath("/api/v1/messages/count").setParameter("q",
                "\"" + bookTitle + "\"" + " AND " + "\"" + bookAuthor + "\"" + " AND " + "sentiment:"
                        + sentimentType);
        URI uri = builder.build();
        HttpGet httpGet = new HttpGet(uri);

        httpGet.setHeader("Content-Type", "text/plain");
        HttpResponse httpResponse = httpClient.execute(httpGet);

        if (httpResponse.getStatusLine().getStatusCode() == 200) {
            BufferedReader rd = new BufferedReader(
                    new InputStreamReader(httpResponse.getEntity().getContent(), "UTF-8"));

            // Read all the books from the best seller list
            ObjectMapper mapper = new ObjectMapper();
            returnedSentiment = mapper.readValue(rd, SentimentSearch.class);
        } else {
            logger.error("could not get tweets from IBM insights http code {}",
                    httpResponse.getStatusLine().getStatusCode());
        }

    } catch (Exception e) {
        logger.error("Twitter error: {}", e.getMessage());
    }

    return new Sentiment(sentimentType, returnedSentiment.getCount());
}

From source file:org.megam.api.http.TransportMachinery.java

public static TransportResponse get(TransportTools nuts)
        throws URISyntaxException, ClientProtocolException, IOException {

    DefaultHttpClient httpclient = new DefaultHttpClient();
    HttpGet httpget = new HttpGet(nuts.urlString());
    if (nuts.headers() != null) {
        for (Map.Entry<String, String> headerEntry : nuts.headers().entrySet()) {

            //this if condition is set for twilio Rest API to add credentials to DefaultHTTPClient, conditions met twilio work.
            if (headerEntry.getKey().equalsIgnoreCase("provider")
                    & headerEntry.getValue().equalsIgnoreCase(nuts.headers().get("provider"))) {
                httpclient.getCredentialsProvider().setCredentials(
                        new AuthScope(AuthScope.ANY_HOST, AuthScope.ANY_PORT), new UsernamePasswordCredentials(
                                nuts.headers().get("account_sid"), nuts.headers().get("oauth_token")));
            }/*from   www  .j a  v a 2s .c  om*/
            //this else part statements for other providers
            else {
                httpget.addHeader(headerEntry.getKey(), headerEntry.getValue());
            }
        }
    }

    if (nuts.isQuery()) {
        URIBuilder uribuilder = new URIBuilder(nuts.urlString());
        uribuilder.setQuery(URLEncodedUtils.format(nuts.pairs(), nuts.encoding()));
        httpget.setURI(uribuilder.build());
    }

    TransportResponse transportResp = null;
    try {
        HttpResponse httpResp = httpclient.execute(httpget);
        transportResp = new TransportResponse(httpResp.getStatusLine(), httpResp.getEntity(),
                httpResp.getLocale());
    } finally {
        httpget.releaseConnection();
    }

    return transportResp;

}

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 {//w w  w. j a v  a 2  s .  com
        LOG.debug("Basic authentication for ES not activated");
        return new DefaultHttpClient(getClientConnectionManager());
    }
}