@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); } }
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; }
@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 + ")"); }
@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)); } }
@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; }
@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()); } }
@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()); } }
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; }
@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()); }
@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; }
@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; }
@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; }
@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); }
@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); }
@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"); }
@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"); }
@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); }
@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); }
/** * 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; } }); }
@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()); }
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; }
@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")); }
@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); }
@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); }
@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; }
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; }
@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"); }
@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"); }
@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); }
@SuppressWarnings("unused") public <T> void unsetMessageBodyReader( ServiceReference<MessageBodyReader<T>> serviceReference, MessageBodyReader<T> messageBodyReader) { _messageBodyReaders.remove(messageBodyReader); }
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); } }
@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); }
public Config configureFramework() { property(CommonProperties.FEATURE_AUTO_DISCOVERY_DISABLE, true); register(JacksonJaxbJsonProvider.class, MessageBodyReader.class, MessageBodyWriter.class); register(MultiPartFeature.class); return this; }
@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; }
@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; }
@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; }
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); }
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); }
@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; }