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

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

Introduction

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

Prototype

public AuthScope(final String host, final int port) 

Source Link

Document

Creates a new credentials scope for the given host, port, any realm name, and any authentication scheme.

Usage

From source file:org.codice.alliance.nsili.endpoint.requests.FtpDestinationSink.java

@Override
public void writeFile(InputStream fileData, long size, String name, String contentType,
        List<Metacard> metacards) throws IOException {
    CloseableHttpClient httpClient = null;
    String urlPath = protocol + "://" + fileLocation.host_name + ":" + port + "/" + fileLocation.path_name + "/"
            + name;//  www .  j a  v a  2 s. c  o  m

    LOGGER.debug("Writing ordered file to URL: {}", urlPath);

    try {
        HttpPut putMethod = new HttpPut(urlPath);
        putMethod.addHeader(HTTP.CONTENT_TYPE, contentType);
        HttpEntity httpEntity = new InputStreamEntity(fileData, size);
        putMethod.setEntity(httpEntity);

        if (StringUtils.isNotEmpty(fileLocation.user_name) && fileLocation.password != null) {
            CredentialsProvider credsProvider = new BasicCredentialsProvider();
            credsProvider.setCredentials(new AuthScope(fileLocation.host_name, port),
                    new UsernamePasswordCredentials(fileLocation.user_name, fileLocation.password));
            httpClient = HttpClients.custom().setDefaultCredentialsProvider(credsProvider).build();
        } else {
            httpClient = HttpClients.createDefault();
        }

        httpClient.execute(putMethod);
        fileData.close();
        putMethod.releaseConnection();
    } finally {
        if (httpClient != null) {
            httpClient.close();
        }
    }
}

From source file:com.arduino2fa.xbee.ReceivePacket.java

private ReceivePacket() throws Exception {
    XBee xbee = new XBee();

    int count = 0;
    int errors = 0;

    // Transmit stuff
    final int timeout = 5000;

    int ackErrors = 0;
    int ccaErrors = 0;
    int purgeErrors = 0;
    long now;/*from w w  w  .  ja  v  a 2 s  .c  o m*/

    // HTTP stuff
    CloseableHttpClient httpClient = HttpClientBuilder.create().build();
    HttpHost httpHost = new HttpHost("ec2-54-186-213-97.us-west-2.compute.amazonaws.com", 3000, "http");

    CredentialsProvider credentialsProvider = new BasicCredentialsProvider();
    credentialsProvider.setCredentials(new AuthScope(httpHost.getHostName(), httpHost.getPort()),
            new UsernamePasswordCredentials("admin", "admin") // TODO get from command line
    );

    // Create AuthCache instance
    AuthCache authCache = new BasicAuthCache();
    BasicScheme basicScheme = new BasicScheme();
    authCache.put(httpHost, basicScheme);

    // Add AuthCache to the execution context
    HttpClientContext httpClientContext = HttpClientContext.create();
    httpClientContext.setCredentialsProvider(credentialsProvider);
    httpClientContext.setAuthCache(authCache);

    HttpGet httpGet = new HttpGet("/token-requests/1");

    CloseableHttpResponse httpResponse;

    BufferedReader br;
    StringBuffer result;
    String line;

    try {
        // Connect to the XBee
        xbee.open(XbeeConfig.PORT, XbeeConfig.BAUD_RATE);

        now = System.currentTimeMillis();

        // Loop indefinitely; sleeps for a few seconds at the end of every iteration
        while (true) {

            // Check if there are queued tx requests on the server
            httpResponse = httpClient.execute(httpHost, httpGet, httpClientContext);
            br = new BufferedReader(new InputStreamReader(httpResponse.getEntity().getContent()));

            result = new StringBuffer();

            while ((line = br.readLine()) != null) {
                result.append(line);
            }

            // Check if the result is a JSON object
            if (result.charAt(0) != '{') {
                log.error("Result " + result.toString() + " is not a JSON object");
                continue;
            }

            JSONObject object = (JSONObject) JSONValue.parse(result.toString());

            if (object != null) {
                Long time = (Long) object.get("time");

                // Check if the request is a new one (created after last check)
                if (time > last) {
                    String token = (String) object.get("token");
                    byte[] tokenHex = SimpleCrypto.toByte(token);

                    int[] payload = new int[] { tokenHex[0], tokenHex[1], tokenHex[2] };

                    XBeeAddress16 destination = new XBeeAddress16(0xFF, 0xFF);
                    TxRequest16 tx = new TxRequest16(destination, payload);

                    try {
                        log.info("sending tx request with payload: " + token);
                        XBeeResponse response = xbee.sendSynchronous(tx, timeout);

                        if (response.getApiId() != ApiId.TX_STATUS_RESPONSE) {
                            log.debug("expected tx status but received " + response);
                        } else {
                            log.debug("got tx status");

                            if (((TxStatusResponse) response).getFrameId() != tx.getFrameId()) {
                                throw new RuntimeException("frame id does not match");
                            }

                            if (((TxStatusResponse) response).getStatus() != TxStatusResponse.Status.SUCCESS) {
                                errors++;

                                if (((TxStatusResponse) response).isAckError()) {
                                    ackErrors++;
                                } else if (((TxStatusResponse) response).isCcaError()) {
                                    ccaErrors++;
                                } else if (((TxStatusResponse) response).isPurged()) {
                                    purgeErrors++;
                                }

                                log.debug("Tx status failure with status: "
                                        + ((TxStatusResponse) response).getStatus());
                            } else {
                                // success
                                log.debug("Success.  count is " + count + ", errors is " + errors + ", in "
                                        + (System.currentTimeMillis() - now) + ", ack errors " + ackErrors
                                        + ", ccaErrors " + ccaErrors + ", purge errors " + purgeErrors);
                            }

                            count++;

                        }
                    } catch (XBeeTimeoutException e) {
                        e.printStackTrace();
                    }
                }
            }

            last = System.currentTimeMillis();
            httpGet.releaseConnection();

            // Delay
            Thread.sleep(2000);
        }
    } finally {
        xbee.close();
    }
}

