Java Code Examples for javax.ws.rs.ext.MessageBodyReader

The following are top voted examples for showing how to use javax.ws.rs.ext.MessageBodyReader. These examples are extracted from open source projects. You can vote up the examples you like and your votes will be used in our system to generate more good examples.
Example 1
Project: gitplex-mit   File: JerseyApplication.java   View source code 7 votes vote down vote up
@Inject
public JerseyApplication(ServiceLocator serviceLocator) {
	GuiceBridge.getGuiceBridge().initializeGuiceBridge(serviceLocator);
	GuiceIntoHK2Bridge guiceBridge = serviceLocator.getService(GuiceIntoHK2Bridge.class);
    guiceBridge.bridgeGuiceInjector(AppLoader.injector);
    
    String disableMoxy = PropertiesHelper.getPropertyNameForRuntime(
    		CommonProperties.MOXY_JSON_FEATURE_DISABLE,
               getConfiguration().getRuntimeType());
       property(disableMoxy, true);
       property(ServerProperties.BV_SEND_ERROR_IN_RESPONSE, true);

       // add the default Jackson exception mappers
       register(JsonParseExceptionMapper.class);
       register(JsonMappingExceptionMapper.class);
       register(JacksonJsonProvider.class, MessageBodyReader.class, MessageBodyWriter.class);
       
       packages(JerseyApplication.class.getPackage().getName());
       
    for (JerseyConfigurator configurator: AppLoader.getExtensions(JerseyConfigurator.class)) {
    	configurator.configure(this);
    }
}
 
Example 2
Project: microprofile-rest-client   File: AdditionalRegistrationTest.java   View source code 7 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 3
Project: micro-server   File: JacksonFeature.java   View source code 7 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 4
Project: GitHub   File: Issue1341.java   View source code 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)) {
        //DisableCircularReferenceDetect
        FastJsonProvider fastJsonProvider = new FastJsonProvider();
        FastJsonConfig fastJsonConfig = new FastJsonConfig();
        //fastJsonConfig.setSerializerFeatures(SerializerFeature.DisableCircularReferenceDetect,SerializerFeature.BrowserSecure);

        fastJsonConfig.setSerializerFeatures(SerializerFeature.DisableCircularReferenceDetect);

        fastJsonProvider.setFastJsonConfig(fastJsonConfig);

        context.register(fastJsonProvider, MessageBodyReader.class, MessageBodyWriter.class);
    }
    return true;
}
 
Example 5
Project: minijax   File: EntityProvider.java   View source code 6 votes vote down vote up
@SuppressWarnings("unchecked")
private T getImpl(final MinijaxRequestContext context, final InputStream entityStream) throws IOException {
    if (entityClass == String.class) {
        return (T) IOUtils.toString(entityStream, StandardCharsets.UTF_8);
    }

    if (entityClass == MultivaluedMap.class) {
        return (T) context.getForm().asForm().asMap();
    }

    final MediaType mediaType = consumesTypes != null && !consumesTypes.isEmpty() ? consumesTypes.get(0) : null;
    final MessageBodyReader<T> reader = context.getApplication().getProviders().getMessageBodyReader(entityClass, genericType, annotations, mediaType);
    if (reader != null) {
        final MultivaluedMap<String, String> httpHeaders = context.getHeaders();
        return reader.readFrom(entityClass, genericType, annotations, mediaType, httpHeaders, entityStream);
    }

    throw new InjectException("Unknown entity type (" + entityClass + ")");
}
 
