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:eu.diacron.crawlservice.app.Util.java

public static JSONArray getwarcsByCrawlid(String crawlid) {

    JSONArray warcsArray = null;//from  w  w w  .  j  av  a 2 s. c o m
    System.out.println("get crawlid");

    CredentialsProvider credsProvider = new BasicCredentialsProvider();
    /*        credsProvider.setCredentials(
     new AuthScope(AuthScope.ANY_HOST, AuthScope.ANY_PORT),
     new UsernamePasswordCredentials("diachron", "7nD9dNGshTtficn"));
     */

    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 {

        //HttpGet httpget = new HttpGet("http://diachron.hanzoarchives.com/warcs/" + crawlid);
        HttpGet httpget = new HttpGet(Configuration.REMOTE_CRAWLER_URL + 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();

            result = result.replace("u'", "'");
            result = result.replace("'", "\"");

            warcsArray = new JSONArray(result);

            for (int i = 0; i < warcsArray.length(); i++) {

                System.out.println("url to download: " + warcsArray.getString(i));

            }

            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 warcsArray;
}

From source file:com.streamreduce.util.HTTPUtils.java

/**
 * Opens a connection to the specified URL with the supplied username and password,
 * if supplied, and then reads the contents of the URL.
 *
 * @param url             the url to open and read from
 * @param method          the method to use for the request
 * @param data            the request body as string
 * @param mediaType       the media type of the request
 * @param username        the username, if any
 * @param password        the password, if any
 * @param requestHeaders  the special request headers to send
 * @param responseHeaders save response headers
 * @return the read string from the//from w  w w.  j  av a  2s  .c  om
 * @throws InvalidCredentialsException if the connection credentials are invalid
 * @throws IOException                 if there is a problem with the request
 */
public static String openUrl(String url, String method, String data, String mediaType,
        @Nullable String username, @Nullable String password, @Nullable List<Header> requestHeaders,
        @Nullable List<Header> responseHeaders) throws InvalidCredentialsException, IOException {

    String response = null;

    /* Set the cookie policy */
    httpClient.getParams().setParameter(ClientPNames.COOKIE_POLICY, CookiePolicy.BROWSER_COMPATIBILITY);

    /* Set the user agent */
    httpClient.getParams().setParameter(CoreProtocolPNames.USER_AGENT, Constants.NODEABLE_HTTP_USER_AGENT);

    HttpContext context = new BasicHttpContext();
    HttpRequestBase httpMethod;

    if (method.equals("DELETE")) {
        httpMethod = new HttpDelete(url);
    } else if (method.equals("GET")) {
        httpMethod = new HttpGet(url);
    } else if (method.equals("POST")) {
        httpMethod = new HttpPost(url);
    } else if (method.equals("PUT")) {
        httpMethod = new HttpPut(url);
    } else {
        throw new IllegalArgumentException("The method you specified is not supported.");
    }

    // Put data into the request for POST and PUT requests
    if (method.equals("POST") || method.equals("PUT") && data != null) {
        HttpEntityEnclosingRequestBase eeMethod = (HttpEntityEnclosingRequestBase) httpMethod;

        eeMethod.setEntity(new StringEntity(data, ContentType.create(mediaType, "UTF-8")));
    }

    /* Set the username/password if any */
    if (username != null) {
        CredentialsProvider credentialsProvider = new BasicCredentialsProvider();
        credentialsProvider.setCredentials(new AuthScope(AuthScope.ANY_HOST, AuthScope.ANY_PORT),
                new UsernamePasswordCredentials(username, password));
        context.setAttribute(ClientContext.CREDS_PROVIDER, credentialsProvider);
    }

    /* Add request headers if need be */
    if (requestHeaders != null) {
        for (Header header : requestHeaders) {
            httpMethod.addHeader(header);
        }
    }

    LOGGER.debug("Making HTTP request as " + (username != null ? username : "anonymous") + ": " + method + " - "
            + url);

    /* Make the request and read the response */
    try {
        HttpResponse httpResponse = httpClient.execute(httpMethod);
        HttpEntity entity = httpResponse.getEntity();
        if (entity != null) {
            response = EntityUtils.toString(entity);
        }
        int responseCode = httpResponse.getStatusLine().getStatusCode();
        if (responseCode == 401 || responseCode == 403) {
            throw new InvalidCredentialsException("The connection credentials are invalid.");
        } else if (responseCode < 200 || responseCode > 299) {
            throw new IOException(
                    "Unexpected status code of " + responseCode + " for a " + method + " request to " + url);
        }

        if (responseHeaders != null) {
            responseHeaders.addAll(Arrays.asList(httpResponse.getAllHeaders()));
        }
    } catch (IOException e) {
        httpMethod.abort();
        throw e;
    }

    return response;
}

From source file:net.gromgull.android.bibsonomyposter.BibsonomyPosterActivity.java

public void bookmark(String url, String title) throws ClientProtocolException, IOException {
    CredentialsProvider credProvider = new BasicCredentialsProvider();

    credProvider.setCredentials(new AuthScope(AuthScope.ANY_HOST,

            AuthScope.ANY_PORT, AuthScope.ANY_REALM), new UsernamePasswordCredentials(username, apikey));

    StringWriter sw = new StringWriter();

    XmlSerializer x = Xml.newSerializer();
    x.setOutput(sw);//from  w w w  .j ava2  s  .  com
    x.startDocument(null, null);
    x.startTag(null, "bibsonomy");
    x.startTag(null, "post");
    x.attribute(null, "description", "a bookmark");

    x.startTag(null, "user");
    x.attribute(null, "name", username);
    x.endTag(null, "user");

    x.startTag(null, "tag");
    x.attribute(null, "name", "from_android");
    x.endTag(null, "tag");

    x.startTag(null, "group");
    x.attribute(null, "name", "public");
    x.endTag(null, "group");

    x.startTag(null, "bookmark");
    x.attribute(null, "url", url);
    x.attribute(null, "title", title);
    x.endTag(null, "bookmark");

    x.endTag(null, "post");
    x.endTag(null, "bibsonomy");

    x.endDocument();

    Log.v(LOGTAG, "XML: " + sw.toString());

    HttpPost httppost = new HttpPost("http://www.bibsonomy.org/api/users/" + username + "/posts");
    StringEntity e = new StringEntity(sw.toString());
    e.setContentEncoding(new BasicHeader(HTTP.CONTENT_TYPE, "application/xml"));
    httppost.setEntity(e);

    DefaultHttpClient httpclient = new DefaultHttpClient();
    httpclient.setCredentialsProvider(credProvider);
    HttpResponse response = httpclient.execute(httppost);
    Log.i(LOGTAG, "Bibsonomy said :" + response.getStatusLine());
    if (response.getStatusLine().getStatusCode() != 201) {
        HttpEntity re = response.getEntity();
        byte b[] = new byte[(int) re.getContentLength()];
        re.getContent().read(b);
        Log.v(LOGTAG, "Bibsonomy said: " + new String(b));
        throw new IOException("Bibsonomy said :" + response.getStatusLine());

    }
}

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

/**
 * Add authentication credentials// w  w  w  .  j a  va  2s. co m
 */
public <T extends Client> T addCredentials(String target, String realm, String scheme, Credentials credentials)
        throws URISyntaxException {
    String host = AuthScope.ANY_HOST;
    int port = AuthScope.ANY_PORT;
    if (target != null) {
        URI uri = new URI(target);
        host = uri.getHost();
        port = uri.getPort();
    }
    HttpHost targetHost = new HttpHost(host, port, scheme);
    getDefaultHttpClient().getCredentialsProvider()
            .setCredentials(new AuthScope(targetHost.getHostName(), targetHost.getPort(),
                    realm != null ? realm : AuthScope.ANY_REALM,
                    scheme != null ? scheme : AuthScope.ANY_SCHEME), credentials);
    return (T) this;
}

From source file:org.mumod.util.HttpManager.java

public void setCredentials(String username, String password) {

    Credentials defaultcreds = new UsernamePasswordCredentials(username, password);
    String host = AuthScope.ANY_HOST;
    if (mHost != null)
        host = mHost;//from   w w w.  j av  a2s  .  c o m
    BasicCredentialsProvider cP = new BasicCredentialsProvider();
    cP.setCredentials(new AuthScope(host, AuthScope.ANY_PORT, AuthScope.ANY_REALM), defaultcreds);
    mClient.setCredentialsProvider(cP);
    mClient.addRequestInterceptor(preemptiveAuth, 0);

}

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

public TweetList getTweetList(String bookTitle, String bookAuthor) {
    TweetList returnedTweets = new TweetList();

    try {//  w  w w  .  j av  a2  s  .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(10 * 1000)
                .setConnectTimeout(10 * 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/search")
                .setParameter("q", "\"" + bookTitle + "\"" + " AND " + "\"" + bookAuthor + "\"")
                .setParameter("size", "5");
        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();
            returnedTweets = mapper.readValue(rd, TweetList.class);
        }
    } catch (Exception e) {
        logger.error("Twitter error: {}", e.getMessage());
    }

    return returnedTweets;
}

From source file:com.logsniffer.event.publisher.http.HttpPublisher.java

/**
 * Init method for this publisher./*from   ww w.j  av a2  s  . c  o  m*/
 * 
 * @param velocityRenderer
 *            the velocityRenderer to set
 * @param httpClient
 *            http client
 */
protected void init(final VelocityEventRenderer velocityRenderer, final HttpClient httpClient) {
    this.velocityRenderer = velocityRenderer;
    this.httpClient = httpClient;
    if (getHttpAuthentication() != null) {
        CredentialsProvider credsProvider = new BasicCredentialsProvider();
        credsProvider.setCredentials(new AuthScope(AuthScope.ANY_HOST, AuthScope.ANY_PORT),
                new UsernamePasswordCredentials(getHttpAuthentication().getUsername(),
                        getHttpAuthentication().getPassword()));
        // Add AuthCache to the execution context
        HttpClientContext context = HttpClientContext.create();
        context.setCredentialsProvider(credsProvider);
    }
}

From source file:com.hardincoding.sonar.subsonic.service.SubsonicMusicService.java

public void setCredentials(final String username, final String password) {
    mUsername = username;//from w  w  w  .j  a  v a2  s  . co m
    mPassword = password;

    AuthScope auth = new AuthScope(AuthScope.ANY_HOST, AuthScope.ANY_PORT);
    Credentials credentials = new UsernamePasswordCredentials(username, password);
    mHttpClient.getCredentialsProvider().setCredentials(auth, credentials);
}

From source file:com.jive.myco.seyren.core.util.graphite.GraphiteHttpClient.java

private HttpClient createHttpClient() {
    HttpClientBuilder clientBuilder = HttpClientBuilder.create().setConnectionManager(createConnectionManager())
            .setDefaultRequestConfig(RequestConfig.custom()
                    .setConnectionRequestTimeout(graphiteConnectionRequestTimeout)
                    .setConnectTimeout(graphiteConnectTimeout).setSocketTimeout(graphiteSocketTimeout).build());

    // Set auth header for graphite if username and password are provided
    if (!StringUtils.isEmpty(graphiteUsername) && !StringUtils.isEmpty(graphitePassword)) {
        CredentialsProvider credentialsProvider = new BasicCredentialsProvider();
        credentialsProvider.setCredentials(new AuthScope(AuthScope.ANY_HOST, AuthScope.ANY_PORT),
                new UsernamePasswordCredentials(graphiteUsername, graphitePassword));
        clientBuilder.setDefaultCredentialsProvider(credentialsProvider);
        context.setAttribute("preemptive-auth", new BasicScheme());
        clientBuilder.addInterceptorFirst(new PreemptiveAuth());
    }//from  w  w  w  . j a  va  2  s  . c o  m

    return clientBuilder.build();
}

From source file:com.intuit.tank.httpclient4.TankHttpClient4.java

@Override
public void addAuth(AuthCredentials creds) {
    String host = (StringUtils.isBlank(creds.getHost()) || "*".equals(creds.getHost())) ? AuthScope.ANY_HOST
            : creds.getHost();/*from  w ww .j  a  v  a 2s  .  c o  m*/
    String realm = (StringUtils.isBlank(creds.getRealm()) || "*".equals(creds.getRealm())) ? AuthScope.ANY_REALM
            : creds.getRealm();
    int port = NumberUtils.toInt(creds.getPortString(), AuthScope.ANY_PORT);
    String scheme = creds.getScheme() != null ? creds.getScheme().getRepresentation() : AuthScope.ANY_SCHEME;
    AuthScope scope = new AuthScope(host, port, realm, scheme);
    if (AuthScheme.NTLM == creds.getScheme()) {
        context.getCredentialsProvider().setCredentials(scope,
                new NTCredentials(creds.getUserName(), creds.getPassword(), "tank-test", creds.getRealm()));
    } else {
        context.getCredentialsProvider().setCredentials(scope,
                new UsernamePasswordCredentials(creds.getUserName(), creds.getPassword()));
    }

}