Java Code Examples for javax.ws.rs.ext.MessageBodyReader#readFrom()

The following examples show how to use javax.ws.rs.ext.MessageBodyReader#readFrom() . 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: InboundSseEventImpl.java    From cxf with Apache License 2.0 6 votes vote down vote up
private <T> T read(Class<T> messageType, Type type, MediaType mediaType) {
    if (data == null) {
        return null;
    }

    final Annotation[] annotations = new Annotation[0];
    final MultivaluedMap<String, String> headers = new MultivaluedHashMap<>(0);
    
    final MessageBodyReader<T> reader = factory.createMessageBodyReader(messageType, type, 
        annotations, mediaType, message);
        
    if (reader == null) {
        throw new RuntimeException("No suitable message body reader for class: " + messageType.getName());
    }

    try (ByteArrayInputStream is = new ByteArrayInputStream(data.getBytes(StandardCharsets.UTF_8))) {
        return reader.readFrom(messageType, type, annotations, mediaType, headers, is);
    } catch (final IOException ex) {
        throw new RuntimeException("Unable to read data of type " + messageType.getName(), ex);
    }
}
 
Example 2
Source File: ProjectResource.java    From component-runtime with Apache License 2.0 6 votes vote down vote up
private ProjectModel readProjectModel(final String compressedModel, final Providers providers) {
    final MessageBodyReader<ProjectModel> jsonReader = providers
            .getMessageBodyReader(ProjectModel.class, ProjectModel.class, NO_ANNOTATION, APPLICATION_JSON_TYPE);
    final ProjectModel model;
    try (final InputStream gzipInputStream = new ByteArrayInputStream(debase64(compressedModel))) {
        model = jsonReader
                .readFrom(ProjectModel.class, ProjectModel.class, NO_ANNOTATION, APPLICATION_JSON_TYPE,
                        new MultivaluedHashMap<>(), gzipInputStream);
    } catch (final IOException e) {
        throw new WebApplicationException(Response
                .status(Response.Status.INTERNAL_SERVER_ERROR)
                .entity(new ErrorMessage(e.getMessage()))
                .type(APPLICATION_JSON_TYPE)
                .build());
    }
    return model;
}
 
Example 3
Source File: SimpleTypeJsonProvider.java    From cxf with Apache License 2.0 6 votes vote down vote up
@Override
public T readFrom(Class<T> type, Type genericType, Annotation[] annotations, MediaType mediaType,
                  MultivaluedMap<String, String> headers, InputStream is)
    throws IOException, WebApplicationException {
    if (!supportSimpleTypesOnly && !InjectionUtils.isPrimitive(type)) {
        MessageBodyReader<T> next =
            providers.getMessageBodyReader(type, genericType, annotations, mediaType);
        JAXRSUtils.getCurrentMessage().put(ProviderFactory.ACTIVE_JAXRS_PROVIDER_KEY, this);
        try {
            return next.readFrom(type, genericType, annotations, mediaType, headers, is);
        } finally {
            JAXRSUtils.getCurrentMessage().put(ProviderFactory.ACTIVE_JAXRS_PROVIDER_KEY, null);
        }
    }
    String data = IOUtils.toString(is).trim();
    int index = data.indexOf(':');
    data = data.substring(index + 1, data.length() - 1).trim();
    if (data.startsWith("\"")) {
        data = data.substring(1, data.length() - 1);
    }
    return primitiveHelper.readFrom(type, genericType, annotations, mediaType, headers,
                                    new ByteArrayInputStream(StringUtils.toBytesUTF8(data)));
}
 
Example 4
Source File: MapMultipartFormDataMessageBodyReader.java    From everrest with Eclipse Public License 2.0 6 votes vote down vote up
@Override
public Map<String, InputItem> readFrom(Class<Map<String, InputItem>> type, Type genericType, Annotation[] annotations,
                                       MediaType mediaType, MultivaluedMap<String, String> httpHeaders, InputStream entityStream)
        throws IOException, WebApplicationException {
    final Type genericSuperclass = ParameterizedTypeImpl.newParameterizedType(Iterator.class, FileItem.class);
    final MessageBodyReader<Iterator> multipartReader =
            providers.getMessageBodyReader(Iterator.class, genericSuperclass, annotations, mediaType);
    final Iterator iterator =
            multipartReader.readFrom(Iterator.class, genericSuperclass, annotations, mediaType, httpHeaders, entityStream);
    final Map<String, InputItem> result = new LinkedHashMap<>();
    while (iterator.hasNext()) {
        final DefaultInputItem item = new DefaultInputItem((FileItem)iterator.next(), providers);
        result.put(item.getName(), item);
    }
    return result;
}
 
