List of usage examples for org.apache.http.client.protocol HttpClientContext create
public static HttpClientContext create()
From source file:io.seldon.external.ExternalPluginServer.java
@Override public JsonNode execute(JsonNode payload, OptionsHolder options) { long timeNow = System.currentTimeMillis(); URI uri = URI.create(options.getStringOption(URL_PROPERTY_NAME)); try {// w w w .ja v a 2 s . c o m URIBuilder builder = new URIBuilder().setScheme("http").setHost(uri.getHost()).setPort(uri.getPort()) .setPath(uri.getPath()).setParameter("json", payload.toString()); uri = builder.build(); } catch (URISyntaxException e) { throw new APIException(APIException.GENERIC_ERROR); } HttpContext context = HttpClientContext.create(); HttpGet httpGet = new HttpGet(uri); try { if (logger.isDebugEnabled()) logger.debug("Requesting " + httpGet.getURI().toString()); CloseableHttpResponse resp = httpClient.execute(httpGet, context); if (resp.getStatusLine().getStatusCode() == 200) { JsonFactory factory = mapper.getJsonFactory(); JsonParser parser = factory.createJsonParser(resp.getEntity().getContent()); JsonNode actualObj = mapper.readTree(parser); if (logger.isDebugEnabled()) logger.debug( "External prediction server took " + (System.currentTimeMillis() - timeNow) + "ms"); return actualObj; } else { logger.error( "Couldn't retrieve prediction from external prediction server -- bad http return code: " + resp.getStatusLine().getStatusCode()); throw new APIException(APIException.GENERIC_ERROR); } } catch (IOException e) { logger.error("Couldn't retrieve prediction from external prediction server - ", e); throw new APIException(APIException.GENERIC_ERROR); } }
From source file:webfx.URLVerifier.java
private void discoverThroughHeaders() throws IOException, URISyntaxException { // relax redirections HttpGet httpGet = new HttpGet(location.toURI()); HttpClientContext httpcontext = HttpClientContext.create(); try (CloseableHttpResponse response = httpclient.execute(httpGet, httpcontext)) { // get mimetype via Content-Type http header Arrays.stream(response.getHeaders("Content-Type")).findFirst() .ifPresent(h -> this.contentType = h.getValue()); if (!Objects.isNull(contentType)) { contentType = contentType.contains(";") ? contentType.substring(0, contentType.indexOf(";")).trim() : contentType;//from w w w .j a v a2s . c om LOGGER.log(Level.INFO, "Final Content-Type: {0}", contentType); } else { LOGGER.log(Level.INFO, "Content-Type Header is Empty: {0}", Arrays.toString(response.getHeaders("Content-Type"))); // clear field b/c it was used inside lambda as temp var contentType = null; } // get filename via Content-Disposition http header Arrays.stream(response.getHeaders("Content-Disposition")).findFirst() .ifPresent(h -> this.pageName = h.getValue()); if (!Objects.isNull(pageName) && pageName.contains("filename=")) { pageName = pageName.substring(pageName.lastIndexOf("filename=") + 9); LOGGER.log(Level.INFO, "temporary page name: {0}", pageName); if (pageName.indexOf('.') > -1) { fileExtension = pageName.substring(pageName.indexOf('.') + 1).trim(); LOGGER.log(Level.INFO, "Final file extension: {0}", fileExtension); } pageName = pageName.substring(0, pageName.indexOf('.')).trim(); LOGGER.log(Level.INFO, "Final page name: {0}", pageName); } else { // clear field b/c it was used inside lambda as temp var pageName = null; } HttpHost target = httpcontext.getTargetHost(); List<URI> redirectLocations = httpcontext.getRedirectLocations(); URI _loc = URIUtils.resolve(httpGet.getURI(), target, redirectLocations); this.location = _loc.toURL(); LOGGER.log(Level.INFO, "Final HTTP location: {0}", _loc.toURL()); } }
From source file:gobblin.compaction.audit.PinotAuditCountHttpClient.java
/** * A thread-safe method which fetches a tier-to-count mapping. * The returned json object from Pinot contains below information * {//from www .j a va2s .c o m * "aggregationResults":[ * { * "groupByResult":[ * { * "value":"172765137.00000", * "group":[ * "kafka-08-tracking-local" * ] * } * ] * } * ], * "exceptions":[ * ] * ..... * } * @param datasetName name of dataset * @param start time start point in milliseconds * @param end time end point in milliseconds * @return A tier to record count mapping when succeeded. Otherwise a null value is returned */ public Map<String, Long> fetch(String datasetName, long start, long end) throws IOException { Map<String, Long> map = new HashMap<>(); String query = "select tier, sum(count) from kafkaAudit where " + "eventType=\"" + datasetName + "\" and " + "beginTimestamp >= \"" + start + "\" and " + "beginTimestamp < \"" + end + "\" group by tier"; String fullURL = targetUrl + URLEncoder.encode(query, Charsets.UTF_8.toString()); HttpGet req = new HttpGet(fullURL); String rst = null; HttpEntity entity = null; log.info("Full url for {} is {}", datasetName, fullURL); try { CloseableHttpResponse response = httpClient.execute(req, HttpClientContext.create()); int statusCode = response.getStatusLine().getStatusCode(); if (statusCode < 200 || statusCode >= 300) { throw new IOException(String.format("status code: %d, reason: %s", statusCode, response.getStatusLine().getReasonPhrase())); } entity = response.getEntity(); rst = EntityUtils.toString(entity); } finally { if (entity != null) { EntityUtils.consume(entity); } } JsonObject all = PARSER.parse(rst).getAsJsonObject(); JsonArray aggregationResults = all.getAsJsonArray("aggregationResults"); if (aggregationResults == null || aggregationResults.size() == 0) { log.error(all.toString()); throw new IOException("No aggregation results " + all.toString()); } JsonObject aggregation = (JsonObject) aggregationResults.get(0); JsonArray groupByResult = aggregation.getAsJsonArray("groupByResult"); if (groupByResult == null || groupByResult.size() == 0) { log.error(aggregation.toString()); throw new IOException("No aggregation results " + aggregation.toString()); } log.info("Audit count for {} is {}", datasetName, groupByResult); for (JsonElement ele : groupByResult) { JsonObject record = (JsonObject) ele; map.put(record.getAsJsonArray("group").get(0).getAsString(), (long) Double.parseDouble(record.get("value").getAsString())); } return map; }
From source file:org.ops4j.pax.web.itest.FormAuthenticationTest.java
@Test public void shouldDenyAccessOnWrongPassword() throws Exception { String path = String.format("http://localhost:%d/form/hello", getHttpPort()); CloseableHttpClient client = HttpClients.createDefault(); HttpClientContext context = HttpClientContext.create(); HttpGet httpGet = new HttpGet(path); HttpResponse response = client.execute(httpGet, context); int statusCode = response.getStatusLine().getStatusCode(); String text = EntityUtils.toString(response.getEntity()); assertThat(text, containsString("Login")); List<NameValuePair> formparams = new ArrayList<NameValuePair>(); formparams.add(new BasicNameValuePair("j_username", "mustermann")); formparams.add(new BasicNameValuePair("j_password", "wrong")); UrlEncodedFormEntity entity = new UrlEncodedFormEntity(formparams, "UTF-8"); path = String.format("http://localhost:%d/form/j_security_check", getHttpPort()); HttpPost httpPost = new HttpPost(path); httpPost.setEntity(entity);//from w ww .j a v a2 s . c o m response = client.execute(httpPost, context); statusCode = response.getStatusLine().getStatusCode(); assertThat(statusCode, is(200)); text = EntityUtils.toString(response.getEntity()); assertThat(text, containsString("failed")); }
From source file:com.cloud.utils.rest.RESTServiceConnectorTest.java
@Test public void testExecuteUpdateObjectWithParameters() throws Exception { final TestPojo newObject = new TestPojo(); newObject.setField("newValue"); final String newObjectJson = gson.toJson(newObject); final CloseableHttpResponse response = mock(CloseableHttpResponse.class); 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 ww w .j a v a 2s . com*/ final RestClient restClient = new BasicRestClient(httpClient, HttpClientContext.create(), "localhost"); final RESTServiceConnector connector = new RESTServiceConnector.Builder().client(restClient).build(); connector.executeUpdateObject(newObject, "/somepath", DEFAULT_TEST_PARAMETERS); verify(httpClient).execute(any(HttpHost.class), HttpUriRequestMethodMatcher.aMethod("PUT"), any(HttpClientContext.class)); verify(httpClient).execute(any(HttpHost.class), HttpUriRequestPayloadMatcher.aPayload(newObjectJson), any(HttpClientContext.class)); verify(httpClient).execute(any(HttpHost.class), HttpUriRequestQueryMatcher.aQueryThatContains("arg2=val2"), any(HttpClientContext.class)); verify(httpClient).execute(any(HttpHost.class), HttpUriRequestQueryMatcher.aQueryThatContains("arg1=val1"), any(HttpClientContext.class)); }
From source file:org.sonatype.nexus.testsuite.NexusHttpsITSupport.java
/** * @return Context with preemptive auth enabled for Nexus *//*from ww w . jav a 2s.co m*/ protected HttpClientContext clientContext() { HttpClientContext context = HttpClientContext.create(); context.setAuthCache(basicAuthCache()); return context; }
From source file:it.cloudicaro.disit.kb.rdf.HttpUtil.java
public static void delete(URL url, String user, String passwd) throws Exception { //System.out.println("DELETE "+url); HttpClient client = HttpClients.createDefault(); HttpDelete request = new HttpDelete(url.toURI()); HttpClientContext context = HttpClientContext.create(); if (user != null && passwd != null) { CredentialsProvider credsProvider = new BasicCredentialsProvider(); credsProvider.setCredentials(AuthScope.ANY, new UsernamePasswordCredentials(user, passwd)); context.setCredentialsProvider(credsProvider); }//w w w. j av a 2s . com HttpResponse response = client.execute(request, context); StatusLine s = response.getStatusLine(); int code = s.getStatusCode(); //System.out.println(code); if (code != 204 && code != 404) throw new Exception( "failed access to " + url.toString() + " code: " + code + " " + s.getReasonPhrase()); }
From source file:nu.yona.server.sms.PlivoSmsService.java
private HttpClientContext createHttpClientContext() { try {// w w w . jav a 2 s . co m SmsProperties smsProperties = yonaProperties.getSms(); URI uri = getPlivoUrl(smsProperties); CredentialsProvider credentialsProvider = new BasicCredentialsProvider(); credentialsProvider.setCredentials(new AuthScope(uri.getHost(), uri.getPort()), new UsernamePasswordCredentials(smsProperties.getPlivoAuthId(), smsProperties.getPlivoAuthToken())); HttpClientContext httpClientContext = HttpClientContext.create(); httpClientContext.setCredentialsProvider(credentialsProvider); return httpClientContext; } catch (URISyntaxException e) { throw SmsException.smsSendingFailed(e); } }