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.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 ww.  jav a 2  s  .c o m
 * @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 a  v  a 2  s  .  co  m*/
    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/*from  w  w w .j a v  a 2 s  .  c  o 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:com.jfrog.bintray.client.impl.HttpClientConfigurator.java

/**
 * Ignores blank username input/* ww  w.ja va2 s .c o m*/
 */
public HttpClientConfigurator authentication(String username, String password) {
    if (StringUtils.isNotBlank(username)) {
        if (StringUtils.isBlank(host)) {
            throw new IllegalStateException("Cannot configure authentication when host is not set.");
        }
        credsProvider.setCredentials(new AuthScope(host, AuthScope.ANY_PORT, AuthScope.ANY_REALM),
                new UsernamePasswordCredentials(username, password));

        builder.addInterceptorFirst(new PreemptiveAuthInterceptor());
    }
    return 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;//www .  j  av  a2  s .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 ww. j  a  va 2 s .  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(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  w  w w . j  av  a 2  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 ww . j av a 2  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 ww .j  av  a 2s.  co  m

    return clientBuilder.build();
}

From source file:org.ttrssreader.net.deprecated.ApacheJSONConnector.java

@Override
public void init() {
    super.init();
    if (!httpAuth) {
        credProvider = null;//from  w ww.java 2  s. c  om
        return;
    }

    // Refresh Credentials-Provider
    if (httpUsername.equals(Constants.EMPTY) || httpPassword.equals(Constants.EMPTY)) {
        credProvider = null;
    } else {
        credProvider = new BasicCredentialsProvider();
        credProvider.setCredentials(new AuthScope(AuthScope.ANY_HOST, AuthScope.ANY_PORT),
                new UsernamePasswordCredentials(httpUsername, httpPassword));
    }
}