Example 5
Source File: MultipartProvider.java    From cxf with Apache License 2.0 6 votes vote down vote up
private <T> Object fromAttachment(Attachment multipart, Class<T> c, Type t, Annotation[] anns)
    throws IOException {
    if (DataHandler.class.isAssignableFrom(c)) {
        return multipart.getDataHandler();
    } else if (DataSource.class.isAssignableFrom(c)) {
        return multipart.getDataHandler().getDataSource();
    } else if (Attachment.class.isAssignableFrom(c)) {
        return multipart;
    } else {
        if (mediaTypeSupported(multipart.getContentType())) {
            mc.put("org.apache.cxf.multipart.embedded", true);
            mc.put("org.apache.cxf.multipart.embedded.ctype", multipart.getContentType());
            mc.put("org.apache.cxf.multipart.embedded.input",
                   multipart.getDataHandler().getInputStream());
            anns = new Annotation[]{};
        }
        MessageBodyReader<T> r =
            mc.getProviders().getMessageBodyReader(c, t, anns, multipart.getContentType());
        if (r != null) {
            InputStream is = multipart.getDataHandler().getInputStream();
            return r.readFrom(c, t, anns, multipart.getContentType(), multipart.getHeaders(),
                              is);
        }
    }
    return null;
}
 
Example 6
Source File: SseEventBuilder.java    From cxf with Apache License 2.0 6 votes vote down vote up
private <T> T readData(Class<T> type, Type genericType, MediaType mediaType) {
    if (data == null) {
        return null;
    }
    try {
        MessageBodyReader<T> mbr = providers.getMessageBodyReader(type, genericType, EMPTY_ANNOTATIONS,
                mediaType);
        if (mbr == null) {
            throw new ProcessingException("No MessageBodyReader found to handle class type, " + type
                    + " using MediaType, " + mediaType);
        }
        return mbr.readFrom(type, genericType, EMPTY_ANNOTATIONS, mediaType, new MultivaluedHashMap<>(),
                new ByteArrayInputStream(data.getBytes()));
    } catch (Exception ex) {
        throw new ProcessingException(ex);
    }
}
 
Example 7
Source File: FormParameterResolver.java    From everrest with Eclipse Public License 2.0 5 votes vote down vote up
@SuppressWarnings({"unchecked"})
private MultivaluedMap<String, String> readForm(ApplicationContext context, boolean decode) throws java.io.IOException {
    MediaType contentType = context.getHttpHeaders().getMediaType();
    ParameterizedType multivaluedMapType = newParameterizedType(MultivaluedMap.class, String.class, String.class);
    MessageBodyReader reader = context.getProviders().getMessageBodyReader(MultivaluedMap.class, multivaluedMapType, null, contentType);
    if (reader == null) {
        throw new IllegalStateException(String.format("Can't find appropriate entity reader for entity type %s and content-type %s",
                                                      MultivaluedMap.class.getName(), contentType));
    }

    reader.readFrom(MultivaluedMap.class,
                    multivaluedMapType,
                    null,
                    contentType,
                    context.getHttpHeaders().getRequestHeaders(),
                    context.getContainerRequest().getEntityStream());
    MultivaluedMap<String, String> form;
    if (decode) {
        form = (MultivaluedMap<String, String>)context.getAttributes().get("org.everrest.provider.entity.decoded.form");
    } else {
        form = (MultivaluedMap<String, String>)context.getAttributes().get("org.everrest.provider.entity.encoded.form");
    }
    if (form == null) {
        form = new MultivaluedMapImpl();
    }

    return form;
}
 
Example 8
Source File: AegisElementProviderTest.java    From cxf with Apache License 2.0 5 votes vote down vote up
@Test
public void testReadFrom() throws Exception {
    MessageBodyReader<AegisTestBean> p = new AegisElementProvider<>();
    byte[] simpleBytes = simpleBeanXml.getBytes("utf-8");
    AegisTestBean bean = p.readFrom(AegisTestBean.class, null, null,
                                      null, null, new ByteArrayInputStream(simpleBytes));
    assertEquals("hovercraft", bean.getStrValue());
    assertTrue(bean.getBoolValue());
}
 
Example 9
Source File: DOM4JProvider.java    From cxf with Apache License 2.0 5 votes vote down vote up
public org.dom4j.Document readFrom(Class<org.dom4j.Document> cls, Type type,
                Annotation[] anns, MediaType mt,
                MultivaluedMap<String, String> headers, InputStream is)
    throws IOException, WebApplicationException {
    MessageBodyReader<org.w3c.dom.Document> reader =
        providers.getMessageBodyReader(DOM_DOC_CLS, DOM_DOC_CLS, anns, mt);
    if (reader == null) {
        throw ExceptionUtils.toNotSupportedException(null, null);
    }
    org.w3c.dom.Document domDoc =
        reader.readFrom(DOM_DOC_CLS, DOM_DOC_CLS, anns, mt, headers, is);
    return new org.dom4j.io.DOMReader().read(domDoc);
}
 