Example 6
Project: minijax   File: MinijaxProviders.java   View source code 6 votes vote down vote up
@SuppressWarnings("unchecked")
public void register(final Class<?> c) {
    if (MessageBodyReader.class.isAssignableFrom(c)) {
        readers.add((Class<MessageBodyReader<?>>) c, MediaTypeUtils.parseMediaTypes(c.getAnnotation(Consumes.class)));
    }

    if (MessageBodyWriter.class.isAssignableFrom(c)) {
        writers.add((Class<MessageBodyWriter<?>>) c, MediaTypeUtils.parseMediaTypes(c.getAnnotation(Produces.class)));
    }

    if (ExceptionMapper.class.isAssignableFrom(c)) {
        exceptionMappers.add((Class<ExceptionMapper<?>>) c, MediaTypeUtils.parseMediaTypes(c.getAnnotation(Produces.class)));
    }

    if (ParamConverterProvider.class.isAssignableFrom(c)) {
        paramConverterProviders.add((ParamConverterProvider) application.get(c));
    }
}
 
Example 7
Project: minijax   File: MinijaxProviders.java   View source code 6 votes vote down vote up
@Override
@SuppressWarnings({ "rawtypes", "unchecked" })
public <T> MessageBodyReader<T> getMessageBodyReader(
        final Class<T> type,
        final Type genericType,
        final Annotation[] annotations,
        final MediaType mediaType) {

    for (final Class<? extends MessageBodyReader<?>> readerClass : readers.get(mediaType)) {
        final MessageBodyReader reader = application.get(readerClass);
        if (reader.isReadable(type, genericType, annotations, mediaType)) {
            return reader;
        }
    }
    return null;
}
 
Example 8
Project: microprofile-rest-client   File: AdditionalRegistrationTest.java   View source code 6 votes vote down vote up
@Test
public void shouldRegisterAMultiTypedProviderClassWithPriorities() {
    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(MultiTypedProvider.class, priorities);
    Configuration configuration = builder.getConfiguration();
    assertTrue(configuration.isRegistered(MultiTypedProvider.class), 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 9
Project: JerseyRestful   File: FastJsonFeature.java   View source code 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 10
Project: geeMVC-Java-MVC-Framework   File: JaxRsResolverTest.java   View source code 6 votes vote down vote up
@Test
public void testLocateMostRelevantConstructor() {
    ReflectionProvider rp = instance(ReflectionProvider.class);

    Providers providers = instance(Providers.class);
    ProviderFilter providerFilter = instance(ProviderFilter.class);

    Field f = rp.getField(JaxRsResolverTest.class, "genericField3");

    RuntimeDelegate.setInstance(new DefaultRuntimeDelegate());

    MessageBodyReader messageBodyReader = providers.getMessageBodyReader(f.getType(), f.getGenericType(), f.getAnnotations(), MediaType.APPLICATION_XML_TYPE);

    assertNotNull(messageBodyReader);
    assertEquals(PersonMessageBodyReader.class, messageBodyReader.getClass());

    Constructor<?> c = providerFilter.mostRelevantConstructor(messageBodyReader.getClass());
    assertEquals(4, c.getParameterCount());
    assertEquals("public com.geemvc.jaxrs.PersonMessageBodyReader(javax.ws.rs.core.Application,javax.ws.rs.core.UriInfo,javax.ws.rs.core.HttpHeaders,javax.ws.rs.ext.Providers)", c.toString());
}
 
Example 11
Project: r01fb   File: RESTAppBase.java   View source code 6 votes vote down vote up
@Override
public Set<Class<?>> getClasses() {
	Set<Class<?>> s = new HashSet<Class<?>>();
	
	// rest Resources
	Set<Class<? extends RESTResource>> restResourceTypes = this.getRESTResourceTypes();
	if (CollectionUtils.hasData(restResourceTypes)) s.addAll(restResourceTypes);
	
	// Request received objects mappers: transforms Java->XML for REST methods param types
	Set<Class<? extends MessageBodyReader<?>>> reqReceivedTypesMappers = this.getRequestReceivedTypesMappers();
	if (CollectionUtils.hasData(reqReceivedTypesMappers)) s.addAll(reqReceivedTypesMappers);
	
	// Response sent objects mappers: transforms Java->XML for REST methods return types
	Set<Class<? extends MessageBodyWriter<?>>> respSentTypesMappers = this.getResponseSentTypesMappers();
	if (CollectionUtils.hasData(respSentTypesMappers)) s.addAll(respSentTypesMappers);
	
	// Exception Mappers
	Set<Class<? extends ExceptionMapper<?>>> expsMappers = this.getExceptionsMappers();
	if (CollectionUtils.hasData(expsMappers)) s.addAll(expsMappers);		
	
	return s;
}
 
Example 12
Project: openid-connect   File: JsonWebKeySetProvider.java   View source code 6 votes vote down vote up
@Override
public JsonWebKeySet readFrom(final Class<JsonWebKeySet> type,
        final Type genericType,
        final Annotation[] annotations,
        final MediaType mediaType,
        final MultivaluedMap<String, String> httpHeaders,
        final InputStream inputStream) throws IOException,
        WebApplicationException {

    final JsonArray keysArray = Json.createReader(inputStream)
            .readObject()
            .getJsonArray("keys");

    final JsonWebKeySet keySet = new JsonWebKeySet();
    final MessageBodyReader<JsonWebKey> reader = providers.getMessageBodyReader(JsonWebKey.class, JsonWebKey.class, annotations, mediaType);
    for (final JsonValue key : keysArray) {
        final InputStream keyStream = new ByteArrayInputStream(key.toString()
                .getBytes(CharSets.UTF8));
        final JsonWebKey jsonWebKey = reader.readFrom(JsonWebKey.class, null, annotations, mediaType, null, keyStream);
        keySet.add(jsonWebKey);
    }

    return keySet;
}
 
Example 13
Project: fastjson-jaxrs-json-provider   File: FastJsonFeature.java   View source code 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 14
Project: minnal   File: ResourceUtilTest.java   View source code 6 votes vote down vote up
@Test
public void shouldGetContentAsList() throws Exception {
	List<String> list = Lists.newArrayList("test1", "test2", "test3");
	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(String.class), eq(String.class), eq(new Annotation[]{}), eq(mediaType), isNull(MultivaluedMap.class), any(InputStream.class))).thenThrow(IOException.class);
	when(reader.readFrom(eq(List.class), any(Type.class), eq(new Annotation[]{}), eq(mediaType), isNull(MultivaluedMap.class), any(InputStream.class))).thenReturn(list);
	Providers providers = mock(Providers.class);
	when(providers.getMessageBodyReader(String.class, String.class, new Annotation[]{}, mediaType)).thenReturn(reader);
	when(providers.getMessageBodyReader(List.class, ResourceUtil.listType(String.class).getType(), new Annotation[]{}, mediaType)).thenReturn(reader);
	Object content = ResourceUtil.getContent(bytes, providers, httpHeaders, String.class);
	assertTrue(content instanceof List);
	assertEquals(content, list);
}
 
