Search in sources :

Example 16 with MessageBodyWriter

use of javax.ws.rs.ext.MessageBodyWriter in project minijax by minijax.

the class WriterTest method testWriteWidget.

@Test
@SuppressWarnings("unchecked")
public void testWriteWidget() throws IOException {
    final Widget widget = new Widget();
    widget.id = "456";
    widget.value = "foobar";
    final ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
    final MessageBodyWriter<Widget> widgetWriter = (MessageBodyWriter<Widget>) writer;
    widgetWriter.writeTo(widget, Widget.class, null, null, MediaType.APPLICATION_JSON_TYPE, null, outputStream);
    assertEquals("{\"id\":\"456\",\"value\":\"foobar\"}", outputStream.toString());
}
Also used : ByteArrayOutputStream(java.io.ByteArrayOutputStream) MessageBodyWriter(javax.ws.rs.ext.MessageBodyWriter) MinijaxTest(org.minijax.test.MinijaxTest) Test(org.junit.Test)

Example 17 with MessageBodyWriter

use of javax.ws.rs.ext.MessageBodyWriter in project minijax by minijax.

the class MinijaxApplication method write.

@SuppressWarnings({ "rawtypes", "unchecked" })
public void write(final MinijaxRequestContext context, final Response response, final HttpServletResponse servletResponse) throws IOException {
    servletResponse.setStatus(response.getStatus());
    for (final Entry<String, List<Object>> entry : response.getHeaders().entrySet()) {
        final String name = entry.getKey();
        for (final Object value : entry.getValue()) {
            servletResponse.addHeader(name, value.toString());
        }
    }
    if (context.getMethod().equals("OPTIONS")) {
        return;
    }
    final MediaType mediaType = response.getMediaType();
    if (mediaType != null) {
        servletResponse.setContentType(mediaType.toString());
    }
    final Object obj = response.getEntity();
    if (obj == null) {
        return;
    }
    final MessageBodyWriter writer = providers.getMessageBodyWriter(obj.getClass(), null, null, mediaType);
    if (writer != null) {
        writer.writeTo(obj, obj.getClass(), null, null, mediaType, null, servletResponse.getOutputStream());
        return;
    }
    // What to do
    servletResponse.getWriter().println(obj.toString());
}
Also used : MediaType(javax.ws.rs.core.MediaType) ArrayList(java.util.ArrayList) List(java.util.List) MessageBodyWriter(javax.ws.rs.ext.MessageBodyWriter)

Example 18 with MessageBodyWriter

use of javax.ws.rs.ext.MessageBodyWriter in project dropwizard by dropwizard.

the class OptionalMessageBodyWriter method writeTo.

@SuppressWarnings({ "rawtypes", "unchecked" })
@Override
public void writeTo(Optional<?> entity, Class<?> type, Type genericType, Annotation[] annotations, MediaType mediaType, MultivaluedMap<String, Object> httpHeaders, OutputStream entityStream) throws IOException {
    if (!entity.isPresent()) {
        throw EmptyOptionalException.INSTANCE;
    }
    final ParameterizedType actualGenericType = (ParameterizedType) genericType;
    final Type actualGenericTypeArgument = actualGenericType.getActualTypeArguments()[0];
    final MessageBodyWriter writer = requireNonNull(mbw).get().getMessageBodyWriter(entity.get().getClass(), actualGenericTypeArgument, annotations, mediaType);
    writer.writeTo(entity.get(), entity.get().getClass(), actualGenericTypeArgument, annotations, mediaType, httpHeaders, entityStream);
}
Also used : ParameterizedType(java.lang.reflect.ParameterizedType) MediaType(javax.ws.rs.core.MediaType) ParameterizedType(java.lang.reflect.ParameterizedType) Type(java.lang.reflect.Type) MessageBodyWriter(javax.ws.rs.ext.MessageBodyWriter)

Example 19 with MessageBodyWriter

use of javax.ws.rs.ext.MessageBodyWriter in project dropwizard by dropwizard.

the class OptionalMessageBodyWriter method writeTo.

@SuppressWarnings({ "rawtypes", "unchecked" })
@Override
public void writeTo(Optional<?> entity, Class<?> type, Type genericType, Annotation[] annotations, MediaType mediaType, MultivaluedMap<String, Object> httpHeaders, OutputStream entityStream) throws IOException {
    if (!entity.isPresent()) {
        throw EmptyOptionalException.INSTANCE;
    }
    final Type innerGenericType = (genericType instanceof ParameterizedType) ? ((ParameterizedType) genericType).getActualTypeArguments()[0] : entity.get().getClass();
    final MessageBodyWriter writer = requireNonNull(mbw).get().getMessageBodyWriter(entity.get().getClass(), innerGenericType, annotations, mediaType);
    writer.writeTo(entity.get(), entity.get().getClass(), innerGenericType, annotations, mediaType, httpHeaders, entityStream);
}
Also used : ParameterizedType(java.lang.reflect.ParameterizedType) MediaType(javax.ws.rs.core.MediaType) ParameterizedType(java.lang.reflect.ParameterizedType) Type(java.lang.reflect.Type) MessageBodyWriter(javax.ws.rs.ext.MessageBodyWriter)

