Example usage for org.springframework.http HttpOutputMessage getBody

List of usage examples for org.springframework.http HttpOutputMessage getBody

Introduction

In this page you can find the example usage for org.springframework.http HttpOutputMessage getBody.

Prototype

OutputStream getBody() throws IOException;

Source Link

Document

Return the body of the message as an output stream.

Usage

From source file:hornet.framework.web.converter.AbstractHornetHttpMessageConverter.java

/**
 * Encapsule l'appel  ecrireFichier(). Ajoute la logique d'ouverture / fermeture des flux
 *//*from w ww .  j  av a 2 s.  c o  m*/

@Override
protected void writeInternal(final T toExport, final HttpOutputMessage outputMessage)
        throws IOException, HttpMessageNotWritableException {

    LOG.debug("Demande d'export de {}", toExport.getClass());

    OutputStream os = null;
    try {
        os = outputMessage.getBody();
        ecrireFichier(toExport, os);
    } catch (final Exception e) {
        LOG.error("Erreur lors de la demande d'export de la classe {} : {}", toExport.getClass(),
                e.getMessage(), e);
        throw e;
    } finally {
        IOUtils.closeQuietly(os);
    }
}

From source file:org.craftercms.commons.jackson.mvc.CrafterJackson2MessageConverter.java

@Override
protected void writeInternal(Object object, HttpOutputMessage outputMessage)
        throws IOException, HttpMessageNotWritableException {

    JsonEncoding encoding = getJsonEncoding(outputMessage.getHeaders().getContentType());
    JsonGenerator jsonGenerator = this.getObjectMapper().getFactory().createGenerator(outputMessage.getBody(),
            encoding);//from  w  w  w  .j  a  v  a  2 s.c om
    // A workaround for JsonGenerators not applying serialization features
    // https://github.com/FasterXML/jackson-databind/issues/12
    if (this.getObjectMapper().isEnabled(SerializationFeature.INDENT_OUTPUT)) {
        jsonGenerator.useDefaultPrettyPrinter();
    }

    try {
        if (this.jsonPrefix != null) {
            jsonGenerator.writeRaw(this.jsonPrefix);
        }

        runAnnotations(object);

        ObjectWriter writer = this.getObjectMapper().writer(filter);
        writer.writeValue(jsonGenerator, object);
    } catch (JsonProcessingException ex) {
        throw new HttpMessageNotWritableException("Could not write JSON: " + ex.getMessage(), ex);
    }
}

From source file:org.geoserver.rest.converters.InputStreamConverter.java

@Override
protected void writeInternal(InputStream inputStream, HttpOutputMessage outputMessage)
        throws IOException, HttpMessageNotWritableException {
    try {//www  .  j  a  va 2  s  .c o m
        IOUtils.copy(inputStream, outputMessage.getBody());
    } finally {
        inputStream.close();
    }
}

From source file:org.geoserver.rest.converters.StyleWriterConverter.java

@Override
public void writeInternal(Object object, HttpOutputMessage outputMessage)
        throws IOException, HttpMessageNotWritableException {

    if (object instanceof RestWrapper) {
        object = ((RestWrapper<?>) object).getObject();
    }//  w  w w  .j  av  a  2 s.  co m

    if (object instanceof StyleInfo) {
        StyleInfo style = (StyleInfo) object;
        // optimization, if the requested format is the same as the native format
        // of the style, stream the file directly from the disk, otherwise encode
        // the style in the requested format
        if (handler.getFormat().equalsIgnoreCase(style.getFormat())) {
            copyDefinition(style, outputMessage.getBody());
            return;
        }
    }

    Style style = object instanceof StyleInfo ? ((StyleInfo) object).getStyle() : (Style) object;
    StyledLayerDescriptor sld = Styles.sld(style);
    // TODO: support pretty print somehow - probably a hint
    handler.encode(sld, version, false, outputMessage.getBody());
}

From source file:org.infoscoop.api.oauth2.provider.ISOAuth2ExceptionRenderer.java

public void handleHttpEntityResponse(HttpEntity<?> responseEntity, ServletWebRequest webRequest)
        throws Exception {
    if (responseEntity == null) {
        return;//from ww w.  j a v a  2  s. c om
    }
    HttpInputMessage inputMessage = createHttpInputMessage(webRequest);
    HttpOutputMessage outputMessage = createHttpOutputMessage(webRequest);
    HttpStatus statusCode = null;
    if (responseEntity instanceof ResponseEntity && outputMessage instanceof ServerHttpResponse) {
        statusCode = ((ResponseEntity<?>) responseEntity).getStatusCode();
        ((ServerHttpResponse) outputMessage).setStatusCode(statusCode);
    }
    HttpHeaders entityHeaders = responseEntity.getHeaders();
    if (!entityHeaders.isEmpty()) {
        outputMessage.getHeaders().putAll(entityHeaders);
    }
    Object body = responseEntity.getBody();
    if (body != null) {
        writeWithMessageConverters(body, inputMessage, outputMessage, statusCode, webRequest.getRequest());
    } else {
        // flush headers
        outputMessage.getBody();
    }
}

From source file:org.molgenis.util.GsonHttpMessageConverter.java

