javax.ws.rs.ext.MessageBodyReader Java Examples

The following examples show how to use javax.ws.rs.ext.MessageBodyReader. 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: ResourceUtilTest.java    From minnal with Apache License 2.0 6 votes vote down vote up
@Test
public void shouldGetContentAsMap() throws Exception {
	Map<String, Object> map = new HashMap<String, Object>();
	map.put("key1", "value1");
	byte[] bytes = new byte[10];
	MediaType mediaType = mock(MediaType.class);
	HttpHeaders httpHeaders = mock(HttpHeaders.class);
	when(httpHeaders.getMediaType()).thenReturn(mediaType);
	MessageBodyReader reader = mock(MessageBodyReader.class);
	when(reader.readFrom(eq(Map.class), eq(Map.class), eq(new Annotation[]{}), eq(mediaType), isNull(MultivaluedMap.class), any(InputStream.class))).thenReturn(map);
	Providers providers = mock(Providers.class);
	when(providers.getMessageBodyReader(Map.class, Map.class, new Annotation[]{}, mediaType)).thenReturn(reader);
	Object content = ResourceUtil.getContent(bytes, providers, httpHeaders, Map.class);
	assertTrue(content instanceof Map);
	assertEquals(content, map);
}
 
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: ProviderFactoryTest.java    From cxf with Apache License 2.0 6 votes vote down vote up
@Test
public void testSortEntityProviders() throws Exception {
    ProviderFactory pf = ServerProviderFactory.getInstance();
    pf.registerUserProvider(new TestStringProvider());
    pf.registerUserProvider(new PrimitiveTextProvider<Object>());

    List<ProviderInfo<MessageBodyReader<?>>> readers = pf.getMessageReaders();

    assertTrue(indexOf(readers, TestStringProvider.class)
               < indexOf(readers, PrimitiveTextProvider.class));

    List<ProviderInfo<MessageBodyWriter<?>>> writers = pf.getMessageWriters();

    assertTrue(indexOf(writers, TestStringProvider.class)
               < indexOf(writers, PrimitiveTextProvider.class));

}
 
Example #4
Source File: AdditionalRegistrationTest.java    From microprofile-rest-client with Apache License 2.0 6 votes vote down vote up
@Test
public void shouldRegisterAMultiTypedProviderInstanceWithPriorities() {
    MultiTypedProvider provider = new MultiTypedProvider();
    Map<Class<?>, Integer> priorities = new HashMap<>();
    priorities.put(ClientRequestFilter.class, 500);
    priorities.put(ClientResponseFilter.class, 501);
    priorities.put(MessageBodyReader.class, 502);
    priorities.put(MessageBodyWriter.class, 503);
    priorities.put(ReaderInterceptor.class, 504);
    priorities.put(WriterInterceptor.class, 505);
    priorities.put(ResponseExceptionMapper.class, 506);
    priorities.put(ParamConverterProvider.class, 507);
    RestClientBuilder builder = RestClientBuilder.newBuilder().register(provider, priorities);
    Configuration configuration = builder.getConfiguration();
    assertTrue(configuration.isRegistered(MultiTypedProvider.class), MultiTypedProvider.class + " should be registered");
    assertTrue(configuration.isRegistered(provider), MultiTypedProvider.class + " should be registered");
    Map<Class<?>, Integer> contracts = configuration.getContracts(MultiTypedProvider.class);
    assertEquals(contracts.size(), priorities.size(),
        "There should be "+priorities.size()+" provider types registered");
    for(Map.Entry<Class<?>, Integer> priority : priorities.entrySet()) {
        Integer contractPriority = contracts.get(priority.getKey());
        assertEquals(contractPriority, priority.getValue(), "The priority for "+priority.getKey()+" should be "+priority.getValue());
    }
}
 
Example #5
Source File: MapMultipartFormDataMessageBodyReaderTest.java    From everrest with Eclipse Public License 2.0 6 votes vote down vote up
@Test
public void readsMapOfInputItems() throws Exception {
    Class type = Map.class;
    ParameterizedType genericType = newParameterizedType(Map.class, String.class, InputItem.class);
    Annotation[] annotations = new Annotation[0];
    MediaType mediaType = MULTIPART_FORM_DATA_TYPE;
    MultivaluedMap<String, String> headers = new MultivaluedHashMap<>();
    InputStream in = mock(InputStream.class);

    FileItem fileItem = createFileItem("fileItem1");
    MessageBodyReader fileItemReader = createFileItemMessageBodyReader(annotations, mediaType, headers, in, fileItem);
    when(providers.getMessageBodyReader(eq(Iterator.class), eq(newParameterizedType(Iterator.class, FileItem.class)), aryEq(annotations), eq(mediaType)))
            .thenReturn(fileItemReader);

    Map<String, InputItem> inputItems = mapMultipartFormDataMessageBodyReader.readFrom(type, genericType, annotations, mediaType, headers, in);
    assertEquals(1, inputItems.size());
    assertEquals(fileItem.getFieldName(), inputItems.get(fileItem.getFieldName()).getName());
}
 