Example 15
Project: minnal   File: ResourceUtilTest.java   View source code 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 16
Project: minnal   File: ResourceUtilTest.java   View source code 6 votes vote down vote up
@Test
public void shouldInvokeMethodWithArguments() 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>();
	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, "dummyActionWithArguments", Lists.newArrayList(new ParameterMetaData("value", "value", String.class), 
			new ParameterMetaData("someNumber", "someNumber", Long.class)), bytes, providers, httpHeaders, values), "dummyActionWithArguments");
}
 
Example 17
Project: minnal   File: ResourceUtilTest.java   View source code 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
Project: minnal   File: ResourceUtilTest.java   View source code 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 19
Project: minnal   File: ResourceUtilTest.java   View source code 6 votes vote down vote up
@Test(expectedExceptions=IllegalStateException.class)
public void shouldThrowExceptionIfMethodThrowsAnyException() 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, "throwsException", new ArrayList<ParameterMetaData>(), bytes, providers, httpHeaders, values);
}
 
Example 20
Project: Handy-URI-Templates-WebApp   File: UriTemplateApplication.java   View source code 6 votes vote down vote up
/**
 * Create a new UriTemplateApplication.
 * 
 */
public UriTemplateApplication()
{
   registerClasses(UriTemplateResource.class);
   registerClasses(SchemaResource.class);
   register(new Feature()
   {

      @Override
      public boolean configure(final FeatureContext context)
      {
         final String disableMoxy = CommonProperties.MOXY_JSON_FEATURE_DISABLE + '.'
               + context.getConfiguration().getRuntimeType().name().toLowerCase();
         context.property(disableMoxy, true);

         context.register(JacksonJaxbJsonProvider.class, MessageBodyReader.class, MessageBodyWriter.class);
         return true;
      }

   });
}
 
