List of usage examples for org.apache.http.util EntityUtils consumeQuietly
public static void consumeQuietly(HttpEntity httpEntity)
From source file:org.digidoc4j.impl.bdoc.SkDataLoader.java
@Override public byte[] post(final String url, final byte[] content) throws DSSException { logger.info("Getting OCSP response from " + url); if (userAgent == null) { throw new TechnicalException("User Agent must be set for OCSP requests"); }/* w w w . j av a 2 s.co m*/ HttpPost httpRequest = null; HttpResponse httpResponse = null; CloseableHttpClient client = null; try { final URI uri = URI.create(url.trim()); httpRequest = new HttpPost(uri); httpRequest.setHeader("User-Agent", userAgent); // The length for the InputStreamEntity is needed, because some receivers (on the other side) need this information. // To determine the length, we cannot read the content-stream up to the end and re-use it afterwards. // This is because, it may not be possible to reset the stream (= go to position 0). // So, the solution is to cache temporarily the complete content data (as we do not expect much here) in a byte-array. final ByteArrayInputStream bis = new ByteArrayInputStream(content); final HttpEntity httpEntity = new InputStreamEntity(bis, content.length); final HttpEntity requestEntity = new BufferedHttpEntity(httpEntity); httpRequest.setEntity(requestEntity); if (contentType != null) { httpRequest.setHeader(CONTENT_TYPE, contentType); } client = getHttpClient(url); httpResponse = getHttpResponse(client, httpRequest, url); final byte[] returnedBytes = readHttpResponse(url, httpResponse); return returnedBytes; } catch (IOException e) { throw new DSSException(e); } finally { try { if (httpRequest != null) { httpRequest.releaseConnection(); } if (httpResponse != null) { EntityUtils.consumeQuietly(httpResponse.getEntity()); } } finally { IOUtils.closeQuietly(client); } } }
From source file:net.sf.jasperreports.phantomjs.ProcessConnection.java
public String runRequest(String data) { HttpPost httpPost = new HttpPost(process.getListenURI()); HttpEntity postEntity = new ByteArrayEntity(data.getBytes(StandardCharsets.UTF_8)); httpPost.setEntity(postEntity);//from ww w .j ava 2 s .co m if (log.isDebugEnabled()) { log.debug(process.getId() + " executing HTTP at " + process.getListenURI()); } try (CloseableHttpResponse response = httpClient.execute(httpPost)) { StatusLine status = response.getStatusLine(); if (log.isDebugEnabled()) { log.debug(process.getId() + " HTTP response status " + status); } HttpEntity entity = response.getEntity(); if (entity == null) { throw new JRRuntimeException("Empty from PhantomJS"); } if (status.getStatusCode() >= 300) { if (entity.getContentType() != null && entity.getContentType().getValue() != null && entity.getContentType().getValue().startsWith("text/plain")) { String responseContents = EntityUtils.toString(entity, StandardCharsets.UTF_8); log.error("PhantomJS process " + process.getId() + " error: " + responseContents); } else { EntityUtils.consumeQuietly(entity); } throw new JRRuntimeException("Unexpected status " + status + " from PhantomJS"); } byte[] responseData; try (InputStream responseStream = entity.getContent()) { responseData = JRLoader.loadBytes(responseStream); } //TODO lucianc return the bytes return new String(responseData, StandardCharsets.UTF_8); } catch (SocketTimeoutException e) { log.error(process.getId() + " request timed out"); throw new RequestTimeoutException(e); } catch (JRException | IOException e) { throw new JRRuntimeException(e); } }
From source file:com.erudika.para.security.FacebookAuthFilter.java
/** * Handles an authentication request.// w ww . j a v a 2s . c om * @param request HTTP request * @param response HTTP response * @return an authentication object that contains the principal object if successful. * @throws IOException ex */ @Override public Authentication attemptAuthentication(HttpServletRequest request, HttpServletResponse response) throws IOException { final String requestURI = request.getRequestURI(); UserAuthentication userAuth = null; if (requestURI.endsWith(FACEBOOK_ACTION)) { String authCode = request.getParameter("code"); if (!StringUtils.isBlank(authCode)) { String url = Utils.formatMessage(TOKEN_URL, authCode, request.getRequestURL().toString(), Config.FB_APP_ID, Config.FB_SECRET); HttpGet tokenPost = new HttpGet(url); CloseableHttpResponse resp1 = httpclient.execute(tokenPost); if (resp1 != null && resp1.getEntity() != null) { String token = EntityUtils.toString(resp1.getEntity(), Config.DEFAULT_ENCODING); if (token != null && token.startsWith("access_token")) { String accessToken = token.substring(token.indexOf("=") + 1, token.indexOf("&")); userAuth = getOrCreateUser(null, accessToken); } EntityUtils.consumeQuietly(resp1.getEntity()); } } } User user = SecurityUtils.getAuthenticatedUser(userAuth); if (userAuth == null || user == null || user.getIdentifier() == null) { throw new BadCredentialsException("Bad credentials."); } else if (!user.getActive()) { throw new LockedException("Account is locked."); } return userAuth; }
From source file:com.erudika.para.security.LinkedInAuthFilter.java
/** * Handles an authentication request.//from www . jav a 2s . c o m * @param request HTTP request * @param response HTTP response * @return an authentication object that contains the principal object if successful. * @throws IOException ex */ @Override public Authentication attemptAuthentication(HttpServletRequest request, HttpServletResponse response) throws IOException { final String requestURI = request.getRequestURI(); UserAuthentication userAuth = null; if (requestURI.endsWith(LINKEDIN_ACTION)) { String authCode = request.getParameter("code"); if (!StringUtils.isBlank(authCode)) { String url = Utils.formatMessage(TOKEN_URL, authCode, request.getRequestURL().toString(), Config.LINKEDIN_APP_ID, Config.LINKEDIN_SECRET); HttpPost tokenPost = new HttpPost(url); CloseableHttpResponse resp1 = httpclient.execute(tokenPost); if (resp1 != null && resp1.getEntity() != null) { Map<String, Object> token = jreader.readValue(resp1.getEntity().getContent()); if (token != null && token.containsKey("access_token")) { userAuth = getOrCreateUser(null, (String) token.get("access_token")); } EntityUtils.consumeQuietly(resp1.getEntity()); } } } User user = SecurityUtils.getAuthenticatedUser(userAuth); if (userAuth == null || user == null || user.getIdentifier() == null) { throw new BadCredentialsException("Bad credentials."); } else if (!user.getActive()) { throw new LockedException("Account is locked."); } return userAuth; }
From source file:de.ii.ldproxy.service.SparqlAdapter.java
public Map<String, String> request(String value, QUERY type) { Map<String, String> ids = new LinkedHashMap<>(); HttpResponse httpResponse = null;//from w w w . j av a 2s. c o m try { HttpGet httpGet = new HttpGet(getRequestUri(value, type)); httpResponse = httpClient.execute(httpGet, new BasicHttpContext()); JsonNode rootNode = jsonMapper.readTree(httpResponse.getEntity().getContent()); Iterator<JsonNode> elements = rootNode.get("results").get("bindings").elements(); while (elements.hasNext()) { JsonNode node = elements.next(); String id = node.get("id").get("value").asText(); String title = node.get("title").get("value").asText(); ids.put(id, title); LOGGER.getLogger().debug("LINK {} {}", id, title); } } catch (IOException | URISyntaxException e) { // ignore } finally { if (httpResponse != null) { EntityUtils.consumeQuietly(httpResponse.getEntity()); } } return ids; }
From source file:org.callimachusproject.client.HttpUriResponse.java
@Override public void setEntity(HttpEntity entity) { HttpEntity previously = getEntity(); if (entity == null && previously != null) { EntityUtils.consumeQuietly(previously); }/*from w w w.j av a 2 s. c om*/ delegate.setEntity(entity); }
From source file:org.apache.lucene.replicator.http.HttpClientBase.java
/** * <b>Internal:</b> response status after invocation, and in case or error attempt to read the * exception sent by the server. //from ww w .j a v a2 s .c o m */ protected void verifyStatus(HttpResponse response) throws IOException { StatusLine statusLine = response.getStatusLine(); if (statusLine.getStatusCode() != HttpStatus.SC_OK) { try { throwKnownError(response, statusLine); } finally { EntityUtils.consumeQuietly(response.getEntity()); } } }
From source file:pl.psnc.synat.wrdz.zmkd.invocation.RestServiceCaller.java
/** * Invoke a service according to the execution info. * // www.j a v a 2 s . c o m * In case of success, the entity stream is not closed. * * @param execInfo * info how to execute a REST service * @return execution outcome * @throws InvalidHttpRequestException * when constructed request is invalid * @throws InvalidHttpResponseException * when response is invalid */ public ExecutionOutcome invoke(ExecutionInfo execInfo) throws InvalidHttpRequestException, InvalidHttpResponseException { HttpClient httpClient = getHttpClient(); HttpRequestBase request = null; try { request = RestServiceCallerUtils.constructServiceRequestBase(execInfo); } catch (URISyntaxException e) { logger.error("Incorrect URI of the service.", e); throw new InvalidHttpRequestException(e); } if (request instanceof HttpEntityEnclosingRequestBase) { HttpEntity entity = RestServiceCallerUtils.constructServiceRequestEntity(execInfo); if (entity != null) { ((HttpEntityEnclosingRequestBase) request).setEntity(entity); } Header header = RestServiceCallerUtils.constructServiceRequestHeader(execInfo); if (header != null) { request.setHeader(header); } } HttpParams params = new BasicHttpParams(); params.setParameter("http.protocol.handle-redirects", false); request.setParams(params); HttpResponse response = null; try { response = httpClient.execute(request); } catch (ClientProtocolException e) { logger.error("Incorrect protocol.", e); throw new InvalidHttpResponseException(e); } catch (IOException e) { logger.error("IO error during execution.", e); throw new InvalidHttpResponseException(e); } try { return RestServiceCallerUtils.retrieveOutcome(response); } catch (IllegalStateException e) { logger.error("Cannot retrived the stream with the content.", e); EntityUtils.consumeQuietly(response.getEntity()); throw new InvalidHttpResponseException(e); } catch (IOException e) { logger.error("IO error when retrieving content.", e); EntityUtils.consumeQuietly(response.getEntity()); throw new InvalidHttpResponseException(e); } // remember to close the entity stream after read it. }
From source file:org.esigate.authentication.GenericAuthentificationHandler.java
@Override public boolean event(EventDefinition id, Event event) { if (EventManager.EVENT_FRAGMENT_PRE.equals(id)) { FragmentEvent e = (FragmentEvent) event; preRequest(e.getHttpRequest(), e.getOriginalRequest()); } else if (EventManager.EVENT_FRAGMENT_POST.equals(id)) { FragmentEvent e = (FragmentEvent) event; while (needsNewRequest(e.getHttpResponse(), e.getHttpRequest(), e.getOriginalRequest())) { EntityUtils.consumeQuietly(e.getHttpResponse().getEntity()); preRequest(e.getHttpRequest(), e.getOriginalRequest()); try { e.setHttpResponse(this.driver.getRequestExecutor().execute(e.getHttpRequest())); } catch (HttpErrorPage e1) { e.setHttpResponse(e1.getHttpResponse()); }/* w w w . ja va 2 s .co m*/ } } else if (EventManager.EVENT_PROXY_PRE.equals(id)) { ProxyEvent e = (ProxyEvent) event; e.setExit(!beforeProxy(e.getOriginalRequest())); } return true; }
From source file:co.cask.tigon.sql.internal.HealthAndMetricsTest.java
private void register(String ftaID, String ftaName, String pingURL) { HttpClient httpClient = new DefaultHttpClient(); JsonObject bodyJson = new JsonObject(); bodyJson.addProperty("name", "test"); bodyJson.addProperty("fta_name", ftaName); bodyJson.addProperty("ftaid", ftaID); HttpPost httpPost = new HttpPost(pingURL + "/v1/announce-fta-instance"); StringEntity params = null;/* w ww. ja v a2 s.c o m*/ try { params = new StringEntity(bodyJson.toString()); } catch (UnsupportedEncodingException e) { e.printStackTrace(); } httpPost.addHeader("Content-Type", "application/json"); httpPost.setEntity(params); try { EntityUtils.consumeQuietly(httpClient.execute(httpPost).getEntity()); } catch (IOException e) { e.printStackTrace(); } }