From source file:org.jboss.as.test.integration.management.http.XCorrelationIdTestCase.java

@Before
public void before() throws Exception {

    this.url = new URL("http", managementClient.getMgmtAddress(), MGMT_PORT, MGMT_CTX);
    this.httpContext = new BasicHttpContext();
    CredentialsProvider credsProvider = new BasicCredentialsProvider();
    credsProvider.setCredentials(new AuthScope(url.getHost(), url.getPort()),
            new UsernamePasswordCredentials(Authentication.USERNAME, Authentication.PASSWORD));

    this.httpClient = HttpClients.custom().setDefaultCredentialsProvider(credsProvider).build();
}

From source file:com.cloudapp.rest.CloudApi.java

public CloudApi(String mail, String pw) {
    client = new DefaultHttpClient();
    client.setReuseStrategy(new DefaultConnectionReuseStrategy());

    // Try to authenticate.
    AuthScope scope = new AuthScope("my.cl.ly", 80);
    client.getCredentialsProvider().setCredentials(scope, new UsernamePasswordCredentials(mail, pw));
}

From source file:org.zalando.stups.tokens.CloseableHttpProvider.java

public CloseableHttpProvider(ClientCredentials clientCredentials, UserCredentials userCredentials,
        URI accessTokenUri, HttpConfig httpConfig) {
    this.userCredentials = userCredentials;
    this.accessTokenUri = accessTokenUri;
    requestConfig = RequestConfig.custom().setSocketTimeout(httpConfig.getSocketTimeout())
            .setConnectTimeout(httpConfig.getConnectTimeout())
            .setConnectionRequestTimeout(httpConfig.getConnectionRequestTimeout())
            .setStaleConnectionCheckEnabled(httpConfig.isStaleConnectionCheckEnabled()).build();

    // prepare basic auth credentials
    final CredentialsProvider credentialsProvider = new BasicCredentialsProvider();
    credentialsProvider.setCredentials(new AuthScope(accessTokenUri.getHost(), accessTokenUri.getPort()),
            new UsernamePasswordCredentials(clientCredentials.getId(), clientCredentials.getSecret()));

    client = HttpClients.custom().setDefaultCredentialsProvider(credentialsProvider).build();

    host = new HttpHost(accessTokenUri.getHost(), accessTokenUri.getPort(), accessTokenUri.getScheme());

    // enable basic auth for the request
    final AuthCache authCache = new BasicAuthCache();
    final BasicScheme basicAuth = new BasicScheme();
    authCache.put(host, basicAuth);/*from   www  .j a  v a2 s  . c o  m*/

    localContext = HttpClientContext.create();
    localContext.setAuthCache(authCache);
}

From source file:com.blazemeter.bamboo.plugin.api.HttpUtility.java

public HttpUtility() {
    this.httpClient = HttpClients.createDefault();
    useProxy = Boolean.parseBoolean(System.getProperty(Constants.USE_PROXY));
    proxyHost = System.getProperty(Constants.PROXY_HOST);

    try {/*from   w w  w.j ava 2  s .c o  m*/
        this.proxyPort = Integer.parseInt(System.getProperty(Constants.PROXY_PORT));
    } catch (NumberFormatException nfe) {
        logger.error("Failed to read http.proxyPort: ", nfe);
    }
    if (useProxy && !org.apache.commons.lang3.StringUtils.isBlank(this.proxyHost)) {
        this.proxy = new HttpHost(proxyHost, proxyPort);

        this.proxyUser = System.getProperty(Constants.PROXY_USER);
        this.proxyPass = System.getProperty(Constants.PROXY_PASS);
        if (!org.apache.commons.lang3.StringUtils.isEmpty(this.proxyUser)
                && !org.apache.commons.lang3.StringUtils.isEmpty(this.proxyPass)) {
            Credentials cr = new UsernamePasswordCredentials(proxyUser, proxyPass);
            AuthScope aus = new AuthScope(proxyHost, proxyPort);
            CredentialsProvider credsProvider = new BasicCredentialsProvider();
            credsProvider.setCredentials(aus, cr);
            this.httpClient = HttpClients.custom().setProxy(proxy).setDefaultCredentialsProvider(credsProvider)
                    .build();
        } else {
            this.httpClient = HttpClients.custom().setProxy(proxy).build();
        }
    }
}