Example 21
Project: Mastering-Java-EE-Development-with-WildFly   File: ComponentTestCase.java   View source code 5 votes vote down vote up
@Test
public void testConfiguration() throws Exception {
	logger.info("start REST Configuration test");
	Client client = newClient();
	Configuration configuration = client.getConfiguration();
	Set<Class<?>> classes = configuration.getClasses();
	for (Class<?> clazz : classes) {
		assertTrue("verify if the class is a rest component or provider",
				MessageBodyReader.class.isAssignableFrom(clazz) || MessageBodyWriter.class.isAssignableFrom(clazz)
						|| clazz.isAnnotationPresent(Provider.class)
						|| DynamicFeature.class.isAssignableFrom(clazz));
		Map<Class<?>, Integer> contracts = configuration.getContracts(clazz);
		assertFalse("each class has different contracts", contracts.isEmpty());
		for (Class<?> contract : contracts.keySet()) {
			int value = contracts.get(contract);
			assertTrue("verify if the contract is a rest component or provider",
					value == 5000 || value == 4000 || value == 3000 || value == 0);
		}
	}
	Set<Object> instances = configuration.getInstances();
	assertTrue("by default there are not instances", instances.isEmpty());
	Map<String, Object> properties = configuration.getProperties();
	assertTrue("by default there are not properties", properties.isEmpty());
	MyComponent myComponent = new MyComponent();
	client.register(myComponent);
	instances = configuration.getInstances();
	assertFalse("Added instance", instances.isEmpty());
	for (Object instance : instances) {
		if (instance instanceof MyComponent)
			assertTrue("MyComponent is registered and active", configuration.isEnabled((Feature) instance));
	}
	assertEquals("Added property through MyComponent", 1, properties.size());
	boolean property = (Boolean) properties.get("configured_myComponent");
	assertEquals("configured_myComponent ok!", true, property);
	assertEquals("type CLIENT by default", CLIENT, configuration.getRuntimeType());
}
 
Example 22
Project: payara-micro-docker-starter-kit   File: JacksonFeature.java   View source code 5 votes vote down vote up
public boolean configure(FeatureContext context) {
    context.property("jersey.config.server.disableMoxyJson", Boolean.valueOf(true));
    Configuration config = context.getConfiguration();
    context.property(getPropertyNameForRuntime("jersey.config.jsonFeature", config.getRuntimeType()), JSON_FEATURE);
    if (!config.isRegistered(JacksonJaxbJsonProvider.class)) {
        context.register(JsonParseExceptionMapper.class);
        context.register(JsonMappingExceptionMapper.class);
        context.register(JacksonJaxbJsonProvider.class, new Class[]{MessageBodyReader.class, MessageBodyWriter.class});
    }

    return true;
}
 
Example 23
Project: minijax   File: ReaderTest.java   View source code 5 votes vote down vote up
@Test
@SuppressWarnings({ "unchecked", "rawtypes" })
public void testReadMap() throws IOException {
    final String json = "{\"key\":\"value\"}";
    final ByteArrayInputStream inputStream = new ByteArrayInputStream(json.getBytes(StandardCharsets.UTF_8));
    final MessageBodyReader<Map> mapReader = (MessageBodyReader<Map>) reader;
    final Map<String, String> map = mapReader.readFrom(Map.class, null, null, null, null, inputStream);
    assertEquals("value", map.get("key"));
}
 