@Override
protected void writeInternal(Object o, HttpOutputMessage outputMessage)
        throws IOException, HttpMessageNotWritableException {

    OutputStreamWriter writer = new OutputStreamWriter(outputMessage.getBody(),
            getCharset(outputMessage.getHeaders()));

    String callback = getCallbackParam();
    if (callback != null) {
        // this is a JSONP (JSON with padding) request
        writer.append(callback).append('(');
    }//from   ww  w .  j  av a  2 s . com

    try {
        Type typeOfSrc = getType();

        if (LOG.isTraceEnabled()) {
            StringBuilder sb = new StringBuilder();
            if (this.prefixJson) {
                sb.append("{} && ");
            }

            if (typeOfSrc != null) {
                sb.append(gson.toJson(o, typeOfSrc));
            } else {
                sb.append(gson.toJson(o));
            }

            LOG.debug("Json response:\n" + sb.toString());
            writer.write(sb.toString());
        } else {
            if (this.prefixJson) {
                writer.append("{} && ");
            }

            if (typeOfSrc != null) {
                this.gson.toJson(o, typeOfSrc, writer);
            } else {
                this.gson.toJson(o, writer);
            }
        }

        if (callback != null) {
            // this is a JSONP (JSON with padding) request
            writer.append(')');
        }
    } catch (JsonIOException ex) {
        throw new HttpMessageNotWritableException("Could not write JSON: " + ex.getMessage(), ex);
    } finally {
        IOUtils.closeQuietly(writer);
    }

}

From source file:org.springframework.boot.devtools.tunnel.payload.HttpTunnelPayload.java

/**
 * Assign this payload to the given {@link HttpOutputMessage}.
 * @param message the message to assign this payload to
 * @throws IOException in case of I/O errors
 *//* w  w  w.  ja v a 2  s.com*/
public void assignTo(HttpOutputMessage message) throws IOException {
    Assert.notNull(message, "Message must not be null");
    HttpHeaders headers = message.getHeaders();
    headers.setContentLength(this.data.remaining());
    headers.add(SEQ_HEADER, Long.toString(getSequence()));
    headers.setContentType(MediaType.APPLICATION_OCTET_STREAM);
    WritableByteChannel body = Channels.newChannel(message.getBody());
    while (this.data.hasRemaining()) {
        body.write(this.data);
    }
    body.close();
}

From source file:org.springframework.flex.http.AmfHttpMessageConverter.java

private void writeActionMessage(ActionMessage message, HttpOutputMessage outputMessage, AmfTrace trace)
        throws IOException {
    AmfMessageSerializer serializer = new AmfMessageSerializer();
    ByteArrayOutputStream outBuffer = new ByteArrayOutputStream();
    serializer.setVersion(message.getVersion());
    serializer.initialize(new SerializationContext(), outBuffer, trace);

    try {//w w  w .  j  a v a2s .  com
        ActionContext context = new ActionContext();
        context.setVersion(message.getVersion());
        context.setResponseMessage(message);
        serializer.writeMessage(message);
        outBuffer.flush();
        outBuffer.close();
        outputMessage.getHeaders().setContentLength(outBuffer.size());
        outBuffer.writeTo(outputMessage.getBody());
    } catch (SerializationException se) {
        throw new HttpMessageNotWritableException("Could not write " + message + " as AMF message.", se);
    }
}

From source file:org.springframework.flex.http.AmfHttpMessageConverter.java

private void writeObject(Object data, HttpOutputMessage outputMessage, AmfTrace trace) throws IOException {
    ByteArrayOutputStream outBuffer = new ByteArrayOutputStream();
    Amf3Output serializer = new Amf3Output(new SerializationContext());
    serializer.setOutputStream(outBuffer);
    serializer.setDebugTrace(trace);/*from  w  w w .ja  va 2s .  c o  m*/
    try {
        serializer.writeObject(data);
        outBuffer.flush();
        outBuffer.close();
        outputMessage.getHeaders().setContentLength(outBuffer.size());
        outBuffer.writeTo(outputMessage.getBody());
    } catch (SerializationException se) {
        throw new HttpMessageNotWritableException("Could not write " + data + " as AMF message.", se);
    }
}

From source file:org.springframework.hateoas.Jackson2PagedResourcesIntegrationTest.java

/**
 * @see SPR-13318// www .j a  v a2  s .  c  om
 */
@Test
public void serializesPagedResourcesCorrectly() throws Exception {

    Assume.assumeThat(SPRING_4_2_WRITE_METHOD, is(notNullValue()));

    User user = new User();
    user.firstname = "Dave";
    user.lastname = "Matthews";

    PageMetadata metadata = new PagedResources.PageMetadata(1, 0, 2);
    PagedResources<User> resources = new PagedResources<User>(Collections.singleton(user), metadata);

    Method method = Sample.class.getMethod("someMethod");
    StringWriter writer = new StringWriter();

    HttpOutputMessage outputMessage = mock(HttpOutputMessage.class);
    when(outputMessage.getBody()).thenReturn(new WriterOutputStream(writer));
    when(outputMessage.getHeaders()).thenReturn(new HttpHeaders());

    MappingJackson2HttpMessageConverter converter = new MappingJackson2HttpMessageConverter();

    ReflectionUtils.invokeMethod(SPRING_4_2_WRITE_METHOD, converter, resources, method.getGenericReturnType(),
            MediaType.APPLICATION_JSON, outputMessage);

    assertThat(writer.toString(), is(REFERENCE));
}