List of usage examples for org.apache.http.client.protocol HttpClientContext create
public static HttpClientContext create()
From source file:securitytools.veracode.VeracodeClient.java
/** * Constructs a new VeracodeClient using the specified configuration. * //from w ww. java2 s. c o m * @param credentials Credentials used to access Veracode services. * @param clientConfiguration Client configuration for options such as proxy * settings, user-agent header, and network timeouts. */ public VeracodeClient(VeracodeCredentials credentials, ClientConfiguration clientConfiguration) { CredentialsProvider credentialsProvider = new BasicCredentialsProvider(); credentialsProvider.setCredentials(new AuthScope(TARGET), credentials); AuthCache authCache = new BasicAuthCache(); authCache.put(TARGET, new BasicScheme()); context = HttpClientContext.create(); context.setCredentialsProvider(credentialsProvider); context.setAuthCache(authCache); try { client = HttpClientFactory.build(clientConfiguration); } catch (NoSuchAlgorithmException nsae) { throw new VeracodeClientException(nsae.getMessage(), nsae); } }
From source file:org.commonjava.util.jhttpc.HttpFactory.java
public HttpClientContext createContext(final SiteConfig location) throws JHttpCException { HttpClientContext ctx = HttpClientContext.create(); if (location != null) { final AuthScope as; try {/*ww w. j a v a2 s . com*/ as = new AuthScope(location.getHost(), location.getPort()); } catch (MalformedURLException e) { throw new JHttpCException( "Failed to parse site URL for host and port: %s (site id: %s). Reason: %s", e, location.getUri(), location.getId(), e.getMessage()); } if (location.getUser() != null) { if (authenticator != null) { ctx = authenticator.decoratePrototypeContext(as, location, PasswordType.USER, ctx); } } if (location.getProxyHost() != null && location.getProxyUser() != null) { if (authenticator != null) { ctx = authenticator.decoratePrototypeContext( new AuthScope(location.getProxyHost(), getProxyPort(location)), location, PasswordType.PROXY, ctx); } } } return ctx; }
From source file:fi.vm.kapa.identification.proxy.service.MetadataService.java
public void updateMetadataCache() { try {/*from w w w . j a v a2 s.c o m*/ approvedAuthenticationProviders = new ApprovedAuthenticationProviders(metadataServerUrl); CloseableHttpClient httpClient = HttpClients.createDefault(); final String serviceProviderMetadataReqUrl = metadataServerUrl + "?type=" + ProviderType.SERVICE_PROVIDER.toString(); logger.debug("url to metadata server: {}", serviceProviderMetadataReqUrl); HttpGet getMethod = new HttpGet(serviceProviderMetadataReqUrl); HttpContext context = HttpClientContext.create(); CloseableHttpResponse response = httpClient.execute(getMethod, context); // HttpEntity entity = response.getEntity(); // String content = EntityUtils.toString(entity); // logger.debug("HTTP Entity:" + content); int statusCode = response.getStatusLine().getStatusCode(); if (statusCode == HTTP_OK) { Gson gson = new Gson(); List<MetadataDTO> metadata = gson.fromJson(EntityUtils.toString(response.getEntity()), new TypeToken<List<MetadataDTO>>() { }.getType()); response.close(); if (!CollectionUtils.isEmpty(metadata)) { logger.debug("Clearing previous metadata cache, content size {}", serviceProviderMetaDataCache.size()); Map<String, MetadataDTO> newMetaDataCache = new HashMap<>(); metadata.forEach(data -> { MetadataDTO toCache = new MetadataDTO(); toCache.setEntityId(data.getEntityId()); logger.debug("data.getDbEntityIdAuthContextUrlByAuthProviderAuthContextUrl(): " + data.getEntityId()); toCache.setDnsName(data.getDnsName()); toCache.setLevelOfAssurance(data.getLevelOfAssurance()); toCache.setAttributeLevelOfAssurance(data.getAttributeLevelOfAssurance()); toCache.setAcsAddress(data.getAcsAddress()); toCache.setProviderType(data.getProviderType()); toCache.setSessionProfile(data.getSessionProfile()); toCache.setVtjVerificationRequired(data.isVtjVerificationRequired()); logger.debug("data.getAuthenticationMethods(): " + data.getAttributeLevelOfAssurance()); toCache.setAuthenticationProviderDTOList( approvedAuthenticationProviders.getByName(data.getAttributeLevelOfAssurance())); logger.debug("--adding metadata - ent ID: " + data.getEntityId() + ", dns: " + data.getDnsName() + ", permitted auth methods: " + data.getAttributeLevelOfAssurance() + ", type: " + data.getProviderType() + ", profile: " + data.getSessionProfile()); newMetaDataCache.put(data.getEntityId(), toCache); }); serviceProviderMetaDataCache = newMetaDataCache; // when done replace old with new } } else { logger.warn("Metadata server responded with HTTP {}", statusCode); response.close(); } } catch (Exception e) { logger.error("Error updating proxy metadata", e); } }
From source file:com.lifetime.util.TimeOffUtil.java
private static List<RepliconTimeOff> getTimeOffInfo(int page, int pageSize) throws IOException, ParseException { String url = "https://na5.replicon.com/liferay/services/" + "TimeOffListService1.svc/GetData"; CloseableHttpClient httpClient = HttpClients.createDefault(); CredentialsProvider provider = new BasicCredentialsProvider(); UsernamePasswordCredentials credential = new UsernamePasswordCredentials(COMPANY_NAME + '\\' + USERNAME, PASSWORD);//ww w . jav a 2 s . c o m provider.setCredentials(AuthScope.ANY, credential); HttpClientContext localContext = HttpClientContext.create(); localContext.setCredentialsProvider(provider); HttpPost httpRequest = new HttpPost(url); HttpEntity requestEntity = getTimeoffRequestEntity(page, pageSize); if (requestEntity != null) { httpRequest.setHeader("Content-type", "application/json"); httpRequest.setEntity(requestEntity); } CloseableHttpResponse response = httpClient.execute(httpRequest, localContext); HttpEntity entity = response.getEntity(); return createTimeOffList(EntityUtils.toString(entity)); }
From source file:com.ittm_solutions.ipacore.IpaApi.java
/** * Returns the http client context used for all connections to the IPA * server.//from w w w . j av a2s . c o m * <p> * This method initializes the http client context on its first call, * subsequent calls return the same instance. * * @return http client context */ private HttpClientContext clientContext() { if (hcContext == null) { // Create a local instance of cookie store CookieStore cookieStore = new BasicCookieStore(); // Create local HTTP context hcContext = HttpClientContext.create(); // Bind custom cookie store to the local context hcContext.setCookieStore(cookieStore); } return hcContext; }
From source file:org.pentaho.di.trans.ael.websocket.SessionConfigurator.java
private HttpContext getContext(URI uri) { HttpClientContext httpClientContext = HttpClientContext.create(); //used by httpclient version >= 4.3 httpClientContext.setAttribute(HttpClientContext.HTTP_ROUTE, new HttpRoute(new HttpHost(uri.getHost(), uri.getPort()))); //used by httpclient version 4.2 httpClientContext.setAttribute(HttpClientContext.HTTP_TARGET_HOST, new HttpHost(uri.getHost(), uri.getPort())); return httpClientContext; }
From source file:com.cloud.utils.rest.RESTServiceConnectorTest.java
@Test public void testExecuteCreateObject() throws Exception { final TestPojo newObject = new TestPojo(); newObject.setField("newValue"); final String newObjectJson = gson.toJson(newObject); 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 v a 2 s . com final RestClient restClient = new BasicRestClient(httpClient, HttpClientContext.create(), "localhost"); final RESTServiceConnector connector = new RESTServiceConnector.Builder().client(restClient).build(); final TestPojo object = connector.executeCreateObject(newObject, "/somepath"); assertThat(object, notNullValue()); assertThat(object, equalTo(newObject)); verify(httpClient).execute(any(HttpHost.class), HttpUriRequestMethodMatcher.aMethod("POST"), any(HttpClientContext.class)); verify(httpClient).execute(any(HttpHost.class), HttpUriRequestPayloadMatcher.aPayload(newObjectJson), any(HttpClientContext.class)); verify(response).close(); }
From source file:edu.lternet.pasta.doi.EzidRegistrar.java
/** * Login to the EZID web service API system and return a valid session * identifier./*from w w w. ja va 2 s . com*/ * * @return The EZID session id * @throws EzidException */ public void login() throws EzidException { String sessionId = null; /* * The following set of code sets up Preemptive Authentication for the HTTP * CLIENT and is done so at the warning stated within the Apache * Http-Components Client tutorial here: * http://hc.apache.org/httpcomponents- * client-ga/tutorial/html/authentication.html#d5e1031 */ 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 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); HttpGet httpGet = new HttpGet(this.getEzidUrl("/login")); HttpResponse response = null; Header[] headers = null; Integer statusCode = null; try { response = httpClient.execute(httpHost, httpGet, context); headers = response.getAllHeaders(); statusCode = (Integer) response.getStatusLine().getStatusCode(); logger.info("STATUS: " + statusCode.toString()); } catch (UnsupportedEncodingException e) { logger.error(e); e.printStackTrace(); } catch (ClientProtocolException e) { logger.error(e); e.printStackTrace(); } catch (IOException e) { logger.error(e); e.printStackTrace(); } finally { closeHttpClient(httpClient); } if (statusCode == HttpStatus.SC_OK) { String headerName = null; String headerValue = null; // Loop through all headers looking for the "Set-Cookie" header. for (int i = 0; i < headers.length; i++) { headerName = headers[i].getName(); if (headerName.equals("Set-Cookie")) { headerValue = headers[i].getValue(); sessionId = this.getSessionId(headerValue); logger.info("Session: " + sessionId); } } } else { String gripe = "login: failed EZID login."; throw new EzidException(gripe); } this.sessionId = sessionId; }
From source file:org.apache.geode.rest.internal.web.RestSecurityDUnitTest.java
private HttpResponse doRequest(HttpRequestBase request, String username, String password) throws MalformedURLException { HttpHost targetHost = new HttpHost(HOSTNAME, this.restPort, PROTOCOL); CloseableHttpClient httpclient = HttpClients.custom().build(); HttpClientContext clientContext = HttpClientContext.create(); // if username is null, do not put in authentication if (username != null) { CredentialsProvider credsProvider = new BasicCredentialsProvider(); credsProvider.setCredentials(new AuthScope(targetHost.getHostName(), targetHost.getPort()), new UsernamePasswordCredentials(username, password)); httpclient = HttpClients.custom().setDefaultCredentialsProvider(credsProvider).build(); AuthCache authCache = new BasicAuthCache(); BasicScheme basicAuth = new BasicScheme(); authCache.put(targetHost, basicAuth); clientContext.setCredentialsProvider(credsProvider); clientContext.setAuthCache(authCache); }//w w w .ja va 2 s .c o m try { return httpclient.execute(targetHost, request, clientContext); } catch (ClientProtocolException e) { e.printStackTrace(); fail("Rest GET should not have thrown ClientProtocolException!"); } catch (IOException e) { e.printStackTrace(); fail("Rest GET Request should not have thrown IOException!"); } return null; }
From source file:com.elastic.support.util.RestExec.java
public HttpClientContext getLocalContext(HttpHost httpHost) throws Exception { AuthCache authCache = new BasicAuthCache(); // Generate BASIC scheme object and add it to the local // auth cache BasicScheme basicAuth = new BasicScheme(); authCache.put(httpHost, basicAuth);//from www. jav a 2 s .c om HttpClientContext localContext = HttpClientContext.create(); localContext.setAuthCache(authCache); return localContext; }