Example 24
Project: minijax   File: ReaderTest.java   View source code 5 votes vote down vote up
@Test
@SuppressWarnings("unchecked")
public void testReadWidget() throws IOException {
    final String json = "{\"id\":\"123\",\"value\":\"hello\"}";
    final ByteArrayInputStream inputStream = new ByteArrayInputStream(json.getBytes(StandardCharsets.UTF_8));
    final MessageBodyReader<Widget> widgetReader = (MessageBodyReader<Widget>) reader;
    final Widget widget = widgetReader.readFrom(Widget.class, null, null, null, null, inputStream);
    assertEquals("123", widget.id);
    assertEquals("hello", widget.value);
}
 
Example 25
Project: minijax   File: ReaderTest.java   View source code 5 votes vote down vote up
@Test(expected = BadRequestException.class)
@SuppressWarnings("unchecked")
public void testReaderException() throws IOException {
    final String json = "";
    final ByteArrayInputStream inputStream = new ByteArrayInputStream(json.getBytes(StandardCharsets.UTF_8));
    final MessageBodyReader<Object> objReader = (MessageBodyReader<Object>) reader;
    objReader.readFrom(Object.class, null, null, null, null, inputStream);
}
 
Example 26
Project: webserver   File: JsonJacksonFeature.java   View source code 5 votes vote down vote up
@Override
public boolean configure(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 Jackson.
  if (!config.isRegistered(JacksonJaxbJsonProvider.class)) {
    // add the Jackson exception mappers with application/json output
    context.register(JsonMappingExceptionMapper.class);
    context.register(JsonParseExceptionMapper.class);

    if (EntityFilteringFeature.enabled(config)) {
      context.register(JacksonFilteringFeature.class);
      context.register(FilteringJacksonJaxbJsonProvider.class, MessageBodyReader.class, MessageBodyWriter.class);
    } else {
      context.register(JacksonJaxbJsonProvider.class, MessageBodyReader.class, MessageBodyWriter.class);
    }
  }

  return true;
}
 
Example 27
Project: redirector   File: SelectServerTemplate.java   View source code 5 votes vote down vote up
protected SelectServer unmarshalJsonStringObject(String jsonStringObject) throws java.io.IOException {
    MessageBodyReader<SelectServer> messageBodyReader = getJsonMessageBodyReader();
    ByteArrayInputStream bais = new ByteArrayInputStream(jsonStringObject.getBytes());
    SelectServer responseObject = messageBodyReader.readFrom(SelectServer.class, SelectServer.class, SelectServer.class.getAnnotations(), null, null, bais);
    bais.close();
    return responseObject;
}
 
Example 28
Project: microprofile-rest-client   File: AdditionalRegistrationTest.java   View source code 5 votes vote down vote up
@Test
public void shouldRegisterAMultiTypedProviderInstance() {
    MultiTypedProvider provider = new MultiTypedProvider();
    Class[] providerTypes = {ClientRequestFilter.class, ClientResponseFilter.class,
        MessageBodyReader.class, MessageBodyWriter.class, ReaderInterceptor.class, WriterInterceptor.class,
        ResponseExceptionMapper.class, ParamConverterProvider.class};
    RestClientBuilder builder = RestClientBuilder.newBuilder().register(provider, providerTypes);
    Configuration configuration = builder.getConfiguration();
    assertTrue(configuration.isRegistered(MultiTypedProvider.class), MultiTypedProvider.class + " should be registered");
    assertTrue(configuration.isRegistered(provider), MultiTypedProvider.class + " should be registered");
    assertEquals(configuration.getContracts(MultiTypedProvider.class).size(), providerTypes.length,
        "There should be "+providerTypes.length+" provider types registered");
}
 
