Java Code Examples for javax.ws.rs.ext.MessageBodyWriter#writeTo()

The following examples show how to use javax.ws.rs.ext.MessageBodyWriter#writeTo() . You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source File: OccurrenceDwcXMLBodyWriterTest.java    From occurrence with Apache License 2.0 6 votes vote down vote up
@Test
public void testOccurrenceXML() throws IOException {
  MessageBodyWriter<Occurrence> occurrenceDwcXMLBodyWriter = new OccurrenceDwcXMLBodyWriter();
  ByteArrayOutputStream baos = new ByteArrayOutputStream();
  Occurrence occ = new Occurrence();

  occ.setCountry(Country.MADAGASCAR);
  occ.setVerbatimField(DwcTerm.verbatimLocality, "mad");
  occ.setReferences(URI.create("http://www.gbif.org"));

  Term customTerm = TermFactory.instance().findTerm("MyTerm");
  occ.setVerbatimField(customTerm, "MyTerm value");

  occurrenceDwcXMLBodyWriter.writeTo(occ, null, null, null, null, null, baos);

  String expectedContent = IOUtils.toString(new FileInputStream(FileUtils.getClasspathFile("dwc_xml/occurrence.xml")));
  assertEquals(CharMatcher.WHITESPACE.removeFrom(expectedContent), CharMatcher.WHITESPACE.removeFrom(baos.toString()));
}
 
Example 2
Source File: ErrorPageGenerator.java    From ameba with MIT License 6 votes vote down vote up
/**
 * <p>writeViewable.</p>
 *
 * @param viewable     a {@link org.glassfish.jersey.server.mvc.Viewable} object.
 * @param mediaType    a {@link javax.ws.rs.core.MediaType} object.
 * @param httpHeaders  a {@link javax.ws.rs.core.MultivaluedMap} object.
 * @param entityStream a {@link java.io.OutputStream} object.
 * @throws java.io.IOException if any.
 */
protected void writeViewable(Viewable viewable,
                             MediaType mediaType,
                             MultivaluedMap<String, Object> httpHeaders,
                             OutputStream entityStream) throws IOException {
    MessageBodyWriter<Viewable> writer = workers.get().getMessageBodyWriter(Viewable.class, null,
            new Annotation[]{}, null);
    if (writer != null) {
        writer.writeTo(viewable,
                Viewable.class,
                Viewable.class,
                new Annotation[0],
                mediaType,
                httpHeaders,
                entityStream);
    }
}
 
Example 3
Source File: OptionalMessageBodyWriter.java    From dropwizard-java8 with Apache License 2.0 6 votes vote down vote up
@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 new NotFoundException();
    }

    final Type innerGenericType = (genericType instanceof ParameterizedType) ?
        ((ParameterizedType) genericType).getActualTypeArguments()[0] : entity.get().getClass();

    MessageBodyWriter writer = mbw.get().getMessageBodyWriter(entity.get().getClass(),
        innerGenericType, annotations, mediaType);
    writer.writeTo(entity.get(), entity.get().getClass(),
        innerGenericType, annotations, mediaType, httpHeaders, entityStream);
}
 
Example 4
Source File: BinaryDataProviderTest.java    From cxf with Apache License 2.0 6 votes vote down vote up
@SuppressWarnings({ "unchecked", "rawtypes" })
@Test
public void testWriteTo() throws Exception {
    MessageBodyWriter p = new BinaryDataProvider();
    ByteArrayOutputStream os = new ByteArrayOutputStream();
    p.writeTo(new byte[]{'h', 'i'}, null, null, null, null, null, os);
    assertArrayEquals(new String("hi").getBytes(), os.toByteArray());
    ByteArrayInputStream is = new ByteArrayInputStream("hi".getBytes());
    os = new ByteArrayOutputStream();
    p.writeTo(is, null, null, null, null, null, os);
    assertArrayEquals(os.toByteArray(), new String("hi").getBytes());

    Reader r = new StringReader("hi");
    os = new ByteArrayOutputStream();
    p.writeTo(r, null, null, null, MediaType.valueOf("text/xml"), null, os);
    assertArrayEquals(os.toByteArray(), new String("hi").getBytes());

    os = new ByteArrayOutputStream();
    p.writeTo(new StreamingOutputImpl(), null, null, null,
              MediaType.valueOf("text/xml"), null, os);
    assertArrayEquals(os.toByteArray(), new String("hi").getBytes());
}
 