Example #6
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 #7
Source File: JAXRSCdiResourceExtension.java    From cxf with Apache License 2.0 6 votes vote down vote up
/**
 * Load external providers from service loader
 * @return loaded external providers
 */
@SuppressWarnings("rawtypes")
private List< Object > loadExternalProviders() {
    final List< Object > providers = new ArrayList< Object >();

    final ServiceLoader< MessageBodyWriter > writers = ServiceLoader.load(MessageBodyWriter.class);
    for (final MessageBodyWriter< ? > writer: writers) {
        providers.add(writer);
    }

    final ServiceLoader< MessageBodyReader > readers = ServiceLoader.load(MessageBodyReader.class);
    for (final MessageBodyReader< ? > reader: readers) {
        providers.add(reader);
    }

    return providers;
}
 
Example #8
Source File: ListMultipartFormDataMessageBodyReaderTest.java    From everrest with Eclipse Public License 2.0 6 votes vote down vote up
@Test
public void readsListOfInputItems() throws Exception {
    Class type = List.class;
    ParameterizedType genericType = newParameterizedType(List.class, InputItem.class);
    Annotation[] annotations = new Annotation[0];
    MediaType mediaType = MULTIPART_FORM_DATA_TYPE;
    MultivaluedMap<String, String> headers = new MultivaluedHashMap<>();
    InputStream in = mock(InputStream.class);

    FileItem fileItem = createFileItem("fileItem1");
    MessageBodyReader fileItemReader = createFileItemMessageBodyReader(annotations, mediaType, headers, in, fileItem);
    when(providers.getMessageBodyReader(eq(Iterator.class), eq(newParameterizedType(Iterator.class, FileItem.class)), aryEq(annotations), eq(mediaType)))
            .thenReturn(fileItemReader);

    List<InputItem> inputItems = listMultipartFormDataMessageBodyReader.readFrom(type, genericType, annotations, mediaType, headers, in);
    assertEquals(1, inputItems.size());
    assertEquals(fileItem.getFieldName(), inputItems.get(0).getName());
}
 
Example #9
Source File: ResourceUtilTest.java    From minnal with Apache License 2.0 6 votes vote down vote up
@Test(expectedExceptions=MinnalInstrumentationException.class)
public void shouldThrowExceptionIfMethodNotFound() throws Throwable {
	Map<String, Object> values = new HashMap<String, Object>();
	DummyModel model = new DummyModel();
	
	byte[] bytes = new byte[10];
	MediaType mediaType = mock(MediaType.class);
	HttpHeaders httpHeaders = mock(HttpHeaders.class);
	when(httpHeaders.getMediaType()).thenReturn(mediaType);
	MessageBodyReader reader = mock(MessageBodyReader.class);
	when(reader.readFrom(eq(Map.class), eq(Map.class), isNull(Annotation[].class), eq(mediaType), isNull(MultivaluedMap.class), any(InputStream.class))).thenReturn(values);
	Providers providers = mock(Providers.class);
	when(providers.getMessageBodyReader(Map.class, Map.class, null, mediaType)).thenReturn(reader);
	
	ResourceUtil.invokeAction(model, "nonExistingMethod", Lists.newArrayList(new ParameterMetaData("anotherModel", "anotherModel", DummyModel.class)), bytes, providers, httpHeaders, values);
}
 
Example #10
Source File: JacksonFeature.java    From micro-server with Apache License 2.0 6 votes vote down vote up
@Override
  public boolean configure(final FeatureContext context) {
      
  	PluginLoader.INSTANCE.plugins.get().stream()
.filter(module -> module.jacksonFeatureProperties()!=null)
.map(Plugin::jacksonFeatureProperties)
.map(fn->fn.apply(context))
.forEach(map -> {
	addAll(map,context);
});
     
      
      JacksonJaxbJsonProvider provider = new JacksonJaxbJsonProvider();
   		provider.setMapper(JacksonUtil.getMapper());
          context.register(provider, new Class[]{MessageBodyReader.class, MessageBodyWriter.class});
   
      return true;
  }
 