Example 10
Source File: PrimitiveTextProviderTest.java    From cxf with Apache License 2.0 5 votes vote down vote up
@Test
public void testReadChineeseChars() throws Exception {
    String s = "中文";

    MessageBodyReader<String> p = new PrimitiveTextProvider<>();

    String value = p.readFrom(String.class, null,
            new Annotation[]{},
            MediaType.valueOf(MediaType.APPLICATION_XML + ";charset=UTF-8"), null,
            new ByteArrayInputStream(s.getBytes(StandardCharsets.UTF_8)));
    assertEquals(s, value);
}
 
Example 11
Source File: JSONProviderTest.java    From cxf with Apache License 2.0 5 votes vote down vote up
@Test
public void testReadFromTag() throws Exception {
    MessageBodyReader<TagVO> p = new JSONProvider<>();
    byte[] bytes = "{\"tagVO\":{\"group\":\"b\",\"name\":\"a\"}}"
        .getBytes();
    Object tagsObject = p.readFrom(TagVO.class, null, null,
                                      null, null, new ByteArrayInputStream(bytes));
    TagVO tag = (TagVO)tagsObject;
    assertEquals("a", tag.getName());
    assertEquals("b", tag.getGroup());
}
 
Example 12
Source File: JSONProviderTest.java    From cxf with Apache License 2.0 5 votes vote down vote up
@Test
public void testReadMalformedJson() throws Exception {
    MessageBodyReader<Tags> p = new JSONProvider<>();
    byte[] bytes = "junk".getBytes();

    try {
        p.readFrom(Tags.class, null, null,
                                       null, null, new ByteArrayInputStream(bytes));
        fail("404 is expected");
    } catch (WebApplicationException ex) {
        assertEquals(Response.Status.BAD_REQUEST.getStatusCode(), ex.getResponse().getStatus());
    }
}
 
Example 13
Source File: SourceProviderTest.java    From cxf with Apache License 2.0 5 votes vote down vote up
private <T> T verifyRead(MessageBodyReader<T> p, Class<?> type) throws Exception {
    @SuppressWarnings("unchecked")
    Class<T> cls = (Class<T>)type;
    return p.readFrom(cls,
               null, null, null, null,
               new ByteArrayInputStream("<test/>".getBytes()));
}
 
Example 14
Source File: BinaryDataProviderTest.java    From cxf with Apache License 2.0 5 votes vote down vote up
@SuppressWarnings({ "unchecked", "rawtypes" })
@Test
public void testReadBytesFromUtf8() throws Exception {
    MessageBodyReader p = new BinaryDataProvider();
    byte[] utf8Bytes = "世界ーファイル".getBytes("UTF-16");
    byte[] readBytes = (byte[])p.readFrom(byte[].class, byte[].class, new Annotation[]{},
                                      MediaType.APPLICATION_OCTET_STREAM_TYPE,
                                      new MetadataMap<String, Object>(),
                                      new ByteArrayInputStream(utf8Bytes));
    assertArrayEquals(utf8Bytes, readBytes);
}
 
Example 15
Source File: BinaryDataProviderTest.java    From cxf with Apache License 2.0 5 votes vote down vote up
@SuppressWarnings({ "unchecked", "rawtypes" })
@Test
public void testReadFrom() throws Exception {
    MessageBodyReader p = new BinaryDataProvider();
    byte[] bytes = (byte[])p.readFrom(byte[].class, byte[].class, new Annotation[]{},
                                      MediaType.APPLICATION_OCTET_STREAM_TYPE,
                                      new MetadataMap<String, Object>(),
                                      new ByteArrayInputStream("hi".getBytes()));
    assertArrayEquals(new String("hi").getBytes(), bytes);

    InputStream is = (InputStream)p.readFrom(InputStream.class, InputStream.class, new Annotation[]{},
                                             MediaType.APPLICATION_OCTET_STREAM_TYPE,
                                             new MetadataMap<String, Object>(),
        new ByteArrayInputStream("hi".getBytes()));
    bytes = IOUtils.readBytesFromStream(is);
    assertArrayEquals(new String("hi").getBytes(), bytes);

    Reader r = (Reader)p.readFrom(Reader.class, Reader.class, new Annotation[]{},
                                  MediaType.APPLICATION_OCTET_STREAM_TYPE,
                                  new MetadataMap<String, Object>(),
                                  new ByteArrayInputStream("hi".getBytes()));
    assertEquals(IOUtils.toString(r), "hi");

    StreamingOutput so = (StreamingOutput)p.readFrom(StreamingOutput.class, StreamingOutput.class,
                                  new Annotation[]{},
                                  MediaType.APPLICATION_OCTET_STREAM_TYPE,
                                  new MetadataMap<String, Object>(),
                                  new ByteArrayInputStream("hi".getBytes()));
    ByteArrayOutputStream baos = new ByteArrayOutputStream();
    so.write(baos);
    bytes = baos.toByteArray();
    assertArrayEquals(new String("hi").getBytes(), bytes);
}
 
