List of usage examples for org.apache.http.client.protocol HttpClientContext create
public static HttpClientContext create()
From source file:org.callimachusproject.client.HttpUriClient.java
@Override protected CloseableHttpResponse doExecute(HttpHost target, HttpRequest request, HttpContext context) throws IOException, ClientProtocolException { HttpClientContext ctx;/*from www . j a va2s. c o m*/ if (context == null) { ctx = HttpClientContext.create(); } else { ctx = HttpClientContext.adapt(context); } if (ctx.getCookieStore() == null) { ctx.setCookieStore(new BasicCookieStore()); } HttpResponse response = getDelegate().execute(target, request, ctx); if (response instanceof CloseableHttpResponse) { return (CloseableHttpResponse) response; } else { return new HttpUriResponse(getSystemId(ctx).toASCIIString(), response); } }
From source file:fi.vm.kapa.identification.shibboleth.extattribute.ShibbolethExtAttributeConnector.java
@Nullable @Override/*from ww w. j a v a 2s . co m*/ protected Map<String, IdPAttribute> doDataConnectorResolve( @Nonnull AttributeResolutionContext attributeResolutionContext, @Nonnull AttributeResolverWorkContext attributeResolverWorkContext) throws ResolutionException { Map<String, IdPAttribute> attributes = new HashMap<>(); logger.debug("Trying to resolve attributes from adapter REST URL: " + adapterUrl); String token = attributeResolutionContext.getPrincipal(); logger.debug("Using token: '{}' to fetch session attributes", token); try { String attributeCallUrl = adapterUrl + "?token=" + token; CloseableHttpClient httpClient = HttpClients.createDefault(); HttpGet getMethod = new HttpGet(attributeCallUrl); HttpContext context = HttpClientContext.create(); CloseableHttpResponse restResponse = httpClient.execute(getMethod, context); int status = restResponse.getStatusLine().getStatusCode(); logger.debug("Response code from adapter HTTP " + status); if (status == HTTP_OK) { Gson gson = new Gson(); Map<String, String> attributeMap = gson.fromJson(EntityUtils.toString(restResponse.getEntity()), new TypeToken<Map<String, String>>() { }.getType()); if (attributeMap != null) { logger.debug("Attribute map size: {}", attributeMap.size()); attributeMap.keySet().forEach(key -> { String value = attributeMap.get(key); logger.debug("--attribute key: {}, attribute value: {}", key, value); if (StringUtils.isNotBlank(value)) { IdPAttribute idPAttribute = new IdPAttribute(key); List<IdPAttributeValue<String>> values = new ArrayList<>(); values.add(new StringAttributeValue(value)); idPAttribute.setValues(values); attributes.put(key, idPAttribute); } }); } else { logger.warn("Attribute fetch OK but no content was found"); } } else { logger.warn("No attributes found for session"); } } catch (Exception e) { logger.error("Error in connection to Adapter", e); } return attributes; }
From source file:org.keycloak.testsuite.crossdc.ConcurrentLoginCrossDCTest.java
@Test public void concurrentLoginWithRandomDcFailures() throws Throwable { log.info("*********************************************"); long start = System.currentTimeMillis(); AtomicReference<String> userSessionId = new AtomicReference<>(); LoginTask loginTask = null;// w ww. ja v a 2s . co m try (CloseableHttpClient httpClient = HttpClientBuilder.create() .setRedirectStrategy(new LaxRedirectStrategy()).build()) { loginTask = new LoginTask(httpClient, userSessionId, LOGIN_TASK_DELAY_MS, LOGIN_TASK_RETRIES, false, Arrays.asList(createHttpClientContextForUser(httpClient, "test-user@localhost", "password"))); HttpUriRequest request = handleLogin( getPageContent(oauth.getLoginFormUrl(), httpClient, HttpClientContext.create()), "test-user@localhost", "password"); log.debug("Executing login request"); org.junit.Assert.assertTrue( parseAndCloseResponse(httpClient.execute(request)).contains("<title>AUTH_RESPONSE</title>")); run(DEFAULT_THREADS, DEFAULT_CLIENTS_COUNT, loginTask, new SwapDcAvailability()); int clientSessionsCount = testingClient.testing().getClientSessionsCountInUserSession("test", userSessionId.get()); org.junit.Assert.assertEquals(1 + DEFAULT_CLIENTS_COUNT, clientSessionsCount); } finally { long end = System.currentTimeMillis() - start; log.infof("Statistics: %s", loginTask == null ? "??" : loginTask.getHistogram()); log.info("concurrentLoginWithRandomDcFailures took " + (end / 1000) + "s"); log.info("*********************************************"); } }
From source file:org.nekorp.workflow.desktop.rest.util.RestTemplateFactory.java
@PostConstruct public void init() { targetHost = new HttpHost(host, port, protocol); //connectionPool = new PoolingHttpClientConnectionManager(); //connectionPool.setDefaultMaxPerRoute(10); //connectionPool.setMaxTotal(20); CredentialsProvider credsProvider = new BasicCredentialsProvider(); credsProvider.setCredentials(new AuthScope(targetHost.getHostName(), targetHost.getPort()), new UsernamePasswordCredentials(username, password)); //wildcard ssl certificate SSLContext sslContext = SSLContexts.createDefault(); SSLConnectionSocketFactory sslsf = new SSLConnectionSocketFactory(sslContext, NoopHostnameVerifier.INSTANCE); httpclient = HttpClients.custom().setDefaultCredentialsProvider(credsProvider) //.setConnectionManager(connectionPool) .setSSLSocketFactory(sslsf).build(); // 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 localContext = HttpClientContext.create(); localContext.setAuthCache(authCache); HttpComponentsClientHttpRequestFactory factory = new HttpComponentsClientHttpRequestFactoryBasicAuth( httpclient, localContext);/* w ww .j a va 2 s. co m*/ this.template = new RestTemplate(); template.getMessageConverters().add(new BufferedImageHttpMessageConverter()); template.setRequestFactory(factory); }
From source file:tools.devnull.boteco.client.rest.impl.DefaultRestClient.java
private RestConfiguration execute(HttpRequestBase request) { return new DefaultRestConfiguration(HttpClients.createDefault(), HttpClientContext.create(), request, configuration);//from w w w. j a v a 2 s. co m }
From source file:com.mirth.connect.plugins.httpauth.oauth2.OAuth2Authenticator.java
@Override public AuthenticationResult authenticate(RequestInfo request) throws Exception { OAuth2HttpAuthProperties properties = getReplacedProperties(request); CloseableHttpClient client = null;//ww w .j a v a2 s . co m CloseableHttpResponse response = null; try { // Create and configure the client and context RegistryBuilder<ConnectionSocketFactory> socketFactoryRegistry = RegistryBuilder .<ConnectionSocketFactory>create() .register("http", PlainConnectionSocketFactory.getSocketFactory()); ConnectorPluginProperties pluginProperties = null; if (CollectionUtils.isNotEmpty(properties.getConnectorPluginProperties())) { pluginProperties = properties.getConnectorPluginProperties().iterator().next(); } provider.getHttpConfiguration().configureSocketFactoryRegistry(pluginProperties, socketFactoryRegistry); BasicHttpClientConnectionManager httpClientConnectionManager = new BasicHttpClientConnectionManager( socketFactoryRegistry.build()); httpClientConnectionManager.setSocketConfig(SocketConfig.custom().setSoTimeout(SOCKET_TIMEOUT).build()); HttpClientBuilder clientBuilder = HttpClients.custom() .setConnectionManager(httpClientConnectionManager); HttpUtil.configureClientBuilder(clientBuilder); client = clientBuilder.build(); HttpClientContext context = HttpClientContext.create(); RequestConfig requestConfig = RequestConfig.custom().setConnectTimeout(SOCKET_TIMEOUT) .setSocketTimeout(SOCKET_TIMEOUT).setStaleConnectionCheckEnabled(true).build(); context.setRequestConfig(requestConfig); URIBuilder uriBuilder = new URIBuilder(properties.getVerificationURL()); // Add query parameters if (properties.getTokenLocation() == TokenLocation.QUERY) { List<String> paramList = request.getQueryParameters().get(properties.getLocationKey()); if (CollectionUtils.isNotEmpty(paramList)) { for (String value : paramList) { uriBuilder.addParameter(properties.getLocationKey(), value); } } } // Build the final URI and create a GET request HttpGet httpGet = new HttpGet(uriBuilder.build()); // Add headers if (properties.getTokenLocation() == TokenLocation.HEADER) { List<String> headerList = request.getHeaders().get(properties.getLocationKey()); if (CollectionUtils.isNotEmpty(headerList)) { for (String value : headerList) { httpGet.addHeader(properties.getLocationKey(), value); } } } // Execute the request response = client.execute(httpGet, context); // Determine authentication from the status code if (response.getStatusLine().getStatusCode() < 400) { return AuthenticationResult.Success(); } else { return AuthenticationResult.Failure(); } } finally { HttpClientUtils.closeQuietly(response); HttpClientUtils.closeQuietly(client); } }
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 w ww .j a v a 2 s . co m*/ localContext = HttpClientContext.create(); localContext.setAuthCache(authCache); }
From source file:org.wildfly.test.integration.elytron.http.AbstractMechTestBase.java
@Test public void testUnauthorized() throws Exception { HttpGet request = new HttpGet(new URI(url.toExternalForm() + "role1")); HttpClientContext context = HttpClientContext.create(); try (CloseableHttpClient httpClient = HttpClients.createDefault()) { try (CloseableHttpResponse response = httpClient.execute(request, context)) { int statusCode = response.getStatusLine().getStatusCode(); assertEquals("Unexpected status code in HTTP response.", SC_UNAUTHORIZED, statusCode); }/*from ww w .ja v a 2 s . co m*/ } }
From source file:org.hawkular.client.RestFactory.java
public T createAPI(URI uri, String userName, String password) { HttpClient httpclient = null;//from w w w . j a va 2 s.c o 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.sonar.runner.Main.java
Main(Exit exit, Cli cli, Conf conf, RunnerFactory runnerFactory) { this.exit = exit; this.cli = cli; this.conf = conf; this.runnerFactory = runnerFactory; // apache http client setup this.httpCookieStore = new BasicCookieStore(); this.globalConfig = RequestConfig.custom().setCookieSpec(CookieSpecs.BROWSER_COMPATIBILITY).build(); this.httpClientContext = HttpClientContext.create(); this.httpClientContext.setCookieStore(httpCookieStore); this.httpClientBuilder = HttpClientBuilder.create().setDefaultRequestConfig(globalConfig) .setDefaultCookieStore(httpCookieStore); }