Example #11
Source File: FastJsonFeature.java    From fastjson-jaxrs-json-provider with Apache License 2.0 6 votes vote down vote up
public boolean configure(final FeatureContext context) {
	final Configuration config = context.getConfiguration();
	final String jsonFeature = CommonProperties.getValue(config.getProperties(), config.getRuntimeType(), InternalProperties.JSON_FEATURE, JSON_FEATURE,
			String.class);
	// Other JSON providers registered.
	if (!JSON_FEATURE.equalsIgnoreCase(jsonFeature)) {
		return false;
	}
	// Disable other JSON providers.
	context.property(PropertiesHelper.getPropertyNameForRuntime(InternalProperties.JSON_FEATURE, config.getRuntimeType()), JSON_FEATURE);
	// Register FastJson.
	if (!config.isRegistered(FastJsonProvider.class)) {
		context.register(FastJsonProvider.class, MessageBodyReader.class, MessageBodyWriter.class);
	}
	return true;
}
 
Example #12
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 #13
Source File: ProviderBinderTest.java    From everrest with Eclipse Public License 2.0 6 votes vote down vote up
@Test
@UseDataProvider("messageBodyReaderByTypeAndMediaType")
public void retrievesMessageBodyReaderByTypeAndMediaType(boolean singletonOrPerRequest,
                                                         Class<?> readObjectType,
                                                         Type readObjectGenericType,
                                                         MediaType mediaType,
                                                         Object expectedMessageBodyReaderClassOrInstance) throws Exception {
    if (singletonOrPerRequest == SINGLETON) {
        registerSingletonMessageBodyReaders();
    } else {
        registerPerRequestMessageBodyReaders();
    }

    MessageBodyReader messageBodyReader = providers.getMessageBodyReader(readObjectType, readObjectGenericType, null, mediaType);
    if (singletonOrPerRequest == SINGLETON) {
        assertSame(expectedMessageBodyReaderClassOrInstance, messageBodyReader);
    } else {
        if (expectedMessageBodyReaderClassOrInstance == null) {
            assertNull(messageBodyReader);
        } else {
            assertNotNull(messageBodyReader);
            assertEquals(expectedMessageBodyReaderClassOrInstance, messageBodyReader.getClass());
        }
    }
}
 
Example #14
Source File: ProviderFactoryTest.java    From cxf with Apache License 2.0 6 votes vote down vote up
@Test
public void testRegisterMbrMbwProviderAsMbwOnly() {
    ServerProviderFactory pf = ServerProviderFactory.getInstance();
    JAXBElementProvider<Book> customProvider = new JAXBElementProvider<>();
    pf.registerUserProvider((Feature) context -> {
        context.register(customProvider, MessageBodyWriter.class);
        return true;
    });
    MessageBodyWriter<Book> writer = pf.createMessageBodyWriter(Book.class, null, null,
                                                                MediaType.TEXT_XML_TYPE, new MessageImpl());
    assertSame(writer, customProvider);

    MessageBodyReader<Book> reader = pf.createMessageBodyReader(Book.class, null, null,
                                                                MediaType.TEXT_XML_TYPE, new MessageImpl());
    assertTrue(reader instanceof JAXBElementProvider);
    assertNotSame(reader, customProvider);
}
 
Example #15
Source File: ProviderFactoryTest.java    From cxf with Apache License 2.0 6 votes vote down vote up
@Test
public void testRegisterMbrMbwProviderAsMbrOnly() {
    ServerProviderFactory pf = ServerProviderFactory.getInstance();
    JAXBElementProvider<Book> customProvider = new JAXBElementProvider<>();
    pf.registerUserProvider((Feature) context -> {
        context.register(customProvider, MessageBodyReader.class);
        return true;
    });
    MessageBodyReader<Book> reader = pf.createMessageBodyReader(Book.class, null, null,
                                                                MediaType.TEXT_XML_TYPE, new MessageImpl());
    assertSame(reader, customProvider);

    MessageBodyWriter<Book> writer = pf.createMessageBodyWriter(Book.class, null, null,
                                                                MediaType.TEXT_XML_TYPE, new MessageImpl());
    assertTrue(writer instanceof JAXBElementProvider);
    assertNotSame(writer, customProvider);
}
 