Example 16
Source File: Attachment.java    From cxf with Apache License 2.0 5 votes vote down vote up
public <T> T getObject(Class<T> cls) {
    if (providers != null) {
        MessageBodyReader<T> mbr =
            providers.getMessageBodyReader(cls, cls, new Annotation[]{}, getContentType());
        if (mbr != null) {
            try {
                return mbr.readFrom(cls, cls, new Annotation[]{}, getContentType(),
                                    headers, getDataHandler().getInputStream());
            } catch (Exception ex) {
                throw ExceptionUtils.toInternalServerErrorException(ex, null);
            }
        }
    }
    return null;
}
 
Example 17
Source File: JAXRSUtils.java    From cxf with Apache License 2.0 5 votes vote down vote up
@SuppressWarnings("unchecked")
public static Object readFromMessageBodyReader(List<ReaderInterceptor> readers,
                                               Class<?> targetTypeClass,
                                               Type parameterType,
                                               Annotation[] parameterAnnotations,
                                               InputStream is,
                                               MediaType mediaType,
                                               Message m) throws IOException, WebApplicationException {

    // Verbose but avoids an extra context instantiation for the typical path
    if (readers.size() > 1) {
        ReaderInterceptor first = readers.remove(0);
        ReaderInterceptorContext context = new ReaderInterceptorContextImpl(targetTypeClass,
                                                                        parameterType,
                                                                        parameterAnnotations,
                                                                        is,
                                                                        m,
                                                                        readers);

        return first.aroundReadFrom(context);
    }
    MessageBodyReader<?> provider = ((ReaderInterceptorMBR)readers.get(0)).getMBR();
    @SuppressWarnings("rawtypes")
    Class cls = targetTypeClass;
    return provider.readFrom(
              cls, parameterType, parameterAnnotations, mediaType,
              new HttpHeadersImpl(m).getRequestHeaders(), is);
}
 
Example 18
Source File: ActiveMQ.java    From activemq-artemis with Apache License 2.0 5 votes vote down vote up
public static <T> T getEntity(ClientMessage msg, Class<T> type, Type genericType, ResteasyProviderFactory factory) {
   int size = msg.getBodySize();
   if (size <= 0)
      return null;

   byte[] body = new byte[size];
   msg.getBodyBuffer().readBytes(body);

   String contentType = msg.getStringProperty(HttpHeaderProperty.CONTENT_TYPE);
   if (contentType == null) {
      throw new UnknownMediaType("Message did not have a Content-Type header cannot extract entity");
   }
   MediaType ct = MediaType.valueOf(contentType);
   MessageBodyReader<T> reader = factory.getMessageBodyReader(type, genericType, null, ct);
   if (reader == null) {
      throw new UnmarshalException("Unable to find a JAX-RS reader for type " + type.getName() + " and media type " + contentType);
   }

   Providers current = ResteasyProviderFactory.getContextData(Providers.class);
   ResteasyProviderFactory.pushContext(Providers.class, factory);
   try {
      return reader.readFrom(type, genericType, null, ct, new Headers<String>(), new ByteArrayInputStream(body));
   } catch (IOException e) {
      throw new RuntimeException(e);
   } finally {
      ResteasyProviderFactory.popContextData(Providers.class);
      if (current != null)
         ResteasyProviderFactory.pushContext(Providers.class, current);
   }
}
 
Example 19
Source File: DefaultInputItem.java    From everrest with Eclipse Public License 2.0 5 votes vote down vote up
@Override
public <T> T getBody(Class<T> type, Type genericType) throws IOException {
    final MediaType mediaType = getMediaType();
    final MessageBodyReader<T> reader = providers.getMessageBodyReader(type, genericType, EMPTY, mediaType);
    if (reader == null) {
        throw new RuntimeException(
                String.format("Unable to find a MessageBodyReader for media type '%s' and class '%s'", mediaType, type.getName()));
    }
    return reader.readFrom(type, genericType, EMPTY, mediaType, headers, getBody());
}
 
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());

}