List of usage examples for org.apache.http.client.protocol HttpClientContext create
public static HttpClientContext create()
From source file:com.redhat.jenkins.nodesharing.RestEndpoint.java
private @Nonnull HttpClientContext getAuthenticatingContext(@Nonnull HttpRequestBase method) { AuthCache authCache = new BasicAuthCache(); BasicScheme basicAuth = new BasicScheme(); authCache.put(URIUtils.extractHost(method.getURI()), basicAuth); CredentialsProvider provider = new BasicCredentialsProvider(); provider.setCredentials(AuthScope.ANY, new org.apache.http.auth.UsernamePasswordCredentials( creds.getUsername(), creds.getPassword().getPlainText())); HttpClientContext context = HttpClientContext.create(); context.setCredentialsProvider(provider); context.setAuthCache(authCache);// www .ja v a 2 s .c o m return context; }
From source file:org.opensaml.security.httpclient.HttpClientSecuritySupportTest.java
@Test public void testSetContextValue() { String attribName = "MyAttrib"; HttpClientContext context = null;//from w w w . j ava 2s . c o m // Empty context context = HttpClientContext.create(); HttpClientSecuritySupport.setContextValue(context, attribName, "foo", false); Assert.assertEquals(context.getAttribute(attribName), "foo"); // Empty context, null value context = HttpClientContext.create(); HttpClientSecuritySupport.setContextValue(context, attribName, null, false); Assert.assertNull(context.getAttribute(attribName)); // Don't replace existing context = HttpClientContext.create(); context.setAttribute(attribName, "bar"); HttpClientSecuritySupport.setContextValue(context, attribName, "foo", false); Assert.assertEquals(context.getAttribute(attribName), "bar"); // Replace existing context = HttpClientContext.create(); context.setAttribute(attribName, "bar"); HttpClientSecuritySupport.setContextValue(context, attribName, "foo", true); Assert.assertEquals(context.getAttribute(attribName), "foo"); // Don't replace because null value context = HttpClientContext.create(); context.setAttribute(attribName, "bar"); HttpClientSecuritySupport.setContextValue(context, attribName, null, true); Assert.assertEquals(context.getAttribute(attribName), "bar"); try { HttpClientSecuritySupport.setContextValue(null, attribName, "foo", false); Assert.fail("Null context value"); } catch (ConstraintViolationException e) { // Expected } try { context = HttpClientContext.create(); HttpClientSecuritySupport.setContextValue(context, null, "foo", false); Assert.fail("Null attribute name"); } catch (ConstraintViolationException e) { // Expected } }
From source file:com.srotya.collectd.storm.StormNimbusMetrics.java
@Override public int config(OConfigItem config) { nimbusAddresses = new ArrayList<>(); String jaasPath = "jaas.conf"; List<OConfigItem> children = config.getChildren(); for (OConfigItem child : children) { switch (child.getKey().toLowerCase()) { case "address": for (OConfigValue nimbus : child.getValues()) { try { new URI(nimbus.toString()); } catch (Exception e) { Collectd.logError("Bad URI " + nimbus + " for Nimbus, error:" + e.getMessage()); return -1; }//from w w w . j a v a 2 s. com nimbusAddresses.add(nimbus.getString()); } break; case "kerberos": kerberos = child.getValues().get(0).getBoolean(); break; case "jaas": jaasPath = child.getValues().get(0).getString(); break; } } Collectd.logInfo("Storm Nimbus Plugin: using following Nimbuses:" + nimbusAddresses); Collectd.logInfo("Storm Nimbus Plugin: using kerberos:" + kerberos); builder = HttpClientBuilder.create(); context = HttpClientContext.create(); if (kerberos) { System.setProperty("java.security.auth.login.config", jaasPath); System.setProperty("java.security.krb5.conf", "/etc/krb5.conf"); System.setProperty("javax.security.auth.useSubjectCredsOnly", "true"); login(); Lookup<AuthSchemeProvider> authSchemeRegistry = RegistryBuilder.<AuthSchemeProvider>create() .register(AuthSchemes.SPNEGO, new SPNegoSchemeFactory(true)).build(); builder.setDefaultAuthSchemeRegistry(authSchemeRegistry); BasicCredentialsProvider credentialsProvider = new BasicCredentialsProvider(); // This may seem odd, but specifying 'null' as principal tells java // to // use the logged in user's credentials Credentials useJaasCreds = new Credentials() { public String getPassword() { return null; } public Principal getUserPrincipal() { return null; } }; credentialsProvider.setCredentials(new AuthScope(null, -1, null), useJaasCreds); context.setCredentialsProvider(credentialsProvider); } else { subject = Subject.getSubject(AccessController.getContext()); } return 0; }
From source file:org.apache.hadoop.gateway.GatewayMultiFuncTest.java
@Test(timeout = TestUtils.MEDIUM_TIMEOUT) public void testPostWithContentTypeKnox681() throws Exception { LOG_ENTER();/* w w w .ja v a 2 s. c om*/ MockServer mock = new MockServer("REPEAT", true); params = new Properties(); params.put("MOCK_SERVER_PORT", mock.getPort()); params.put("LDAP_URL", "ldap://localhost:" + ldapTransport.getAcceptor().getLocalAddress().getPort()); String topoStr = TestUtils.merge(DAT, "topologies/test-knox678-utf8-chars-topology.xml", params); File topoFile = new File(config.getGatewayTopologyDir(), "knox681.xml"); FileUtils.writeStringToFile(topoFile, topoStr); topos.reloadTopologies(); mock.expect().method("PUT").pathInfo("/repeat-context/").respond().status(HttpStatus.SC_CREATED) .content("{\"name\":\"value\"}".getBytes()).contentLength(-1) .contentType("application/json; charset=UTF-8").header("Location", gatewayUrl + "/knox681/repeat"); String uname = "guest"; String pword = uname + "-password"; HttpHost targetHost = new HttpHost("localhost", gatewayPort, "http"); CredentialsProvider credsProvider = new BasicCredentialsProvider(); credsProvider.setCredentials(new AuthScope(targetHost.getHostName(), targetHost.getPort()), new UsernamePasswordCredentials(uname, pword)); AuthCache authCache = new BasicAuthCache(); BasicScheme basicAuth = new BasicScheme(); authCache.put(targetHost, basicAuth); HttpClientContext context = HttpClientContext.create(); context.setCredentialsProvider(credsProvider); context.setAuthCache(authCache); CloseableHttpClient client = HttpClients.createDefault(); HttpPut request = new HttpPut(gatewayUrl + "/knox681/repeat"); request.addHeader("X-XSRF-Header", "jksdhfkhdsf"); request.addHeader("Content-Type", "application/json"); CloseableHttpResponse response = client.execute(request, context); assertThat(response.getStatusLine().getStatusCode(), is(HttpStatus.SC_CREATED)); assertThat(response.getFirstHeader("Location").getValue(), endsWith("/gateway/knox681/repeat")); assertThat(response.getFirstHeader("Content-Type").getValue(), is("application/json; charset=UTF-8")); String body = new String(IOUtils.toByteArray(response.getEntity().getContent()), Charset.forName("UTF-8")); assertThat(body, is("{\"name\":\"value\"}")); response.close(); client.close(); mock.expect().method("PUT").pathInfo("/repeat-context/").respond().status(HttpStatus.SC_CREATED) .content("<test-xml/>".getBytes()).contentType("application/xml; charset=UTF-8") .header("Location", gatewayUrl + "/knox681/repeat"); client = HttpClients.createDefault(); request = new HttpPut(gatewayUrl + "/knox681/repeat"); request.addHeader("X-XSRF-Header", "jksdhfkhdsf"); request.addHeader("Content-Type", "application/xml"); response = client.execute(request, context); assertThat(response.getStatusLine().getStatusCode(), is(HttpStatus.SC_CREATED)); assertThat(response.getFirstHeader("Location").getValue(), endsWith("/gateway/knox681/repeat")); assertThat(response.getFirstHeader("Content-Type").getValue(), is("application/xml; charset=UTF-8")); body = new String(IOUtils.toByteArray(response.getEntity().getContent()), Charset.forName("UTF-8")); assertThat(the(body), hasXPath("/test-xml")); response.close(); client.close(); mock.stop(); LOG_EXIT(); }
From source file:com.cloud.utils.rest.RESTServiceConnectorTest.java
@Test public void testExecuteRetrieveObject() throws Exception { final TestPojo existingObject = new TestPojo(); existingObject.setField("existingValue"); final String newObjectJson = gson.toJson(existingObject); final CloseableHttpResponse response = mock(CloseableHttpResponse.class); when(response.getEntity()).thenReturn(new StringEntity(newObjectJson)); when(response.getStatusLine()).thenReturn(HTTP_200_STATUS_LINE); final CloseableHttpClient httpClient = mock(CloseableHttpClient.class); when(httpClient.execute(any(HttpHost.class), any(HttpRequest.class), any(HttpClientContext.class))) .thenReturn(response);/*from w w w . j a va 2 s. c om*/ final RestClient restClient = new BasicRestClient(httpClient, HttpClientContext.create(), "localhost"); final RESTServiceConnector connector = new RESTServiceConnector.Builder().client(restClient).build(); final TestPojo object = connector.executeRetrieveObject(TestPojo.class, "/somepath"); assertThat(object, notNullValue()); assertThat(object, equalTo(existingObject)); verify(httpClient).execute(any(HttpHost.class), HttpUriRequestMethodMatcher.aMethod("GET"), any(HttpClientContext.class)); verify(response).close(); }
From source file:edu.lternet.pasta.doi.EzidRegistrar.java
/** * Registers the resource DOI based on the DataCite metadata object. * //from ww w . j a va 2s . c o m * @throws EzidException */ public void registerDataCiteMetadata() throws EzidException { if (this.dataCiteMetadata == null) { String gripe = "registerDataCiteMetadata: DataCite metadata object is null."; throw new EzidException(gripe); } HttpHost httpHost = new HttpHost(this.host, Integer.valueOf(this.port), this.protocol); CloseableHttpClient httpClient = HttpClientBuilder.create().build(); AuthScope authScope = new AuthScope(httpHost.getHostName(), httpHost.getPort()); UsernamePasswordCredentials credentials = new UsernamePasswordCredentials(this.ezidUser, this.ezidPassword); CredentialsProvider credentialsProvider = new BasicCredentialsProvider(); credentialsProvider.setCredentials(authScope, credentials); // 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 HttpClientContext context = HttpClientContext.create(); context.setCredentialsProvider(credentialsProvider); context.setAuthCache(authCache); String doi = this.dataCiteMetadata.getDigitalObjectIdentifier().getDoi(); String url = this.getEzidUrl("/id/" + doi); StringBuffer metadata = new StringBuffer(""); metadata.append("datacite: " + this.dataCiteMetadata.toDataCiteXml() + "\n"); metadata.append("_target: " + this.dataCiteMetadata.getLocationUrl() + "\n"); HttpPut httpPut = new HttpPut(url); httpPut.setHeader("Content-type", "text/plain"); HttpEntity stringEntity = null; Integer statusCode = null; String entityString = null; try { stringEntity = new StringEntity(metadata.toString()); httpPut.setEntity(stringEntity); HttpResponse httpResponse = httpClient.execute(httpHost, httpPut, context); statusCode = httpResponse.getStatusLine().getStatusCode(); HttpEntity httpEntity = httpResponse.getEntity(); entityString = EntityUtils.toString(httpEntity); } catch (UnsupportedEncodingException e) { logger.error(e.getMessage()); e.printStackTrace(); } catch (ClientProtocolException e) { logger.error(e.getMessage()); e.printStackTrace(); } catch (IOException e) { logger.error(e.getMessage()); e.printStackTrace(); } finally { closeHttpClient(httpClient); } logger.info("registerDataCiteMetadata: " + this.dataCiteMetadata.getLocationUrl() + "\n" + entityString); // Test for DOI collision or DOI registration failure if ((statusCode == HttpStatus.SC_BAD_REQUEST) && (entityString != null) && (entityString.contains("identifier already exists"))) { String gripe = "identifier already exists"; throw new EzidException(gripe); } else if (statusCode != HttpStatus.SC_CREATED) { logger.error(this.dataCiteMetadata.toDataCiteXml()); String gripe = "DOI registration failed for: " + doi; throw new EzidException(gripe); } }
From source file:org.cleverbus.core.common.ws.transport.http.CloseableHttpComponentsMessageSender.java
/** * Template method that allows for creation of a {@link HttpContext} for the given uri. Default implementation * returns {@code null}./* www .j a v a2 s . co m*/ * * @param uri the uri to create the context for * @return the context, or {@code null} */ @Override protected HttpContext createContext(URI uri) { // Add AuthCache to the execution context HttpClientContext context = HttpClientContext.create(); context.setCredentialsProvider(credentialsProvider); context.setAuthCache(authCache.get()); return context; }
From source file:org.keycloak.testsuite.saml.LogoutTest.java
@Test public void testFrontchannelLogoutWithRedirectUrlDifferentBrowser() throws ParsingException, ConfigurationException, ProcessingException { adminClient.realm(REALM_NAME).clients().get(sales2Rep.getId()) .update(ClientBuilder.edit(sales2Rep).frontchannelLogout(true) .removeAttribute(SamlProtocol.SAML_SINGLE_LOGOUT_SERVICE_URL_POST_ATTRIBUTE) .attribute(SamlProtocol.SAML_SINGLE_LOGOUT_SERVICE_URL_REDIRECT_ATTRIBUTE, "http://url") .build());// w ww . jav a 2s. c om Document logoutDoc = prepareLogoutFromSalesAfterLoggingIntoTwoApps(); samlClient.execute((client, context, strategy) -> { HttpUriRequest post = POST.createSamlUnsignedRequest(getAuthServerSamlEndpoint(REALM_NAME), null, logoutDoc); CloseableHttpResponse response = client.execute(post, HttpClientContext.create()); assertThat(response, statusCodeIsHC(Response.Status.OK)); return response; }); }
From source file:org.callimachusproject.client.HttpClientRedirectTest.java
@Test public void testRedirectFromFragment() throws Exception { register("*", new SimpleService()); register("/People.htm", new HttpRequestHandler() { public void handle(HttpRequest request, HttpResponse response, HttpContext context) throws HttpException, IOException { response.setStatusCode(HttpStatus.SC_MOVED_PERMANENTLY); response.setHeader("Location", "/people.html"); final StringEntity entity = new StringEntity("Whatever"); response.setEntity(entity);//w w w . j av a 2 s . c o m } }); final HttpHost target = getServerHttp(); final HttpGet httpget = new HttpGet("/People.htm#tim"); final HttpClientContext context = HttpClientContext.create(); final HttpResponse response = this.httpclient.execute(target, httpget, context); Assert.assertEquals(HttpStatus.SC_OK, response.getStatusLine().getStatusCode()); EntityUtils.consume(response.getEntity()); final HttpRequest request = context.getRequest(); Assert.assertEquals("/people.html", request.getRequestLine().getUri()); final URI uri = new URIBuilder().setHost(target.getHostName()).setPort(target.getPort()) .setScheme(target.getSchemeName()).setPath("/people.html").setFragment("tim").build(); final URI location = getHttpLocation(httpget, context); Assert.assertEquals(uri, location); }
From source file:org.lokra.seaweedfs.core.Connection.java
/** * Fetch http API json result./*from w ww .j av a2s.c o m*/ * * @param request Http request. * @return Json fetch by http response. * @throws IOException Http connection is fail or server response within some error message. */ JsonResponse fetchJsonResultByRequest(HttpRequestBase request) throws IOException { CloseableHttpResponse response = null; request.setHeader("Connection", "close"); JsonResponse jsonResponse = null; try { response = httpClient.execute(request, HttpClientContext.create()); HttpEntity entity = response.getEntity(); jsonResponse = new JsonResponse(EntityUtils.toString(entity), response.getStatusLine().getStatusCode()); EntityUtils.consume(entity); } finally { if (response != null) { try { response.close(); } catch (IOException ignored) { } } request.releaseConnection(); } if (jsonResponse.json.contains("\"error\":\"")) { Map map = objectMapper.readValue(jsonResponse.json, Map.class); final String errorMsg = (String) map.get("error"); if (errorMsg != null) throw new SeaweedfsException(errorMsg); } return jsonResponse; }