Example #16
Source File: ProviderFactory.java    From cxf with Apache License 2.0 6 votes vote down vote up
public int compare(ProviderInfo<MessageBodyReader<?>> p1,
                   ProviderInfo<MessageBodyReader<?>> p2) {
    MessageBodyReader<?> e1 = p1.getProvider();
    MessageBodyReader<?> e2 = p2.getProvider();

    List<MediaType> types1 = JAXRSUtils.getProviderConsumeTypes(e1);
    types1 = JAXRSUtils.sortMediaTypes(types1, null);
    List<MediaType> types2 = JAXRSUtils.getProviderConsumeTypes(e2);
    types2 = JAXRSUtils.sortMediaTypes(types2, null);

    int result = JAXRSUtils.compareSortedMediaTypes(types1, types2, null);
    if (result != 0) {
        return result;
    }
    result = compareClasses(e1, e2);
    if (result != 0) {
        return result;
    }
    result = compareCustomStatus(p1, p2);
    if (result != 0) {
        return result;
    }
    return comparePriorityStatus(p1.getProvider().getClass(), p2.getProvider().getClass());
}
 
Example #17
Source File: ResourceUtilTest.java    From minnal with Apache License 2.0 6 votes vote down vote up
@Test
public void shouldInvokeMethodWithArgumentsAndModel() throws Throwable {
	Map<String, Object> content = new HashMap<String, Object>();
	content.put("value", "test123");
	content.put("someNumber", 1L);
	Map<String, Object> values = new HashMap<String, Object>();
	values.put("anotherModel", new DummyModel());
	DummyModel model = new DummyModel();
	
	byte[] bytes = new byte[10];
	MediaType mediaType = mock(MediaType.class);
	HttpHeaders httpHeaders = mock(HttpHeaders.class);
	when(httpHeaders.getMediaType()).thenReturn(mediaType);
	MessageBodyReader reader = mock(MessageBodyReader.class);
	when(reader.readFrom(eq(Map.class), eq(Map.class), isNull(Annotation[].class), eq(mediaType), isNull(MultivaluedMap.class), any(InputStream.class))).thenReturn(content);
	Providers providers = mock(Providers.class);
	when(providers.getMessageBodyReader(Map.class, Map.class, null, mediaType)).thenReturn(reader);
	
	assertEquals(ResourceUtil.invokeAction(model, "dummyActionWithArgumentsAndModel", Lists.newArrayList(new ParameterMetaData("anotherModel", "anotherModel", DummyModel.class),
			new ParameterMetaData("value", "value", String.class), new ParameterMetaData("someNumber", "someNumber", Long.class)), bytes, providers, httpHeaders, values), "dummyActionWithArgumentsAndModel");
}
 
Example #18
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 #19
Source File: JSONProviderTest.java    From cxf with Apache License 2.0 6 votes vote down vote up
@Test
public void testReadFromTags() throws Exception {
    MessageBodyReader<Tags> p = new JSONProvider<>();
    byte[] bytes =
        "{\"Tags\":{\"list\":[{\"group\":\"b\",\"name\":\"a\"},{\"group\":\"d\",\"name\":\"c\"}]}}"
        .getBytes();
    Object tagsObject = p.readFrom(Tags.class, null, null,
                                      null, null, new ByteArrayInputStream(bytes));
    Tags tags = (Tags)tagsObject;
    List<TagVO> list = tags.getTags();
    assertEquals(2, list.size());
    assertEquals("a", list.get(0).getName());
    assertEquals("b", list.get(0).getGroup());
    assertEquals("c", list.get(1).getName());
    assertEquals("d", list.get(1).getGroup());
}
 
Example #20
Source File: CachingMessageBodyReader.java    From cxf with Apache License 2.0 6 votes vote down vote up
protected MessageBodyReader<T> getReader(Class<?> type, Type gType, Annotation[] anns, MediaType mt) {
    if (delegatingReaders != null) {
        return getDelegatingReader(type, gType, anns, mt);
    }
    MessageBodyReader<T> r = null;

    mc.put(ACTIVE_JAXRS_PROVIDER_KEY, this);
    try {
        @SuppressWarnings("unchecked")
        Class<T> actualType = (Class<T>)type;
        r = mc.getProviders().getMessageBodyReader(actualType, gType, anns, mt);
    } finally {
        mc.put(ACTIVE_JAXRS_PROVIDER_KEY, null);
    }

    if (r == null) {
        org.apache.cxf.common.i18n.Message message =
            new org.apache.cxf.common.i18n.Message("NO_MSG_READER", BUNDLE, type);
        LOG.severe(message.toString());
        throw ExceptionUtils.toNotAcceptableException(null, null);
    }
    return r;
}
 
Example #21
Source File: RestComponentResolverTest.java    From everrest with Eclipse Public License 2.0 5 votes vote down vote up
@Test
public void resolvesSingletonMessageBodyReader() {
    MessageBodyReader<String> messageBodyReader = new StringEntityProvider();

    componentResolver.addSingleton(messageBodyReader);

    verify(providers).addMessageBodyReader(messageBodyReader);
}
 