Example 5
Source File: ContainerResponseTest.java    From everrest with Eclipse Public License 2.0 6 votes vote down vote up
private Answer<Void> writeEntity() {
    return invocation -> {
        MessageBodyWriter messageBodyWriter = (MessageBodyWriter)invocation.getArguments()[1];
        Object entity = containerResponse.getEntity();
        if (entity != null) {
            messageBodyWriter.writeTo(entity,
                                      entity.getClass(),
                                      containerResponse.getEntityType(),
                                      null,
                                      containerResponse.getContentType(),
                                      containerResponse.getHttpHeaders(),
                                      entityStream);
        }
        return null;
    };
}
 
Example 6
Source File: PrimitiveTextProviderTest.java    From cxf with Apache License 2.0 6 votes vote down vote up
@Test
public void testWriteStringISO() throws Exception {
    MessageBodyWriter<String> p = new PrimitiveTextProvider<>();
    ByteArrayOutputStream os = new ByteArrayOutputStream();
    MultivaluedMap<String, Object> headers = new MetadataMap<>();

    String eWithAcute = "\u00E9";
    String helloStringUTF16 = "Hello, my name is F" + eWithAcute + "lix Agn" + eWithAcute + "s";

    p.writeTo(helloStringUTF16,
              String.class, String.class, null, MediaType.valueOf("text/plain;charset=ISO-8859-1"),
              headers, os);

    byte[] iso88591bytes = helloStringUTF16.getBytes("ISO-8859-1");
    String helloStringISO88591 = new String(iso88591bytes, "ISO-8859-1");

    assertEquals(helloStringISO88591, os.toString("ISO-8859-1"));
}
 
Example 7
Source File: SimpleTypeJsonProvider.java    From cxf with Apache License 2.0 6 votes vote down vote up
@Override
public void writeTo(T t, Class<?> type, Type genericType, Annotation[] annotations, MediaType mediaType,
                    MultivaluedMap<String, Object> headers, OutputStream os)
    throws IOException, WebApplicationException {
    if (!supportSimpleTypesOnly && !InjectionUtils.isPrimitive(type)) {
        @SuppressWarnings("unchecked")
        MessageBodyWriter<T> next =
            (MessageBodyWriter<T>)providers.getMessageBodyWriter(type, genericType, annotations, mediaType);
        JAXRSUtils.getCurrentMessage().put(ProviderFactory.ACTIVE_JAXRS_PROVIDER_KEY, this);
        try {
            next.writeTo(t, type, genericType, annotations, mediaType, headers, os);
        } finally {
            JAXRSUtils.getCurrentMessage().put(ProviderFactory.ACTIVE_JAXRS_PROVIDER_KEY, null);
        }
    } else {
        os.write(StringUtils.toBytesASCII("{\"" + type.getSimpleName().toLowerCase() + "\":"));
        writeQuote(os, type);
        primitiveHelper.writeTo(t, type, genericType, annotations, mediaType, headers, os);
        writeQuote(os, type);
        os.write(StringUtils.toBytesASCII("}"));
    }
}
 
Example 8
Source File: AWSRequest.java    From dremio-oss with Apache License 2.0 6 votes vote down vote up
@Override
public InputStream getContent() {
  ByteArrayOutputStream baos = new ByteArrayOutputStream();
  final Object entity = clientRequestContext.getEntity();
  if (entity == null) {
    return null;
  } else {
    MessageBodyWriter messageBodyWriter = workers.getMessageBodyWriter(entity.getClass(), entity.getClass(),
      new Annotation[]{}, clientRequestContext.getMediaType());
    try {
      // use the MBW to serialize entity into baos
      messageBodyWriter.writeTo(entity,
        entity.getClass(), entity.getClass(), new Annotation[] {},
        clientRequestContext.getMediaType(), new MultivaluedHashMap<String, Object>(),
        baos);
    } catch (IOException e) {
      throw new RuntimeException(
        "Error while serializing entity.", e);
    }
    return new ByteArrayInputStream(baos.toByteArray());
  }
}
 