Example 29
Project: microprofile-rest-client   File: AdditionalRegistrationTest.java   View source code 5 votes vote down vote up
@Test
public void shouldRegisterAMultiTypedProviderClass() {
    Class[] providerTypes = {ClientRequestFilter.class, ClientResponseFilter.class,
        MessageBodyReader.class, MessageBodyWriter.class, ReaderInterceptor.class, WriterInterceptor.class,
        ResponseExceptionMapper.class, ParamConverterProvider.class};
    RestClientBuilder builder = RestClientBuilder.newBuilder().register(MultiTypedProvider.class, providerTypes);
    Configuration configuration = builder.getConfiguration();
    assertTrue(configuration.isRegistered(MultiTypedProvider.class), MultiTypedProvider.class + " should be registered");
    assertEquals(configuration.getContracts(MultiTypedProvider.class).size(), providerTypes.length,
        "There should be "+providerTypes.length+" provider types registered");
}
 
Example 30
Project: com-liferay-apio-architect   File: ApioApplication.java   View source code 5 votes vote down vote up
@Reference(
	cardinality = MULTIPLE, policyOption = GREEDY,
	target = "(liferay.apio.architect.message.body.reader=true)"
)
public <T> void setMessageBodyReader(
	ServiceReference<MessageBodyReader<T>> serviceReference,
	MessageBodyReader<T> messageBodyReader) {

	_messageBodyReaders.add(messageBodyReader);
}
 
Example 31
Project: com-liferay-apio-architect   File: ApioApplication.java   View source code 5 votes vote down vote up
@SuppressWarnings("unused")
public <T> void unsetMessageBodyReader(
	ServiceReference<MessageBodyReader<T>> serviceReference,
	MessageBodyReader<T> messageBodyReader) {

	_messageBodyReaders.remove(messageBodyReader);
}
 
Example 32
Project: enkan   File: SerDesMiddleware.java   View source code 5 votes vote down vote up
private void loadReaderAndWriter() {
    ClassLoader cl = Optional.ofNullable(Thread.currentThread().getContextClassLoader())
            .orElse(getClass().getClassLoader());
    for (MessageBodyReader reader : ServiceLoader.load(MessageBodyReader.class, cl)) {
        bodyReaders.add(reader);
    }
    for (MessageBodyWriter writer : ServiceLoader.load(MessageBodyWriter.class, cl)) {
        bodyWriters.add(writer);
    }
}
 
Example 33
Project: rx-jersey   File: RxGenericBodyReader.java   View source code 5 votes vote down vote up
@SuppressWarnings("unchecked")
@Override
public Object readFrom(Class<Object> type, Type genericType, Annotation[] annotations, MediaType mediaType, MultivaluedMap<String, String> httpHeaders, InputStream entityStream) throws IOException, WebApplicationException {
    final Type actualTypeArgument = actual(genericType);
    final Class entityType = entityType(actualTypeArgument);
    final MessageBodyReader reader = workers.get().getMessageBodyReader(entityType, actualTypeArgument, annotations, mediaType);

    return reader.readFrom(entityType, actualTypeArgument, annotations, mediaType, httpHeaders, entityStream);
}
 
Example 34
Project: mosquito-report-api   File: Config.java   View source code 5 votes vote down vote up
public Config configureFramework() {
    property(CommonProperties.FEATURE_AUTO_DISCOVERY_DISABLE, true);
    register(JacksonJaxbJsonProvider.class, MessageBodyReader.class, MessageBodyWriter.class);
    register(MultiPartFeature.class);

    return this;
}
 
Example 35
Project: keystone4j   File: JacksonFeature.java   View source code 5 votes vote down vote up
@Override
public boolean configure(FeatureContext context) {
	final String disableMoxy = CommonProperties.MOXY_JSON_FEATURE_DISABLE + '.'
			+ context.getConfiguration().getRuntimeType().name().toLowerCase();
	context.property(disableMoxy, true);

	// add the default Jackson exception mappers
	context.register(JsonParseExceptionMapper.class);
	context.register(JsonMappingExceptionMapper.class);
	context.register(JacksonProvider.class, MessageBodyReader.class, MessageBodyWriter.class);
	return true;
}
 
