List of usage examples for org.apache.http.entity EntityTemplate writeTo
public void writeTo(OutputStream outputStream) throws IOException
From source file:org.robertburrelldonkin.template4couchdb.rest.HttpClientRestClientTest.java
@Test public void testPostContent() throws Exception { ArgumentCaptor<HttpPost> argument = ArgumentCaptor.forClass(HttpPost.class); this.subject.post(URL, documentMarshaller, document, responseUnmarshaller); verify(client).execute(argument.capture(), eq(handler)); EntityTemplate entity = (EntityTemplate) argument.getValue().getEntity(); assertNotNull(entity);// w ww. j a va2s . c o m entity.writeTo(stream); verify(producer).writeTo(stream); }
From source file:net.elasticgrid.rackspace.common.RackspaceConnection.java
/** * Make a http request and process the response. This method also performs automatic retries. * * @param request the HTTP method to use (GET, POST, DELETE, etc) * @param respType the class that represents the desired/expected return type * @return the unmarshalled entity/*w ww. j a va2 s. c om*/ * @throws RackspaceException * @throws IOException if there is an I/O exception * @throws HttpException if there is an HTTP exception * @throws JiBXException if the result can't be unmarshalled */ @SuppressWarnings("unchecked") protected <T> T makeRequest(HttpRequestBase request, Class<T> respType) throws HttpException, IOException, JiBXException, RackspaceException { if (!authenticated) authenticate(); // add auth params, and protocol specific headers request.addHeader("X-Auth-Token", getAuthToken()); // set accept and content-type headers request.setHeader("Accept", "application/xml; charset=UTF-8"); request.setHeader("Accept-Encoding", "gzip"); request.setHeader("Content-Type", "application/xml; charset=UTF-8"); // send the request T result = null; boolean done = false; int retries = 0; boolean doRetry = false; RackspaceException error = null; do { HttpResponse response = null; if (retries > 0) logger.log(Level.INFO, "Retry #{0}: querying via {1} {2}", new Object[] { retries, request.getMethod(), request.getURI() }); else logger.log(Level.INFO, "Querying via {0} {1}", new Object[] { request.getMethod(), request.getURI() }); if (logger.isLoggable(Level.FINEST) && request instanceof HttpEntityEnclosingRequestBase) { HttpEntity entity = ((HttpEntityEnclosingRequestBase) request).getEntity(); if (entity instanceof EntityTemplate) { EntityTemplate template = (EntityTemplate) entity; ByteArrayOutputStream baos = null; try { baos = new ByteArrayOutputStream(); template.writeTo(baos); logger.log(Level.FINEST, "Request body:\n{0}", baos.toString()); } finally { IOUtils.closeQuietly(baos); } } } InputStream entityStream = null; HttpEntity entity = null; if (logger.isLoggable(Level.FINEST)) { response = getHttpClient().execute(request); entity = response.getEntity(); try { entityStream = entity.getContent(); logger.log(Level.FINEST, "Response body on " + request.getURI() + " via " + request.getMethod() + ":\n" + IOUtils.toString(entityStream)); } finally { IOUtils.closeQuietly(entityStream); } } response = getHttpClient().execute(request); int statusCode = response.getStatusLine().getStatusCode(); entity = response.getEntity(); switch (statusCode) { case 200: case 202: case 203: try { entityStream = entity.getContent(); IBindingFactory bindingFactory = BindingDirectory.getFactory(respType); IUnmarshallingContext unmarshallingCxt = bindingFactory.createUnmarshallingContext(); result = (T) unmarshallingCxt.unmarshalDocument(entityStream, "UTF-8"); } finally { entity.consumeContent(); IOUtils.closeQuietly(entityStream); } done = true; break; case 503: // service unavailable logger.log(Level.WARNING, "Service unavailable on {0} via {1}. Will retry in {2} seconds.", new Object[] { request.getURI(), request.getMethod(), Math.pow(2.0, retries + 1) }); doRetry = true; break; case 401: // unauthorized logger.warning("Not authenticated or authentication token expired. Authenticating..."); authenticate(); doRetry = true; break; case 417: throw new RackspaceException(new IllegalArgumentException("Some parameters are invalid!")); // TODO: temp hack 'til Rackspace API is fixed! case 400: case 500: default: try { entityStream = entity.getContent(); IBindingFactory bindingFactory = BindingDirectory.getFactory(CloudServersAPIFault.class); IUnmarshallingContext unmarshallingCxt = bindingFactory.createUnmarshallingContext(); CloudServersAPIFault fault = (CloudServersAPIFault) unmarshallingCxt .unmarshalDocument(entityStream, "UTF-8"); done = true; throw new RackspaceException(fault.getCode(), fault.getMessage(), fault.getDetails()); } catch (JiBXException e) { response = getHttpClient().execute(request); entity = response.getEntity(); entityStream = entity.getContent(); logger.log(Level.SEVERE, "Can't unmarshal response from " + request.getURI() + " via " + request.getMethod() + ":" + IOUtils.toString(entityStream)); e.printStackTrace(); throw e; } finally { entity.consumeContent(); IOUtils.closeQuietly(entityStream); } } if (doRetry) { retries++; if (retries > maxRetries) { throw new HttpException("Number of retries exceeded for " + request.getURI(), error); } doRetry = false; try { Thread.sleep((int) Math.pow(2.0, retries) * 1000); } catch (InterruptedException ex) { // do nothing } } } while (!done); return result; }