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.datatorrent.stram.util.WebServicesClient.java

private static void setupUserPassAuthScheme(AuthScheme scheme, String httpScheme, AuthSchemeProvider provider,
        ConfigProvider configuration) {//from  www . j  a  v  a 2 s . c o  m
    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 {/* w w w. ja v a 2s.  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  av  a2s  .  co  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:ca.sqlpower.wabit.enterprise.client.ServerInfoProvider.java

private static void init(String host, String port, String path, String username, String password)
        throws IOException {

    URL serverInfoUrl = toServerInfoURL(host, port, path);
    if (version.containsKey(generateServerKey(host, port, path, username, password)))
        return;//  ww  w.  j  a  v a 2s  .c om

    try {
        HttpParams params = new BasicHttpParams();
        HttpConnectionParams.setConnectionTimeout(params, 2000);
        DefaultHttpClient httpClient = new DefaultHttpClient(params);
        httpClient.setCookieStore(WabitClientSession.getCookieStore());
        httpClient.getCredentialsProvider().setCredentials(
                new AuthScope(serverInfoUrl.getHost(), AuthScope.ANY_PORT),
                new UsernamePasswordCredentials(username, password));

        HttpUriRequest request = new HttpOptions(serverInfoUrl.toURI());
        String responseBody = httpClient.execute(request, new BasicResponseHandler());

        // Decode the message
        String serverVersion;
        Boolean licensedServer;
        final String watermarkMessage;
        try {
            JSONObject jsonObject = new JSONObject(responseBody);
            serverVersion = jsonObject.getString(ServerProperties.SERVER_VERSION.toString());
            licensedServer = jsonObject.getBoolean(ServerProperties.SERVER_LICENSED.toString());
            watermarkMessage = jsonObject.getString(ServerProperties.SERVER_WATERMARK_MESSAGE.toString());
        } catch (JSONException e) {
            throw new IOException(e.getMessage());
        }

        // Save found values
        version.put(generateServerKey(host, port, path, username, password), new Version(serverVersion));
        licenses.put(generateServerKey(host, port, path, username, password), licensedServer);
        watermarkMessages.put(generateServerKey(host, port, path, username, password), watermarkMessage);

        // Notify the user if the server is not licensed.
        if (!licensedServer) {
            SwingUtilities.invokeLater(new Runnable() {
                public void run() {
                    JOptionPane.showMessageDialog(null, watermarkMessage, "SQL Power Wabit Server License",
                            JOptionPane.WARNING_MESSAGE);
                }
            });
        }

        // Now get the available fonts.
        URL serverFontsURL = toServerFontsURL(host, port, path);
        HttpUriRequest fontsRequest = new HttpGet(serverFontsURL.toURI());
        String fontsResponseBody = httpClient.execute(fontsRequest, new BasicResponseHandler());
        try {
            JSONArray fontsArray = new JSONArray(fontsResponseBody);
            List<String> fontNames = new ArrayList<String>();
            for (int i = 0; i < fontsArray.length(); i++) {
                fontNames.add(fontsArray.getString(i));
            }
            // Sort the list.
            Collections.sort(fontNames);
            fonts.put(generateServerKey(host, port, path, username, password), fontNames);
        } catch (JSONException e) {
            throw new IOException(e.getMessage());
        }

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

From source file:com.ibm.streamsx.topology.internal.context.AnalyticsServiceStreamsContext.java

private CloseableHttpClient createHttpClient(JSONObject credentials) {

    UsernamePasswordCredentials upc = new UsernamePasswordCredentials(credentials.get("userid").toString(),
            credentials.get("password").toString());
    CredentialsProvider credsProvider = new BasicCredentialsProvider();
    credsProvider.setCredentials(new AuthScope(credentials.get("rest_host").toString(), AuthScope.ANY_PORT),
            upc);//from w w w  . j a v  a  2s  . co m
    CloseableHttpClient httpClient = HttpClients.custom().setDefaultCredentialsProvider(credsProvider).build();
    return httpClient;
}

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

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

    try {//w ww  . j a v  a  2s . c o  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 . ja v a2 s  .  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:com.seyren.core.service.checker.GraphiteTargetChecker.java

/**
 * Set auth header for graphite if username and password are provided
 *///from  w w  w .  j av a  2s.c  o  m
private void setAuthHeadersIfNecessary() {
    if (!StringUtils.isEmpty(graphiteUsername) && !StringUtils.isEmpty(graphitePassword)) {
        CredentialsProvider credsProvider = new BasicCredentialsProvider();
        credsProvider.setCredentials(new AuthScope(graphiteHost, AuthScope.ANY_PORT),
                new UsernamePasswordCredentials(graphiteUsername, graphitePassword));
        if (client instanceof AbstractHttpClient) {
            ((AbstractHttpClient) client).setCredentialsProvider(credsProvider);
        }
    }
}

From source file:com.github.egonw.rrdf.RJenaHelper.java

public static StringMatrix sparqlRemoteNoJena(String endpoint, String queryString, String user, String password)
        throws Exception {
    StringMatrix table = null;/*w w  w . java2 s .c  om*/

    // use Apache for doing the SPARQL query
    DefaultHttpClient httpclient = new DefaultHttpClient();

    // Set credentials on the client
    if (user != null) {
        URL endpointURL = new URL(endpoint);
        CredentialsProvider credsProvider = new BasicCredentialsProvider();
        credsProvider.setCredentials(new AuthScope(endpointURL.getHost(), AuthScope.ANY_PORT),
                new UsernamePasswordCredentials(user, password));
        httpclient.setCredentialsProvider(credsProvider);
    }

    List<NameValuePair> formparams = new ArrayList<NameValuePair>();
    formparams.add(new BasicNameValuePair("query", queryString));
    UrlEncodedFormEntity entity = new UrlEncodedFormEntity(formparams, "UTF-8");
    HttpPost httppost = new HttpPost(endpoint);
    httppost.setEntity(entity);
    HttpResponse response = httpclient.execute(httppost);
    StatusLine statusLine = response.getStatusLine();
    int statusCode = statusLine.getStatusCode();
    if (statusCode != 200)
        throw new HttpException(
                "Expected HTTP 200, but got a " + statusCode + ": " + statusLine.getReasonPhrase());

    HttpEntity responseEntity = response.getEntity();
    InputStream in = responseEntity.getContent();

    // now the Jena part
    ResultSet results = ResultSetFactory.fromXML(in);
    // also use Jena for getting the prefixes...
    Query query = QueryFactory.create(queryString);
    PrefixMapping prefixMap = query.getPrefixMapping();
    table = convertIntoTable(prefixMap, results);

    in.close();
    return table;
}