Example 36
Project: routing-bird   File: JacksonFeature.java   View source code 5 votes vote down vote up
@Override
public boolean configure(final FeatureContext context) {
    final String disableMoxy = CommonProperties.MOXY_JSON_FEATURE_DISABLE + '.' + context.getConfiguration().getRuntimeType().name().toLowerCase();
    context.property(disableMoxy, true);

    context.register(new JacksonJaxbJsonProvider(mapper, DEFAULT_ANNOTATIONS), MessageBodyReader.class, MessageBodyWriter.class);
    return true;
}
 
Example 37
Project: blaze-storage   File: ResponseObjectInvocation.java   View source code 5 votes vote down vote up
@SuppressWarnings("unchecked")
private <T> MessageBodyReader<T> getMessageReader(Class<T> responseType) {
	for (MessageBodyReader<?> reader : responseObjectMessageReader) {
		if (reader.isReadable(responseType, null, null, null)) {
			return (MessageBodyReader<T>) reader;
		}
	}

	return null;
}
 
Example 38
Project: blaze-storage   File: ResponseObjectInvocation.java   View source code 5 votes vote down vote up
public <T> T invoke(Class<T> responseType) {
	MessageBodyReader<T> reader = getMessageReader(responseType);

	if (reader != null) {
		return getResponseObject(reader, responseType, delegate.invoke());
	}

	return delegate.invoke(responseType);
}
 
Example 39
Project: blaze-storage   File: ResponseObjectInvocation.java   View source code 5 votes vote down vote up
public <T> T invoke(GenericType<T> responseType) {
	@SuppressWarnings("unchecked")
	Class<T> responseClass = (Class<T>) responseType.getRawType();
	MessageBodyReader<T> reader = getMessageReader(responseClass);

	if (reader != null) {
		Response response = delegate.invoke();
		return getResponseObject(reader, responseClass, response);
	}

	return delegate.invoke(responseType);
}
 
Example 40
Project: blaze-storage   File: MultipartUploadRepresentationMessageBodyReader.java   View source code 5 votes vote down vote up
@Override
public MultipartUploadRepresentation readFrom(Class<MultipartUploadRepresentation> type, Type genericType, Annotation[] annotations, MediaType mediaType, MultivaluedMap<String, String> httpHeaders, InputStream entityStream) throws IOException, WebApplicationException {
	String boundary = mediaType.getParameters().get("boundary");
	if (boundary == null) {
		throw new IOException("Unable to get boundary");
	}
	
	MultipartInputImpl input = new MultipartInputImpl(mediaType, providers);
	input.parse(entityStream);
	Collection<InputPart> parts = input.getParts();
	
	Map<String, BucketObjectUpdateRepresentation> uploads = new HashMap<String, BucketObjectUpdateRepresentation>(parts.size());
	@SuppressWarnings("resource")
	MultipartUploadRepresentation result = new MultipartUploadRepresentation("true".equalsIgnoreCase(httpHeaders.getFirst(BlazeStorageHeaders.QUIET)), uploads, input);
	
	Class<BucketObjectUpdateRepresentation> readerType = BucketObjectUpdateRepresentation.class;
	Type readerGenericType = readerType;
	Annotation[] readerAnnotations = new Annotation[0];
	
	MessageBodyReader<BucketObjectUpdateRepresentation> reader = providers.getMessageBodyReader(readerType, readerGenericType, readerAnnotations, MediaType.WILDCARD_TYPE);
	
	for (InputPart p : parts) {
		MultivaluedMap<String, String> partHttpHeaders = p.getHeaders();
		String partKey = partHttpHeaders.getFirst(BlazeStorageHeaders.MULTIPART_KEY);
		
		if (partKey == null) {
			throw new WebApplicationException(Response.status(Status.BAD_REQUEST).build());
		}
		
		BucketObjectUpdateRepresentation bucketObjectUpdateRepresentation = reader.readFrom(readerType, readerGenericType, readerAnnotations, p.getMediaType(), partHttpHeaders, p.getInputStream());
		uploads.put(partKey, bucketObjectUpdateRepresentation);
	}

	return result;
}