List of usage examples for org.apache.http.client AuthCache put
void put(HttpHost host, AuthScheme authScheme);
From source file:org.zenoss.app.consumer.metric.impl.MetricServicePoster.java
/** * Login to the ZAuth service using the zenoss credentials. Grab the tenant id from the http response and cache * the results for future requests.//from w ww .jav a2s .c o m * @return tenant id * @throws IOException */ String getTenantId() throws IOException { if (tenantId == null) { log.debug("Requesting tenant id"); // get the hostname and port from ProxyConfiguration ProxyConfiguration proxyConfig = configuration.getProxyConfiguration(); String hostname = proxyConfig.getHostname(); int port = proxyConfig.getPort(); //configure request HttpContext context = new BasicHttpContext(); HttpHost host = new HttpHost(hostname, port, "http"); HttpPost post = new HttpPost(AUTHENTICATE_URL); post.addHeader(ACCEPT, APPLICATION_JSON.toString()); //configure authentication String username = configuration.getZenossCredentials().getUsername(); String password = configuration.getZenossCredentials().getPassword(); if (!Strings.nullToEmpty(username).isEmpty()) { //configure credentials CredentialsProvider provider = new BasicCredentialsProvider(); provider.setCredentials(new AuthScope(host.getHostName(), host.getPort()), new UsernamePasswordCredentials(username, password)); context.setAttribute(ClientContext.CREDS_PROVIDER, provider); //setup auth cache AuthCache cache = new BasicAuthCache(); BasicScheme scheme = new BasicScheme(); cache.put(host, scheme); context.setAttribute(ClientContext.AUTH_CACHE, cache); } //handle response and collect tenantId HttpResponse response = null; try { response = httpClient.execute(host, post, context); StatusLine statusLine = response.getStatusLine(); int statusCode = statusLine.getStatusCode(); log.debug("Tenant id request complete with status: {}", statusCode); if (statusCode >= 200 && statusCode <= 299) { Header id = response.getFirstHeader(ZenossTenant.ID_HTTP_HEADER); if (id == null) { log.warn("Failed to get zauth tenant id after login"); throw new RuntimeException("Failed to get zauth tenant id after successful login"); } tenantId = id.getValue(); log.info("Got tenant id: {}", tenantId); } else { log.warn("Unsuccessful response from server: {}", response.getStatusLine()); throw new IOException("Login for tenantId failed"); } } catch (NullPointerException ex) { log.warn("npe retrieving tenantId: {}", ex); } finally { try { if (response != null) { response.getEntity().getContent().close(); } } catch (NullPointerException | IOException ex) { log.warn("Failed to close request: {}", ex); } } } return tenantId; }
From source file:cz.zcu.kiv.eegdatabase.logic.util.BasicAuthHttpClient.java
@Override protected HttpContext createHttpContext() { HttpContext context = super.createHttpContext(); AuthCache authCache = new BasicAuthCache(); // Generate BASIC scheme object and add it to the local auth cache BasicScheme basicAuth = new BasicScheme(); HttpHost targetHost = new HttpHost(url.getHost(), url.getPort(), url.getProtocol()); authCache.put(targetHost, basicAuth); context.setAttribute(ClientContext.AUTH_CACHE, authCache); return context; }
From source file:org.energy_home.jemma.utils.rest.RestClient.java
public void setCredential(String hostname, int port, String username, String password) { HttpHost httpHost = new HttpHost(hostname, port); httpClient.getCredentialsProvider().setCredentials(new AuthScope(hostname, port), new UsernamePasswordCredentials(username, password)); // Create AuthCache instance AuthCache authCache = new BasicAuthCache(); // Generate BASIC scheme object and add it to the local auth cache BasicScheme basicAuth = new BasicScheme(); authCache.put(httpHost, basicAuth); // Add AuthCache to the execution context httpContext.setAttribute(ClientContext.AUTH_CACHE, authCache); }
From source file:org.hawkular.client.core.jaxrs.RestFactory.java
public T createAPI(ClientInfo clientInfo) { final HttpClient httpclient; if (clientInfo.getEndpointUri().toString().startsWith("https")) { httpclient = getHttpClient();/*from w w w . j a v a2s. c o m*/ } else { httpclient = HttpClientBuilder.create().build(); } final ResteasyClient client; if (clientInfo.getUsername().isPresent() && clientInfo.getPassword().isPresent()) { HttpHost targetHost = new HttpHost(clientInfo.getEndpointUri().getHost(), clientInfo.getEndpointUri().getPort()); CredentialsProvider credsProvider = new BasicCredentialsProvider(); credsProvider.setCredentials(new AuthScope(targetHost.getHostName(), targetHost.getPort()), new UsernamePasswordCredentials(clientInfo.getUsername().get(), clientInfo.getPassword().get())); // Create AuthCache instance AuthCache authCache = new BasicAuthCache(); // Generate BASIC scheme object and add it to the local auth cache BasicScheme basicAuth = new BasicScheme(); authCache.put(targetHost, basicAuth); // Add AuthCache to the execution context HttpClientContext context = HttpClientContext.create(); context.setCredentialsProvider(credsProvider); context.setAuthCache(authCache); ApacheHttpClient4Engine engine = new ApacheHttpClient4Engine(httpclient, context); client = new ResteasyClientBuilder().httpEngine(engine).build(); } else { ApacheHttpClient4Engine engine = new ApacheHttpClient4Engine(getHttpClient()); client = new ResteasyClientBuilder().httpEngine(engine).build(); } client.register(JacksonJaxbJsonProvider.class); client.register(JacksonObjectMapperProvider.class); client.register(RequestLoggingFilter.class); client.register(new RequestHeadersFilter(clientInfo.getHeaders())); client.register(ResponseLoggingFilter.class); client.register(HCJacksonJson2Provider.class); client.register(ConvertersProvider.class); ProxyBuilder<T> proxyBuilder = client.target(clientInfo.getEndpointUri()).proxyBuilder(apiClassType); if (classLoader != null) { proxyBuilder = proxyBuilder.classloader(classLoader); } return proxyBuilder.build(); }
From source file:org.hawkular.client.RestFactory.java
public T createAPI(URI uri, String userName, String password) { HttpClient httpclient = null;//from w ww .j av a 2 s .co m if (uri.toString().startsWith("https")) { httpclient = getHttpClient(); } else { httpclient = HttpClientBuilder.create().build(); } ResteasyClient client = null; if (userName != null) { HttpHost targetHost = new HttpHost(uri.getHost(), uri.getPort()); CredentialsProvider credsProvider = new BasicCredentialsProvider(); credsProvider.setCredentials(new AuthScope(targetHost.getHostName(), targetHost.getPort()), new UsernamePasswordCredentials(userName, password)); // Create AuthCache instance AuthCache authCache = new BasicAuthCache(); // Generate BASIC scheme object and add it to the local auth cache BasicScheme basicAuth = new BasicScheme(); authCache.put(targetHost, basicAuth); // Add AuthCache to the execution context HttpClientContext context = HttpClientContext.create(); context.setCredentialsProvider(credsProvider); context.setAuthCache(authCache); ApacheHttpClient4Engine engine = new ApacheHttpClient4Engine(httpclient, context); client = new ResteasyClientBuilder().httpEngine(engine).build(); } else { ApacheHttpClient4Engine engine = new ApacheHttpClient4Engine(getHttpClient()); client = new ResteasyClientBuilder().httpEngine(engine).build(); } client.register(JacksonJaxbJsonProvider.class); client.register(JacksonObjectMapperProvider.class); client.register(RestRequestFilter.class); client.register(RestResponseFilter.class); client.register(HCJacksonJson2Provider.class); ProxyBuilder<T> proxyBuilder = client.target(uri).proxyBuilder(apiClassType); if (classLoader != null) { proxyBuilder = proxyBuilder.classloader(classLoader); } return proxyBuilder.build(); }
From source file:org.jboss.teiid.quickstart.PortfolioClient.java
public void resteasyHttpBackendClient() { System.out.println("\nResteasy Client API with HTTP client as engine"); HttpHost targetHost = new HttpHost("localhost", 8080, "http"); // 1. Create AuthCache instance AuthCache authCache = new BasicAuthCache(); // 2. Generate BASIC scheme object and add it to the local auth cache BasicScheme basicAuth = new BasicScheme(); authCache.put(targetHost, basicAuth); // 3. Add AuthCache to the execution context HttpClientContext localContext = HttpClientContext.create(); localContext.setAuthCache(authCache); // 4. Create client executor and proxy HttpClientBuilder builder = HttpClientBuilder.create(); CredentialsProvider credsProvider = new BasicCredentialsProvider(); AuthScope scope = new AuthScope(targetHost.getHostName(), targetHost.getPort()); UsernamePasswordCredentials credentials = new UsernamePasswordCredentials(USERNAME, PASSWORD); credsProvider.setCredentials(scope, credentials); builder.setDefaultCredentialsProvider(credsProvider); HttpClient httpClient = builder.build(); // 5. Create ResteasyClient with http client as engine ApacheHttpClient4Engine engine = new ApacheHttpClient4Engine(httpClient, localContext); ResteasyClient client = new ResteasyClientBuilder().httpEngine(engine).build(); // 6. Execute Rest call via ResteasyClient String authString = getBasicAuthentication(); for (String api : apis) { ResteasyWebTarget target = client.target(api); Response response = target.request().header(HttpHeaders.ACCEPT, MediaType.APPLICATION_XML) .header(HttpHeaders.AUTHORIZATION, authString).get(); if (response.getStatus() == 200) { String value = response.readEntity(String.class); System.out.println(value); response.close();//from w w w. java2 s.co m } else { handleError(response); } } }
From source file:org.sonatype.nexus.testsuite.security.nexus4257.Nexus4257CookieVerificationIT.java
/** * Makes a request after setting the user agent and verifies that the session cookie is NOT set. *///from ww w. j av a 2 s . com private void testCookieNotSetForKnownStateLessClients(final String userAgent) throws Exception { TestContext context = TestContainer.getInstance().getTestContext(); String username = context.getAdminUsername(); String password = context.getPassword(); String url = this.getBaseNexusUrl() + "content/"; URI uri = new URI(url); Header header = new BasicHeader("User-Agent", userAgent + "/1.6"); // user agent plus some version DefaultHttpClient httpClient = new DefaultHttpClient(); final BasicHttpContext localcontext = new BasicHttpContext(); final HttpHost targetHost = new HttpHost(uri.getHost(), uri.getPort(), uri.getScheme()); httpClient.getCredentialsProvider().setCredentials( new AuthScope(targetHost.getHostName(), targetHost.getPort()), new UsernamePasswordCredentials(username, password)); AuthCache authCache = new BasicAuthCache(); BasicScheme basicAuth = new BasicScheme(); authCache.put(targetHost, basicAuth); localcontext.setAttribute(ClientContext.AUTH_CACHE, authCache); HttpGet getMethod = new HttpGet(url); getMethod.addHeader(header); assertThat(executeAndRelease(httpClient, getMethod, localcontext), equalTo(200)); Cookie sessionCookie = this.getSessionCookie(httpClient.getCookieStore().getCookies()); assertThat("Session Cookie should not be set for user agent: " + userAgent, sessionCookie, nullValue()); }
From source file:org.apache.reef.runtime.hdinsight.client.yarnrest.HDInsightInstance.java
private HttpClientContext getClientContext(final String hostname, final String username, final String password) throws IOException { final HttpHost targetHost = new HttpHost(hostname, 443, "https"); final HttpClientContext result = HttpClientContext.create(); // Setup credentials provider final CredentialsProvider credentialsProvider = new BasicCredentialsProvider(); credentialsProvider.setCredentials(AuthScope.ANY, new UsernamePasswordCredentials(username, password)); result.setCredentialsProvider(credentialsProvider); // Setup preemptive authentication final AuthCache authCache = new BasicAuthCache(); final BasicScheme basicAuth = new BasicScheme(); authCache.put(targetHost, basicAuth); result.setAuthCache(authCache);/* www . java 2 s.com*/ final HttpGet httpget = new HttpGet("/"); // Prime the cache try (final CloseableHttpResponse response = this.httpClient.execute(targetHost, httpget, result)) { // empty try block used to automatically close resources } return result; }
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 www . j a v a 2 s. co 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(); } }