List of usage examples for org.apache.http.util EntityUtils consumeQuietly
public static void consumeQuietly(HttpEntity httpEntity)
From source file:org.apache.olingo.server.example.TripPinServiceTest.java
@Test public void dataIsolation() throws Exception { String url = baseURL + "/People"; HttpRequest request = new HttpGet(url); request.setHeader(HttpHeader.ODATA_ISOLATION, "snapshot"); HttpResponse response = httpSend(request, 412); EntityUtils.consumeQuietly(response.getEntity()); }
From source file:org.openrdf.http.client.SparqlSession.java
/** * Parse the response in this thread using the provided {@link RDFHandler}. * All HTTP connections are closed and released in this method *//*from w w w.j a v a 2s . co m*/ protected void getRDF(HttpUriRequest method, RDFHandler handler, boolean requireContext) throws IOException, RDFHandlerException, RepositoryException, MalformedQueryException, UnauthorizedException, QueryInterruptedException { // Specify which formats we support using Accept headers Set<RDFFormat> rdfFormats = RDFParserRegistry.getInstance().getKeys(); if (rdfFormats.isEmpty()) { throw new RepositoryException("No tuple RDF parsers have been registered"); } // send the tuple query HttpResponse response = sendGraphQueryViaHttp(method, requireContext, rdfFormats); try { String mimeType = getResponseMIMEType(response); try { RDFFormat format = RDFFormat.matchMIMEType(mimeType, rdfFormats); RDFParser parser = Rio.createParser(format, getValueFactory()); parser.setParserConfig(getParserConfig()); parser.setParseErrorListener(new ParseErrorLogger()); parser.setRDFHandler(handler); parser.parse(response.getEntity().getContent(), method.getURI().toASCIIString()); } catch (UnsupportedRDFormatException e) { throw new RepositoryException("Server responded with an unsupported file format: " + mimeType); } catch (RDFParseException e) { throw new RepositoryException("Malformed query result from server", e); } } finally { EntityUtils.consumeQuietly(response.getEntity()); } }
From source file:org.eclipse.rdf4j.http.client.SPARQLProtocolSession.java
/** * Parse the response in a background thread. HTTP connections are dealt with in the * {@link BackgroundGraphResult} or (in the error-case) in this method. *//* w w w .ja va2 s . com*/ protected BackgroundGraphResult getRDFBackground(HttpUriRequest method, boolean requireContext) throws IOException, RDFHandlerException, RepositoryException, MalformedQueryException, UnauthorizedException, QueryInterruptedException { boolean submitted = false; // Specify which formats we support using Accept headers Set<RDFFormat> rdfFormats = RDFParserRegistry.getInstance().getKeys(); if (rdfFormats.isEmpty()) { throw new RepositoryException("No tuple RDF parsers have been registered"); } BackgroundGraphResult gRes = null; // send the tuple query HttpResponse response = sendGraphQueryViaHttp(method, requireContext, rdfFormats); try { // if we get here, HTTP code is 200 String mimeType = getResponseMIMEType(response); RDFFormat format = RDFFormat.matchMIMEType(mimeType, rdfFormats).orElseThrow( () -> new RepositoryException("Server responded with an unsupported file format: " + mimeType)); RDFParser parser = Rio.createParser(format, getValueFactory()); parser.setParserConfig(getParserConfig()); parser.setParseErrorListener(new ParseErrorLogger()); Charset charset = null; // SES-1793 : Do not attempt to check for a charset if the format is // defined not to have a charset // This prevents errors caused by people erroneously attaching a // charset to a binary formatted document HttpEntity entity = response.getEntity(); if (format.hasCharset() && entity != null && entity.getContentType() != null) { // TODO copied from SPARQLGraphQuery repository, is this // required? try { charset = ContentType.parse(entity.getContentType().getValue()).getCharset(); } catch (IllegalCharsetNameException e) { // work around for Joseki-3.2 // Content-Type: application/rdf+xml; // charset=application/rdf+xml } if (charset == null) { charset = UTF8; } } if (entity == null) { throw new RepositoryException("Server response was empty."); } String baseURI = method.getURI().toASCIIString(); gRes = new BackgroundGraphResult(parser, entity.getContent(), charset, baseURI); execute(gRes); submitted = true; return gRes; } finally { if (!submitted) { try { if (gRes != null) { gRes.close(); } } finally { EntityUtils.consumeQuietly(response.getEntity()); } } } }
From source file:org.openrdf.http.client.SparqlSession.java
/** * Parse the response in this thread using a suitable * {@link BooleanQueryResultParser}. All HTTP connections are closed and * released in this method//w ww . j ava 2 s . c o m * * @throws OpenRDFException */ protected boolean getBoolean(HttpUriRequest method) throws IOException, OpenRDFException { // Specify which formats we support using Accept headers Set<BooleanQueryResultFormat> booleanFormats = BooleanQueryResultParserRegistry.getInstance().getKeys(); if (booleanFormats.isEmpty()) { throw new RepositoryException("No boolean query result parsers have been registered"); } // send the tuple query HttpResponse response = sendBooleanQueryViaHttp(method, booleanFormats); try { // if we get here, HTTP code is 200 String mimeType = getResponseMIMEType(response); try { BooleanQueryResultFormat format = BooleanQueryResultFormat.matchMIMEType(mimeType, booleanFormats); BooleanQueryResultParser parser = QueryResultIO.createParser(format); QueryResultCollector results = new QueryResultCollector(); parser.setQueryResultHandler(results); parser.parseQueryResult(response.getEntity().getContent()); return results.getBoolean(); } catch (UnsupportedQueryResultFormatException e) { throw new RepositoryException("Server responded with an unsupported file format: " + mimeType); } catch (QueryResultParseException e) { throw new RepositoryException("Malformed query result from server", e); } } finally { EntityUtils.consumeQuietly(response.getEntity()); } }
From source file:org.eclipse.rdf4j.http.client.SPARQLProtocolSession.java
/** * Parse the response in this thread using the provided {@link RDFHandler}. All HTTP connections are * closed and released in this method/*from ww w .j av a 2 s . c o m*/ */ protected void getRDF(HttpUriRequest method, RDFHandler handler, boolean requireContext) throws IOException, RDFHandlerException, RepositoryException, MalformedQueryException, UnauthorizedException, QueryInterruptedException { // Specify which formats we support using Accept headers Set<RDFFormat> rdfFormats = RDFParserRegistry.getInstance().getKeys(); if (rdfFormats.isEmpty()) { throw new RepositoryException("No tuple RDF parsers have been registered"); } // send the tuple query HttpResponse response = sendGraphQueryViaHttp(method, requireContext, rdfFormats); try { String mimeType = getResponseMIMEType(response); try { RDFFormat format = RDFFormat.matchMIMEType(mimeType, rdfFormats) .orElseThrow(() -> new RepositoryException( "Server responded with an unsupported file format: " + mimeType)); RDFParser parser = Rio.createParser(format, getValueFactory()); parser.setParserConfig(getParserConfig()); parser.setParseErrorListener(new ParseErrorLogger()); parser.setRDFHandler(handler); parser.parse(response.getEntity().getContent(), method.getURI().toASCIIString()); } catch (RDFParseException e) { throw new RepositoryException("Malformed query result from server", e); } } finally { EntityUtils.consumeQuietly(response.getEntity()); } }
From source file:org.openrdf.http.client.SparqlSession.java
/** * Convenience method to deal with HTTP level errors of tuple, graph and * boolean queries in the same way. This method aborts the HTTP connection. * //from ww w.j av a 2s . co m * @param method * @throws OpenRDFException */ protected HttpResponse executeOK(HttpUriRequest method) throws IOException, OpenRDFException { boolean fail = true; HttpResponse response = execute(method); try { int httpCode = response.getStatusLine().getStatusCode(); if (httpCode == HttpURLConnection.HTTP_OK || httpCode == HttpURLConnection.HTTP_NOT_AUTHORITATIVE) { fail = false; return response; // everything OK, control flow can continue } else { // trying to contact a non-Sesame server? throw new RepositoryException("Failed to get server protocol; no such resource on this server: " + method.getURI().toString()); } } finally { if (fail) { EntityUtils.consumeQuietly(response.getEntity()); } } }
From source file:org.fcrepo.test.api.TestRESTAPI.java
@Test public void testIngest() throws Exception { // Create new empty object URI url = getURI(String.format("/objects/new")); StringEntity entity = getStringEntity("", TEXT_XML); verifyPOSTStatusOnly(url, SC_UNAUTHORIZED, entity, false); HttpPost post = new HttpPost(url); HttpResponse response = putOrPost(post, entity, true); String responseBody = readString(response); assertEquals(SC_CREATED, response.getStatusLine().getStatusCode()); String emptyObjectPid = extractPid(response.getFirstHeader(HttpHeaders.LOCATION).getValue()); assertNotNull(emptyObjectPid);// w ww .j av a 2s . c o m // PID should be returned as a header and as the response body assertTrue(responseBody.equals(emptyObjectPid)); // Delete empty object url = getURI(String.format("/objects/%s", emptyObjectPid)); verifyDELETEStatusOnly(url, SC_UNAUTHORIZED, false); verifyDELETEStatusOnly(url, SC_OK, true); // Ensure that GETs of the deleted object immediately give 404s (See FCREPO-594) verifyGETStatusOnly(url, SC_NOT_FOUND); // Create new empty object with a PID namespace specified url = getURI(String.format("/objects/new?namespace=test")); verifyPOSTStatusOnly(url, SC_UNAUTHORIZED, entity, false); post = new HttpPost(url); response = putOrPost(post, entity, true); EntityUtils.consumeQuietly(response.getEntity()); assertEquals(SC_CREATED, response.getStatusLine().getStatusCode()); emptyObjectPid = extractPid(response.getFirstHeader(HttpHeaders.LOCATION).getValue()); assertTrue(emptyObjectPid.startsWith("test")); // Delete empty "test" object url = getURI(String.format("/objects/%s", emptyObjectPid)); verifyDELETEStatusOnly(url, SC_UNAUTHORIZED, false); verifyDELETEStatusOnly(url, SC_OK, true); // Delete the demo:REST object (ingested as part of setup) url = getURI(String.format("/objects/%s", DEMO_REST_PID.toString())); verifyDELETEStatusOnly(url, SC_UNAUTHORIZED, false); verifyDELETEStatusOnly(url, SC_OK, true); // Create a new empty demo:REST object with parameterized ownerId url = getURI(String.format("/objects/%s?ownerId=%s", DEMO_REST_PID.toString(), DEMO_OWNERID)); verifyPOSTStatusOnly(url, SC_UNAUTHORIZED, null, false); post = new HttpPost(url); response = putOrPost(post, entity, true); responseBody = readString(response); assertEquals(SC_CREATED, response.getStatusLine().getStatusCode()); Header locationHeader = response.getFirstHeader(HttpHeaders.LOCATION); assertNotNull(locationHeader); assertTrue(locationHeader.getValue().contains(URLEncoder.encode(DEMO_REST_PID.toString(), "UTF-8"))); assertTrue(responseBody.equals(DEMO_REST_PID.toString())); // verify ownerId responseBody = verifyGETStatusString(url, SC_OK, true, true); assertTrue(responseBody.indexOf(DEMO_OWNERID) > 0); // Delete the demo:REST object (ingested as part of setup) url = getURI(String.format("/objects/%s", DEMO_REST_PID.toString())); verifyDELETEStatusOnly(url, SC_UNAUTHORIZED, false); verifyDELETEStatusOnly(url, SC_OK, true); // Ingest the demo:REST object url = getURI(String.format("/objects/%s", DEMO_REST_PID.toString())); entity = getStringEntity(DEMO_REST, TEXT_XML); verifyPOSTStatusOnly(url, SC_UNAUTHORIZED, entity, false); post = new HttpPost(url); response = putOrPost(post, entity, true); responseBody = readString(response); assertEquals(SC_CREATED, response.getStatusLine().getStatusCode()); locationHeader = response.getFirstHeader(HttpHeaders.LOCATION); assertNotNull(locationHeader); assertTrue(locationHeader.getValue().contains(URLEncoder.encode(DEMO_REST_PID.toString(), "UTF-8"))); assertTrue(responseBody.equals(DEMO_REST_PID.toString())); // Ingest minimal object with no PID url = getURI(String.format("/objects/new")); entity = getStringEntity(DEMO_MIN, TEXT_XML); verifyPOSTStatusOnly(url, SC_UNAUTHORIZED, entity, false); post = new HttpPost(url); response = putOrPost(post, entity, true); EntityUtils.consumeQuietly(response.getEntity()); assertEquals(SC_CREATED, response.getStatusLine().getStatusCode()); // Delete minimal object String minimalObjectPid = extractPid(response.getFirstHeader(HttpHeaders.LOCATION).getValue()); url = getURI(String.format("/objects/%s", minimalObjectPid)); verifyDELETEStatusOnly(url, SC_UNAUTHORIZED, false); verifyDELETEStatusOnly(url, SC_OK, true); }
From source file:org.eclipse.rdf4j.http.client.SPARQLProtocolSession.java
/** * Parse the response in this thread using a suitable {@link BooleanQueryResultParser}. All HTTP * connections are closed and released in this method * // w w w. jav a 2 s. c o m * @throws RDF4JException */ protected boolean getBoolean(HttpUriRequest method) throws IOException, RDF4JException { // Specify which formats we support using Accept headers Set<QueryResultFormat> booleanFormats = BooleanQueryResultParserRegistry.getInstance().getKeys(); if (booleanFormats.isEmpty()) { throw new RepositoryException("No boolean query result parsers have been registered"); } // send the tuple query HttpResponse response = sendBooleanQueryViaHttp(method, booleanFormats); try { // if we get here, HTTP code is 200 String mimeType = getResponseMIMEType(response); try { QueryResultFormat format = BooleanQueryResultFormat.matchMIMEType(mimeType, booleanFormats) .orElseThrow(() -> new RepositoryException( "Server responded with an unsupported file format: " + mimeType)); BooleanQueryResultParser parser = QueryResultIO.createBooleanParser(format); QueryResultCollector results = new QueryResultCollector(); parser.setQueryResultHandler(results); parser.parseQueryResult(response.getEntity().getContent()); return results.getBoolean(); } catch (QueryResultParseException e) { throw new RepositoryException("Malformed query result from server", e); } } finally { EntityUtils.consumeQuietly(response.getEntity()); } }
From source file:org.openrdf.http.client.SparqlSession.java
protected HttpResponse execute(HttpUriRequest method) throws IOException, OpenRDFException { boolean consume = true; method.setParams(params);/* ww w .j a va 2 s . c o m*/ HttpResponse response = httpClient.execute(method, httpContext); try { int httpCode = response.getStatusLine().getStatusCode(); if (httpCode >= 200 && httpCode < 300 || httpCode == HttpURLConnection.HTTP_NOT_FOUND) { consume = false; return response; // everything OK, control flow can continue } else { switch (httpCode) { case HttpURLConnection.HTTP_UNAUTHORIZED: // 401 throw new UnauthorizedException(); case HttpURLConnection.HTTP_UNAVAILABLE: // 503 throw new QueryInterruptedException(); default: ErrorInfo errInfo = getErrorInfo(response); // Throw appropriate exception if (errInfo.getErrorType() == ErrorType.MALFORMED_DATA) { throw new RDFParseException(errInfo.getErrorMessage()); } else if (errInfo.getErrorType() == ErrorType.UNSUPPORTED_FILE_FORMAT) { throw new UnsupportedRDFormatException(errInfo.getErrorMessage()); } else if (errInfo.getErrorType() == ErrorType.MALFORMED_QUERY) { throw new MalformedQueryException(errInfo.getErrorMessage()); } else if (errInfo.getErrorType() == ErrorType.UNSUPPORTED_QUERY_LANGUAGE) { throw new UnsupportedQueryLanguageException(errInfo.getErrorMessage()); } else { throw new RepositoryException(errInfo.toString()); } } } } finally { if (consume) { EntityUtils.consumeQuietly(response.getEntity()); } } }
From source file:org.eclipse.rdf4j.http.client.SPARQLProtocolSession.java
/** * Convenience method to deal with HTTP level errors of tuple, graph and boolean queries in the same way. * This method aborts the HTTP connection. * //from ww w .j a v a2 s. c o m * @param method * @throws RDF4JException */ protected HttpResponse executeOK(HttpUriRequest method) throws IOException, RDF4JException { boolean fail = true; HttpResponse response = execute(method); try { int httpCode = response.getStatusLine().getStatusCode(); if (httpCode == HttpURLConnection.HTTP_OK || httpCode == HttpURLConnection.HTTP_NOT_AUTHORITATIVE) { fail = false; return response; // everything OK, control flow can continue } else { // trying to contact a non-SPARQL server? throw new RepositoryException("Failed to get server protocol; no such resource on this server: " + method.getURI().toString()); } } finally { if (fail) { EntityUtils.consumeQuietly(response.getEntity()); } } }