Example 9
Source File: OutboundSseEventBodyWriter.java    From cxf with Apache License 2.0 6 votes vote down vote up
@SuppressWarnings("unchecked")
private<T> void writePayloadTo(Class<T> cls, Type type, Annotation[] anns, MediaType mt,
        MultivaluedMap<String, Object> headers, Object data, OutputStream os)
            throws IOException, WebApplicationException {

    MessageBodyWriter<T> writer = null;
    if (message != null && factory != null) {
        writer = factory.createMessageBodyWriter(cls, type, anns, mt, message);
    }

    if (writer == null) {
        throw new InternalServerErrorException("No suitable message body writer for class: " + cls.getName());
    }

    writer.writeTo((T)data, cls, type, anns, mt, headers, os);
}
 
Example 10
Source File: AegisElementProviderTest.java    From cxf with Apache License 2.0 5 votes vote down vote up
@Test
public void testNoNamespaceWriteTo() throws Exception {
    MessageBodyWriter<Object> p = new NoNamespaceAegisElementProvider<>();
    ByteArrayOutputStream os = new ByteArrayOutputStream();
    AegisTestBean bean = new AegisTestBean();
    bean.setBoolValue(Boolean.TRUE);
    bean.setStrValue("hovercraft");
    p.writeTo(bean, null, null, new Annotation[]{},
              MediaType.APPLICATION_OCTET_STREAM_TYPE,
              new MetadataMap<String, Object>(), os);
    byte[] bytes = os.toByteArray();
    String xml = new String(bytes, "utf-8");
    assertEquals(noNamespaceXml, xml);
}
 
Example 11
Source File: VerbatimOccurrenceDwcXMLBodyWriterTest.java    From occurrence with Apache License 2.0 5 votes vote down vote up
@Test
public void testVerbatimOccurrenceXML() throws IOException{
  MessageBodyWriter<VerbatimOccurrence> occurrenceDwcXMLBodyWriter = new OccurrenceVerbatimDwcXMLBodyWriter();
  ByteArrayOutputStream baos = new ByteArrayOutputStream();
  VerbatimOccurrence occ = new VerbatimOccurrence();

  occ.setVerbatimField(DwcTerm.verbatimLocality, "mad");
  Term customTerm = TermFactory.instance().findTerm("MyTerm");
  occ.setVerbatimField(customTerm, "MyTerm value");

  occurrenceDwcXMLBodyWriter.writeTo(occ, null, null, null, null, null, baos);

  String expectedContent = IOUtils.toString(new FileInputStream(FileUtils.getClasspathFile("dwc_xml/verbatim_occurrence.xml")));
  assertEquals(CharMatcher.WHITESPACE.removeFrom(expectedContent), CharMatcher.WHITESPACE.removeFrom(baos.toString()));
}
 
Example 12
Source File: MultipartFormDataWriter.java    From everrest with Eclipse Public License 2.0 5 votes vote down vote up
@SuppressWarnings("unchecked")
protected void writeItem(OutputItem item, OutputStream output, byte[] boundary) throws IOException {
    output.write(HYPHENS);
    output.write(boundary);
    output.write(NEW_LINE);
    final MediaType mediaType = item.getMediaType();
    final Class<?> type = item.getType();
    final Type genericType = item.getGenericType();
    final MessageBodyWriter writer = providers.getMessageBodyWriter(type, genericType, EMPTY, mediaType);
    if (writer == null) {
        throw new RuntimeException(
                String.format("Unable to find a MessageBodyWriter for media type '%s' and class '%s'", mediaType, type.getName()));
    }
    final MultivaluedMap<String, String> myHeaders = new MultivaluedMapImpl();
    String contentDispositionHeader = "form-data; name=\"" + item.getName() + '"';
    final String filename = item.getFilename();
    if (filename != null) {
        contentDispositionHeader += ("; filename=\"" + item.getFilename() + "\"");
    }
    myHeaders.putSingle("Content-Disposition", contentDispositionHeader);
    if (mediaType != null) {
        myHeaders.putSingle("Content-Type", mediaType.toString());
    }
    myHeaders.putAll(item.getHeaders());
    writeHeaders(myHeaders, output);
    writer.writeTo(item.getEntity(), type, genericType, EMPTY, mediaType, myHeaders, output);
    output.write(NEW_LINE);
}
 