From source file:org.openhab.binding.rwesmarthome.internal.communicator.util.HttpComponentsHelper.java

/**
 * prepare for the https connection/* ww w .ja v a2  s . c o m*/
 * call this in the constructor of the class that does the connection if
 * it's used multiple times
 */
private void setup() {
    SchemeRegistry schemeRegistry = new SchemeRegistry();

    // http scheme
    schemeRegistry.register(new Scheme("http", PlainSocketFactory.getSocketFactory(), 80));
    // https scheme
    schemeRegistry.register(new Scheme("https", new EasySSLSocketFactory(), 443));

    params = new BasicHttpParams();
    params.setParameter(ConnManagerPNames.MAX_TOTAL_CONNECTIONS, 1);
    params.setParameter(ConnManagerPNames.MAX_CONNECTIONS_PER_ROUTE, new ConnPerRouteBean(1));
    params.setParameter(CoreProtocolPNames.USE_EXPECT_CONTINUE, false);
    HttpProtocolParams.setVersion(params, HttpVersion.HTTP_1_1);
    HttpProtocolParams.setContentCharset(params, "utf8");

    CredentialsProvider credentialsProvider = new BasicCredentialsProvider();
    // set the user credentials for our site "example.com"
    credentialsProvider.setCredentials(new AuthScope("example.com", AuthScope.ANY_PORT),
            new UsernamePasswordCredentials("UserNameHere", "UserPasswordHere"));
    clientConnectionManager = new ThreadSafeClientConnManager(params, schemeRegistry);

    context = new BasicHttpContext();
    context.setAttribute("http.auth.credentials-provider", credentialsProvider);
}

From source file:com.cisco.cta.taxii.adapter.httpclient.CredentialsProviderFactory.java

private void addTaxiiCredentials(CredentialsProvider credsProvider) {
    URL url = settings.getPollEndpoint();
    HttpHost targetHost = new HttpHost(url.getHost(), url.getPort(), url.getProtocol());
    credsProvider.setCredentials(new AuthScope(targetHost.getHostName(), targetHost.getPort()),
            new UsernamePasswordCredentials(settings.getUsername(), settings.getPassword()));
}

From source file:es.tsb.ltba.nomhad.httpclient.NomhadHttpClient.java

/**
 * Set the credentials, if the client was created without them.
 * //from  w  w w . j a v a2 s  .  c om
 * @param usr
 *            user
 * @param pwd
 *            password
 */
public void setCredentials(String usr, String pwd) {
    httpClient.getCredentialsProvider().setCredentials(new AuthScope(AuthScope.ANY_HOST, AuthScope.ANY_PORT),
            new UsernamePasswordCredentials(usr, pwd));
}

From source file:org.metaeffekt.dcc.commons.ant.HttpRequestTask.java

/**
 * Executes the task.//from  w  ww  .j a v a 2 s  .  c  o  m
 * 
 * @see org.apache.tools.ant.Task#execute()
 */
@Override
public void execute() {

    StringBuilder sb = new StringBuilder();
    sb.append(serverScheme).append("://").append(serverHostName).append(':').append(serverPort);
    sb.append("/").append(uri);
    String url = sb.toString();

    BasicCredentialsProvider credentialsProvider = null;
    if (username != null) {
        log("User: " + username, Project.MSG_DEBUG);
        credentialsProvider = new BasicCredentialsProvider();
        credentialsProvider.setCredentials(new AuthScope(serverHostName, serverPort),
                new UsernamePasswordCredentials(username, password));
    }

    HttpClient httpClient = HttpClientBuilder.create().setDefaultCredentialsProvider(credentialsProvider)
            .build();

    try {
        switch (httpMethod) {
        case GET:
            HttpGet get = new HttpGet(url);
            doRequest(httpClient, get);
            break;
        case PUT:
            HttpPut put = new HttpPut(url);
            if (body == null) {
                body = "";
            }
            log("Setting body: " + body, Project.MSG_DEBUG);
            put.setEntity(new StringEntity(body, ContentType.create(contentType)));
            doRequest(httpClient, put);
            break;
        case POST:
            HttpPost post = new HttpPost(url);
            if (body == null) {
                body = "";
            }
            log("Setting body: " + body, Project.MSG_DEBUG);
            post.setEntity(new StringEntity(body, ContentType.create(contentType)));
            doRequest(httpClient, post);
            break;
        case DELETE:
            HttpDelete delete = new HttpDelete(url);
            doRequest(httpClient, delete);
            break;
        default:
            throw new IllegalArgumentException("HttpMethod " + httpMethod + " not supported!");
        }
    } catch (IOException e) {
        throw new BuildException(e);
    }
}