Example #22
Source File: ThreadLocalProviders.java    From cxf with Apache License 2.0 5 votes vote down vote up
public <T> MessageBodyReader<T> getMessageBodyReader(Class<T> type,
                                                     Type genericType,
                                                     Annotation[] annotations,
                                                     MediaType mediaType) {
    Providers p = getCurrentProviders();
    return p != null ? p.getMessageBodyReader(type, genericType, annotations, mediaType) : null;
}
 
Example #23
Source File: ProviderFactoryAllTest.java    From cxf with Apache License 2.0 5 votes vote down vote up
@Test
public void testCustomJsonProvider() {
    ProviderFactory pf = ServerProviderFactory.getInstance();
    JSONProvider<Book> provider = new JSONProvider<>();
    pf.registerUserProvider(provider);
    MessageBodyReader<?> customJsonReader = pf.createMessageBodyReader(Book.class, null, null,
                                           MediaType.APPLICATION_JSON_TYPE, new MessageImpl());
    assertSame(customJsonReader, provider);

    MessageBodyWriter<?> customJsonWriter = pf.createMessageBodyWriter(Book.class, null, null,
                                           MediaType.APPLICATION_JSON_TYPE, new MessageImpl());
    assertSame(customJsonWriter, provider);
}
 
Example #24
Source File: ProviderFactoryTest.java    From cxf with Apache License 2.0 5 votes vote down vote up
@Test
public void testMessageBodyReaderBoolean() throws Exception {
    ProviderFactory pf = ServerProviderFactory.getInstance();
    pf.registerUserProvider(new CustomBooleanReader());
    MessageBodyReader<Boolean> mbr = pf.createMessageBodyReader(Boolean.class, Boolean.class, new Annotation[]{},
                               MediaType.TEXT_PLAIN_TYPE, new MessageImpl());
    assertTrue(mbr instanceof PrimitiveTextProvider);
}
 
Example #25
Source File: PrimitiveTextProviderTest.java    From cxf with Apache License 2.0 5 votes vote down vote up
@SuppressWarnings("unchecked")
@Test
public void testReadByte() throws Exception {
    MessageBodyReader<?> p = new PrimitiveTextProvider<>();

    @SuppressWarnings("rawtypes")
    Byte valueRead = (Byte)p.readFrom((Class)Byte.TYPE,
                                      null,
                                      null,
                                      null,
                                      null,
                                      new ByteArrayInputStream("1".getBytes()));
    assertEquals(1, valueRead.byteValue());

}
 
Example #26
Source File: ProviderFactoryAllTest.java    From cxf with Apache License 2.0 5 votes vote down vote up
private void verifyProvider(ProviderFactory pf, Class<?> type, Class<?> provider, String mediaType)
    throws Exception {

    if (pf == null) {
        pf = ServerProviderFactory.getInstance();
    }

    MediaType mType = MediaType.valueOf(mediaType);

    MessageBodyReader<?> reader = pf.createMessageBodyReader(type, type, null, mType, new MessageImpl());
    assertSame("Unexpected provider found", provider, reader.getClass());

    MessageBodyWriter<?> writer = pf.createMessageBodyWriter(type, type, null, mType, new MessageImpl());
    assertTrue("Unexpected provider found", provider == writer.getClass());
}
 
Example #27
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 #28
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 #29
Source File: AegisElementProviderTest.java    From cxf with Apache License 2.0 5 votes vote down vote up
@Test
public void testNoNamespaceReadFrom() throws Exception {
    MessageBodyReader<AegisTestBean> p = new NoNamespaceAegisElementProvider<>();
    byte[] bytes = noNamespaceXml.getBytes("utf-8");
    AegisTestBean bean = p.readFrom(AegisTestBean.class, null, null,
                                      null, null, new ByteArrayInputStream(bytes));
    assertEquals("hovercraft", bean.getStrValue());
    assertTrue(bean.getBoolValue());
}
 
Example #30
Source File: ProviderFactoryTest.java    From cxf with Apache License 2.0 5 votes vote down vote up
private void verifyProvider(ProviderFactory pf, Class<?> type, Class<?> provider, String mediaType)
    throws Exception {

    if (pf == null) {
        pf = ServerProviderFactory.getInstance();
    }

    MediaType mType = MediaType.valueOf(mediaType);

    MessageBodyReader<?> reader = pf.createMessageBodyReader(type, type, null, mType, new MessageImpl());
    assertSame("Unexpected provider found", provider, reader.getClass());

    MessageBodyWriter<?> writer = pf.createMessageBodyWriter(type, type, null, mType, new MessageImpl());
    assertTrue("Unexpected provider found", provider == writer.getClass());
}