Example 13
Source File: ByteArrayContainerResponseWriter.java    From everrest with Eclipse Public License 2.0 5 votes vote down vote up
@Override
@SuppressWarnings({"unchecked"})
public void writeBody(GenericContainerResponse response, MessageBodyWriter entityWriter) throws IOException {
    if (committed) {
        return;
    }
    ByteArrayOutputStream out = new ByteArrayOutputStream();
    Object entity = response.getEntity();
    if (entity != null) {
        entityWriter.writeTo(entity, entity.getClass(), response.getEntityType(), null, response.getContentType(),
                             response.getHttpHeaders(), out);
        body = out.toByteArray();
    }
}
 
Example 14
Source File: ServletContainerResponseWriter.java    From everrest with Eclipse Public License 2.0 5 votes vote down vote up
@Override
@SuppressWarnings({"unchecked"})
public void writeBody(GenericContainerResponse response, MessageBodyWriter entityWriter) throws IOException {
    if (servletResponse.isCommitted()) {
        return;
    }
    Object entity = response.getEntity();
    if (entity != null) {
        OutputStream out = servletResponse.getOutputStream();
        entityWriter.writeTo(entity, entity.getClass(), response.getEntityType(), null, response.getContentType(),
                             response.getHttpHeaders(), out);
        out.flush();
    }
}
 
Example 15
Source File: EverrestResponseWriter.java    From everrest with Eclipse Public License 2.0 5 votes vote down vote up
@Override
@SuppressWarnings({"unchecked"})
public void writeBody(GenericContainerResponse response, MessageBodyWriter entityWriter) throws IOException {
    if (committed) {
        return;
    }
    final ByteArrayOutputStream out = new ByteArrayOutputStream();
    final Object entity = response.getEntity();
    if (entity != null) {
        entityWriter.writeTo(entity, entity.getClass(), response.getEntityType(), null, response.getContentType(),
                             response.getHttpHeaders(), out);
        byte[] body = out.toByteArray();
        output.setBody(new String(body));
    }
}
 
Example 16
Source File: AegisElementProviderTest.java    From cxf with Apache License 2.0 5 votes vote down vote up
@Test
public void testWriteTo() throws Exception {
    MessageBodyWriter<Object> p = new AegisElementProvider<>();
    ByteArrayOutputStream os = new ByteArrayOutputStream();
    AegisTestBean bean = new AegisTestBean();
    bean.setBoolValue(Boolean.TRUE);
    bean.setStrValue("hovercraft");
    p.writeTo(bean, null, null, new Annotation[]{},
              MediaType.APPLICATION_OCTET_STREAM_TYPE,
              new MetadataMap<String, Object>(), os);
    byte[] bytes = os.toByteArray();
    String xml = new String(bytes, "utf-8");
    assertEquals(simpleBeanXml, xml);
}
 
Example 17
Source File: PrimitiveTextProviderTest.java    From cxf with Apache License 2.0 5 votes vote down vote up
@SuppressWarnings({ "unchecked", "rawtypes" })
@Test
public void testWriteBoolean() throws Exception {
    MessageBodyWriter p = new PrimitiveTextProvider();
    ByteArrayOutputStream os = new ByteArrayOutputStream();
    p.writeTo(Boolean.TRUE, null, null, null, MediaType.TEXT_PLAIN_TYPE, null, os);
    assertArrayEquals(new String("true").getBytes(), os.toByteArray());

    os = new ByteArrayOutputStream();

    final boolean value = true;
    p.writeTo(value, null, null, null, MediaType.TEXT_PLAIN_TYPE, null, os);
    assertArrayEquals(new String("true").getBytes(), os.toByteArray());
}
 