Example 20 with MessageBodyWriter

use of javax.ws.rs.ext.MessageBodyWriter in project jersey by jersey.

the class PatchingInterceptor method aroundReadFrom.

@SuppressWarnings("unchecked")
@Override
public Object aroundReadFrom(ReaderInterceptorContext readerInterceptorContext) throws IOException, WebApplicationException {
    // Get the resource we are being called on, and find the GET method
    Object resource = uriInfo.getMatchedResources().get(0);
    Method found = null;
    for (Method next : resource.getClass().getMethods()) {
        if (next.getAnnotation(GET.class) != null) {
            found = next;
            break;
        }
    }
    if (found == null) {
        throw new InternalServerErrorException("No matching GET method on resource");
    }
    // Invoke the get method to get the state we are trying to patch
    Object bean;
    try {
        bean = found.invoke(resource);
    } catch (Exception e) {
        throw new WebApplicationException(e);
    }
    // Convert this object to a an array of bytes
    ByteArrayOutputStream baos = new ByteArrayOutputStream();
    MessageBodyWriter bodyWriter = workers.getMessageBodyWriter(bean.getClass(), bean.getClass(), new Annotation[0], MediaType.APPLICATION_JSON_TYPE);
    bodyWriter.writeTo(bean, bean.getClass(), bean.getClass(), new Annotation[0], MediaType.APPLICATION_JSON_TYPE, new MultivaluedHashMap<String, Object>(), baos);
    // Use the Jackson 2.x classes to convert both the incoming patch
    // and the current state of the object into a JsonNode / JsonPatch
    ObjectMapper mapper = new ObjectMapper();
    JsonNode serverState = mapper.readValue(baos.toByteArray(), JsonNode.class);
    JsonNode patchAsNode = mapper.readValue(readerInterceptorContext.getInputStream(), JsonNode.class);
    JsonPatch patch = JsonPatch.fromJson(patchAsNode);
    try {
        // Apply the patch
        JsonNode result = patch.apply(serverState);
        // Stream the result & modify the stream on the readerInterceptor
        ByteArrayOutputStream resultAsByteArray = new ByteArrayOutputStream();
        mapper.writeValue(resultAsByteArray, result);
        readerInterceptorContext.setInputStream(new ByteArrayInputStream(resultAsByteArray.toByteArray()));
        // Pass control back to the Jersey code
        return readerInterceptorContext.proceed();
    } catch (JsonPatchException ex) {
        throw new InternalServerErrorException("Error applying patch.", ex);
    }
}
Also used : WebApplicationException(javax.ws.rs.WebApplicationException) JsonNode(com.fasterxml.jackson.databind.JsonNode) Method(java.lang.reflect.Method) ByteArrayOutputStream(java.io.ByteArrayOutputStream) JsonPatch(com.github.fge.jsonpatch.JsonPatch) JsonPatchException(com.github.fge.jsonpatch.JsonPatchException) IOException(java.io.IOException) InternalServerErrorException(javax.ws.rs.InternalServerErrorException) WebApplicationException(javax.ws.rs.WebApplicationException) JsonPatchException(com.github.fge.jsonpatch.JsonPatchException) ByteArrayInputStream(java.io.ByteArrayInputStream) GET(javax.ws.rs.GET) InternalServerErrorException(javax.ws.rs.InternalServerErrorException) MessageBodyWriter(javax.ws.rs.ext.MessageBodyWriter) ObjectMapper(com.fasterxml.jackson.databind.ObjectMapper)

Aggregations

MessageBodyWriter (javax.ws.rs.ext.MessageBodyWriter)25 MediaType (javax.ws.rs.core.MediaType)10 Test (org.junit.Test)10 ByteArrayOutputStream (java.io.ByteArrayOutputStream)6 OutputStreamWriter (java.io.OutputStreamWriter)6 Writer (java.io.Writer)6 Type (java.lang.reflect.Type)6 IOException (java.io.IOException)5 MessageBodyReader (javax.ws.rs.ext.MessageBodyReader)5 List (java.util.List)4 Map (java.util.Map)4 WebApplicationException (javax.ws.rs.WebApplicationException)4 MultivaluedMap (javax.ws.rs.core.MultivaluedMap)4 ByteArrayInputStream (java.io.ByteArrayInputStream)3 OutputStream (java.io.OutputStream)3 Annotation (java.lang.annotation.Annotation)3 ArrayList (java.util.ArrayList)3 Produces (javax.ws.rs.Produces)3 InjectionManager (org.glassfish.jersey.internal.inject.InjectionManager)3 File (java.io.File)2