Example 18
Source File: MediaTypeExtension.java    From openhab-core with Eclipse Public License 2.0 5 votes vote down vote up
@Override
public void writeTo(final T object, final Class<?> type, final Type genericType, final Annotation[] annotations,
        final MediaType mediaType, final MultivaluedMap<String, Object> httpHeaders,
        final OutputStream entityStream) throws IOException, WebApplicationException {
    final MessageBodyWriter<T> writer = writers.get(mediaTypeWithoutParams(mediaType));
    if (writer != null) {
        writer.writeTo(object, type, genericType, annotations, mediaType, httpHeaders, entityStream);
    } else {
        throw new InternalServerErrorException("unsupported media type");
    }
}
 
Example 19
Source File: RxGenericBodyWriter.java    From rx-jersey with MIT License 5 votes vote down vote up
@SuppressWarnings("unchecked")
@Override
public void writeTo(Object entity, Class<?> type, Type genericType, Annotation[] annotations, MediaType mediaType, MultivaluedMap<String, Object> httpHeaders, OutputStream entityStream)
        throws IOException, WebApplicationException {

    final Type actualTypeArgument = actual(genericType);
    final MessageBodyWriter writer = workers.get().getMessageBodyWriter(entity.getClass(), actualTypeArgument, annotations, mediaType);

    writer.writeTo(entity, entity.getClass(), actualTypeArgument, annotations, mediaType, httpHeaders, entityStream);
}
 
Example 20
Source File: AegisElementProviderTest.java    From cxf with Apache License 2.0 4 votes vote down vote up
@Test
public void testReadWriteComplexMap() throws Exception {
    Map<AegisTestBean, AegisSuperBean> testMap = new HashMap<>();

    Class<InterfaceWithMap> iwithMapClass = InterfaceWithMap.class;
    Method method = iwithMapClass.getMethod("mapFunction");
    Type mapType = method.getGenericReturnType();

    AegisTestBean bean = new AegisTestBean();
    bean.setBoolValue(Boolean.TRUE);
    bean.setStrValue("hovercraft");

    AegisSuperBean bean2 = new AegisSuperBean();
    bean2.setBoolValue(Boolean.TRUE);
    bean2.setStrValue("hovercraft2");
    testMap.put(bean, bean2);

    MessageBodyWriter<Map<AegisTestBean, AegisSuperBean>> writer
        = new AegisElementProvider<>();
    ByteArrayOutputStream os = new ByteArrayOutputStream();

    writer.writeTo(testMap, testMap.getClass(), mapType, new Annotation[]{},
                   MediaType.APPLICATION_OCTET_STREAM_TYPE,
                   new MetadataMap<String, Object>(), os);
    byte[] bytes = os.toByteArray();
    String xml = new String(bytes, "utf-8");
    MessageBodyReader<Map<AegisTestBean, AegisSuperBean>> reader
        = new AegisElementProvider<>();
    byte[] simpleBytes = xml.getBytes("utf-8");

    Map<AegisTestBean, AegisSuperBean> map2 = reader.readFrom(null, mapType, new Annotation[]{},
                                                              MediaType.APPLICATION_OCTET_STREAM_TYPE,
                                                              new MetadataMap<String, String>(),
                                                              new ByteArrayInputStream(simpleBytes));
    assertEquals(1, map2.size());
    Map.Entry<AegisTestBean, AegisSuperBean> entry = map2.entrySet().iterator().next();
    AegisTestBean bean1 = entry.getKey();
    assertEquals("hovercraft", bean1.getStrValue());
    assertTrue(bean1.getBoolValue());
    AegisTestBean bean22 = entry.getValue();
    assertEquals("hovercraft2", bean22.getStrValue());
    assertTrue(bean22.getBoolValue());

}