@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; }
/** * {@inheritDoc} */ @SuppressWarnings("unchecked") @Override public void writeTo(Value<?> entity, Class<?> type, Type genericType, Annotation[] annotations, MediaType mediaType, MultivaluedMap<String, Object> httpHeaders, OutputStream entityStream) throws IOException { final Object entityValue = entity.getOrElseThrow(() -> EmptyValueException.INSTANCE); final Class<?> entityClass = entityValue.getClass(); final Type actualGenericTypeArgument; if (genericType instanceof ParameterizedType) { actualGenericTypeArgument = ((ParameterizedType) genericType).getActualTypeArguments()[0]; } else { actualGenericTypeArgument = entityClass; } final MessageBodyWriter writer = mbw.get().getMessageBodyWriter(entityClass, actualGenericTypeArgument, annotations, mediaType); writer.writeTo(entityValue, entityClass, actualGenericTypeArgument, annotations, mediaType, httpHeaders, entityStream); }
@SuppressWarnings("rawtypes") private MediaType findResponseType( final Object obj, final List<MediaType> produces) { final Class<?> objType = obj == null ? null : obj.getClass(); for (final MediaType mediaType : produces) { final MessageBodyWriter writer = providers.getMessageBodyWriter(objType, null, null, mediaType); if (writer != null) { return mediaType; } } return MediaType.TEXT_PLAIN_TYPE; }
@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)); } }
@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; }
@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; }
private void debugWrite(Object root, MediaType format) { MessageBodyWriter messageBodyWriter = workers.getMessageBodyWriter(root.getClass(), root.getClass(), new Annotation[]{}, format); ByteArrayOutputStream baos = new ByteArrayOutputStream(); try { // use the MBW to serialize myBean into baos messageBodyWriter.writeTo(root, root.getClass(), root.getClass(), new Annotation[]{}, format, new MultivaluedHashMap<String, Object>(), baos); } catch (Throwable e) { logger.error(String.format("could not serialize %s to format %s", root, format), e); throw propagate(e); } logger.info("{}", baos); }
@Override public void writeTo(MultipartUploadRepresentation o, Class<?> type, Type genericType, Annotation[] annotations, MediaType mediaType, MultivaluedMap<String, Object> httpHeaders, OutputStream entityStream) throws IOException, WebApplicationException { Class<BucketObjectUpdateRepresentation> writerType = BucketObjectUpdateRepresentation.class; Type writerGenericType = writerType; Annotation[] writerAnnotations = new Annotation[0]; MessageBodyWriter<BucketObjectUpdateRepresentation> writer = providers.getMessageBodyWriter(writerType, writerGenericType, writerAnnotations, MediaType.WILDCARD_TYPE); String boundary = UUID.randomUUID().toString(); httpHeaders.putSingle(BlazeStorageHeaders.QUIET, Boolean.toString(o.isQuiet())); httpHeaders.putSingle(HttpHeaders.CONTENT_TYPE, mediaType.toString() + "; boundary=" + boundary); byte[] boundaryBytes = ("--" + boundary).getBytes(); for (Map.Entry<String, BucketObjectUpdateRepresentation> entry : o.getUploads().entrySet()) { BucketObjectUpdateRepresentation value = entry.getValue(); MediaType writerMediaType = MediaType.valueOf(value.getContentType()); MultivaluedMap<String, Object> headers = new MultivaluedHashMap<String, Object>(); headers.add(BlazeStorageHeaders.MULTIPART_KEY, entry.getKey()); entityStream.write(boundaryBytes); entityStream.write("\r\n".getBytes()); writer.writeTo(entry.getValue(), writerType, writerGenericType, writerAnnotations, writerMediaType, headers, new HeaderFlushedOutputStream(headers, entityStream)); entityStream.write("\r\n".getBytes()); } entityStream.write(boundaryBytes); entityStream.write("--".getBytes()); }
@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 void writeTo(final JsonWebKeySet jwks, final Class<?> type, final Type genericType, final Annotation[] annotations, final MediaType mediaType, final MultivaluedMap<String, Object> httpHeaders, final OutputStream os) throws IOException, WebApplicationException { final MessageBodyWriter<JsonWebKey> writer = providers.getMessageBodyWriter(JsonWebKey.class, JsonWebKey.class, annotations, mediaType); final JsonArrayBuilder keysArray = Json.createArrayBuilder(); for (final JsonWebKey key : jwks.getKeys()) { final ByteArrayOutputStream keyStream = new ByteArrayOutputStream(); writer.writeTo(key, JsonWebKey.class, null, annotations, mediaType, null, keyStream); keyStream.close(); keysArray.add(Json.createReader(new ByteArrayInputStream(keyStream.toByteArray())) .readObject()); } final JsonObject jwksObject = Json.createObjectBuilder() .add("keys", keysArray) .build(); final JsonWriter w = Json.createWriter(os); w.write(jwksObject); w.close(); }
/** * <p>writeViewable.</p> * * @param viewable a {@link org.glassfish.jersey.server.mvc.Viewable} object. * @param mediaType a {@link javax.ws.rs.core.MediaType} object. * @param httpHeaders a {@link javax.ws.rs.core.MultivaluedMap} object. * @param entityStream a {@link java.io.OutputStream} object. * @throws java.io.IOException if any. */ protected void writeViewable(Viewable viewable, MediaType mediaType, MultivaluedMap<String, Object> httpHeaders, OutputStream entityStream) throws IOException { MessageBodyWriter<Viewable> writer = workers.get().getMessageBodyWriter(Viewable.class, null, new Annotation[]{}, null); if (writer != null) { writer.writeTo(viewable, Viewable.class, Viewable.class, new Annotation[0], mediaType, httpHeaders, entityStream); } }
@SuppressWarnings({"rawtypes", "unchecked"}) @Override public void writeTo(Optional<?> entity, Class<?> type, Type genericType, Annotation[] annotations, MediaType mediaType, MultivaluedMap<String, Object> httpHeaders, OutputStream entityStream) throws IOException { if (!entity.isPresent()) { throw new NotFoundException(); } final Type innerGenericType = (genericType instanceof ParameterizedType) ? ((ParameterizedType) genericType).getActualTypeArguments()[0] : entity.get().getClass(); MessageBodyWriter writer = mbw.get().getMessageBodyWriter(entity.get().getClass(), innerGenericType, annotations, mediaType); writer.writeTo(entity.get(), entity.get().getClass(), innerGenericType, annotations, mediaType, httpHeaders, entityStream); }
/** * 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; } }); }
@SuppressWarnings("unchecked") public static MimeBodyPart createBodyPart(Providers providers, SMIMEOutput out) throws IOException, MessagingException { ByteArrayOutputStream bodyOs = new ByteArrayOutputStream(); MessageBodyWriter writer = providers.getMessageBodyWriter(out.getType(), out.getGenericType(), null, out.getMediaType()); if (writer == null) { throw new RuntimeException("Failed to find writer for type: " + out.getType().getName()); } MultivaluedMap<String, String> bodyHeaders = new MultivaluedHashMap<String, String>(); bodyHeaders.add("Content-Type", out.getMediaType().toString()); writer.writeTo(out.getEntity(), out.getType(), out.getGenericType(), null, out.getMediaType(), bodyHeaders, bodyOs); InternetHeaders ih = new InternetHeaders(); for (Map.Entry<String, List<String>> entry : bodyHeaders.entrySet()) { for (String value : entry.getValue()) { ih.addHeader(entry.getKey(), value); } } return new MimeBodyPart(ih, bodyOs.toByteArray()); }
@Test public void testOccurrenceXML() throws IOException { MessageBodyWriter<Occurrence> occurrenceDwcXMLBodyWriter = new OccurrenceDwcXMLBodyWriter(); ByteArrayOutputStream baos = new ByteArrayOutputStream(); Occurrence occ = new Occurrence(); occ.setCountry(Country.MADAGASCAR); occ.setVerbatimField(DwcTerm.verbatimLocality, "mad"); occ.setReferences(URI.create("http://www.gbif.org")); Term customTerm = TermFactory.instance().findTerm("MyTerm"); occ.setVerbatimField(customTerm, "MyTerm value"); occurrenceDwcXMLBodyWriter.writeTo(occ, null, null, null, null, null, baos); String expectedContent = IOUtils.toString(new FileInputStream(FileUtils.getClasspathFile("dwc_xml/occurrence.xml"))); assertEquals(CharMatcher.WHITESPACE.removeFrom(expectedContent), CharMatcher.WHITESPACE.removeFrom(baos.toString())); }
@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()); }
/** * {@inheritDoc} */ @SuppressWarnings("unchecked") @Override public void writeTo(Either<?, ?> entity, Class<?> type, Type genericType, Annotation[] annotations, MediaType mediaType, MultivaluedMap<String, Object> httpHeaders, OutputStream entityStream) throws IOException { final Object entityValue; final int typeArgumentIndex; if (entity.isLeft()) { entityValue = entity.getLeft(); typeArgumentIndex = 0; } else { entityValue = entity.get(); typeArgumentIndex = 1; } final Class<?> entityClass = entityValue.getClass(); final Type actualGenericTypeArgument; if (genericType instanceof ParameterizedType) { actualGenericTypeArgument = ((ParameterizedType) genericType).getActualTypeArguments()[typeArgumentIndex]; } else { actualGenericTypeArgument = entityClass; } final MessageBodyWriter writer = mbw.get().getMessageBodyWriter(entityClass, actualGenericTypeArgument, annotations, mediaType); writer.writeTo(entityValue, entityClass, actualGenericTypeArgument, annotations, mediaType, httpHeaders, entityStream); }
@Autowired public SupportedMediaTypesScanner( @NonNull List<MessageBodyWriter<GraphEntity>> graphEntityWriters, @NonNull List<MessageBodyWriter<TupleEntity>> tupleEntityWriters) { loadSupportedMediaTypes(graphEntityWriters, graphMediaTypes, this.graphEntityWriters); loadSupportedMediaTypes(tupleEntityWriters, tupleMediaTypes, this.tupleEntityWriters); }
private <T> void loadSupportedMediaTypes(List<MessageBodyWriter<T>> entityWriters, List<MediaType> list, List<MessageBodyWriter<T>> resultingList) { entityWriters.forEach(writer -> { Class<?> entityWriterClass = writer.getClass(); EntityWriter providerAnnotation = entityWriterClass.getAnnotation(EntityWriter.class); Produces produceAnnotation = entityWriterClass.getAnnotation(Produces.class); if (providerAnnotation == null) { LOG.warn( String.format("Found writer that did not specify the EntityWriter annotation correctly." + " Skipping %s", writer.getClass())); return; } if (produceAnnotation == null) { LOG.warn(String.format( "Found writer that did not specify the Produce annotation correctly. Skipping %s", writer.getClass())); return; } addMediaTypes(list, produceAnnotation); resultingList.add(writer); LOG.info(String.format("Registered %s writer for results.", writer.getClass())); }); }
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") public void testWriteMap() throws IOException { final Map<String, String> map = new HashMap<>(); map.put("key", "value"); final ByteArrayOutputStream outputStream = new ByteArrayOutputStream(); final MessageBodyWriter<Map<String, String>> mapWriter = (MessageBodyWriter<Map<String, String>>) writer; mapWriter.writeTo(map, Map.class, null, null, MediaType.APPLICATION_JSON_TYPE, null, outputStream); assertEquals("{\"key\":\"value\"}", outputStream.toString()); }
@Test @SuppressWarnings("unchecked") public void testWriteWidget() throws IOException { final Widget widget = new Widget(); widget.id = "456"; widget.value = "foobar"; final ByteArrayOutputStream outputStream = new ByteArrayOutputStream(); final MessageBodyWriter<Widget> widgetWriter = (MessageBodyWriter<Widget>) writer; widgetWriter.writeTo(widget, Widget.class, null, null, MediaType.APPLICATION_JSON_TYPE, null, outputStream); assertEquals("{\"id\":\"456\",\"value\":\"foobar\"}", outputStream.toString()); }
@SuppressWarnings({ "rawtypes", "unchecked" }) public void write( final MinijaxRequestContext context, final Response response, final HttpServletResponse servletResponse) throws IOException { servletResponse.setStatus(response.getStatus()); for (final Entry<String, List<Object>> entry : response.getHeaders().entrySet()) { final String name = entry.getKey(); for (final Object value : entry.getValue()) { servletResponse.addHeader(name, value.toString()); } } if (context.getMethod().equals("OPTIONS")) { return; } final MediaType mediaType = response.getMediaType(); if (mediaType != null) { servletResponse.setContentType(mediaType.toString()); } final Object obj = response.getEntity(); if (obj == null) { return; } final MessageBodyWriter writer = providers.getMessageBodyWriter(obj.getClass(), null, null, mediaType); if (writer != null) { writer.writeTo(obj, obj.getClass(), null, null, mediaType, null, servletResponse.getOutputStream()); return; } // What to do servletResponse.getWriter().println(obj.toString()); }
@Override @SuppressWarnings({ "rawtypes", "unchecked" }) public <T> MessageBodyWriter<T> getMessageBodyWriter( final Class<T> type, final Type genericType, final Annotation[] annotations, final MediaType mediaType) { if (STRING_WRITER.isWriteable(type, genericType, annotations, mediaType)) { return (MessageBodyWriter<T>) STRING_WRITER; } if (INPUT_STREAM_WRITER.isWriteable(type, genericType, annotations, mediaType)) { return (MessageBodyWriter<T>) INPUT_STREAM_WRITER; } if (FILE_WRITER.isWriteable(type, genericType, annotations, mediaType)) { return (MessageBodyWriter<T>) FILE_WRITER; } for (final Class<? extends MessageBodyWriter<?>> writerClass : writers.get(mediaType)) { final MessageBodyWriter writer = application.get(writerClass); if (writer.isWriteable(type, genericType, annotations, mediaType)) { return writer; } } return null; }
@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; }
@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.writer=true)" ) public <T> void setMessageBodyWriter( ServiceReference<MessageBodyWriter<T>> serviceReference, MessageBodyWriter<T> messageBodyWriter) { _messageBodyWriters.add(messageBodyWriter); }
@SuppressWarnings("unused") public <T> void unsetMessageBodyWriter( ServiceReference<MessageBodyWriter<T>> serviceReference, MessageBodyWriter<T> messageBodyWriter) { _messageBodyWriters.remove(messageBodyWriter); }
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); } }
public void handle(Object result, RequestContext requestCtx) { MessageBodyWriter writer = providers.getMessageBodyWriter(result.getClass(), result.getClass(), result.getClass().getAnnotations(), MediaType.valueOf(requestCtx.contentType())); try { writer.writeTo(result, result.getClass(), null, result.getClass().getAnnotations(), MediaType.valueOf(requestCtx.contentType()), null, requestCtx.getResponse().getOutputStream()); } catch (WebApplicationException | IllegalArgumentException | IOException e) { e.printStackTrace(); } }
@SuppressWarnings("unchecked") @Override public void writeTo(Object entity, Class<?> type, Type genericType, Annotation[] annotations, MediaType mediaType, MultivaluedMap<String, Object> httpHeaders, OutputStream entityStream) throws IOException, WebApplicationException { final Type actualTypeArgument = actual(genericType); final MessageBodyWriter writer = workers.get().getMessageBodyWriter(entity.getClass(), actualTypeArgument, annotations, mediaType); writer.writeTo(entity, entity.getClass(), actualTypeArgument, annotations, mediaType, httpHeaders, entityStream); }
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 Object aroundReadFrom(ReaderInterceptorContext context) throws IOException { Optional<Object> optionalBean = getCurrentObject(); if (optionalBean.isPresent()) { ByteArrayOutputStream outputStream = new ByteArrayOutputStream(); // Currently assume the bean is of type BuiltResponse, this may need to change in the future Object bean = ((BuiltResponse) optionalBean.get()).getEntity(); MessageBodyWriter<? super Object> bodyWriter = providers.getMessageBodyWriter(Object.class, bean.getClass(), new Annotation[0], MediaType.APPLICATION_JSON_TYPE); bodyWriter.writeTo(bean, bean.getClass(), bean.getClass(), new Annotation[0], MediaType.APPLICATION_JSON_TYPE, new MultivaluedHashMap<>(), outputStream); // Use the Jackson 2.x classes to convert both the incoming patch and the current state of the object into a JsonNode / JsonPatch ObjectMapper mapper = new ObjectMapper(); JsonNode serverState = mapper.readValue(outputStream.toByteArray(), JsonNode.class); JsonNode patchAsNode = mapper.readValue(context.getInputStream(), JsonNode.class); JsonPatch patch = JsonPatch.fromJson(patchAsNode); try { JsonNode result = patch.apply(serverState); // Stream the result & modify the stream on the readerInterceptor ByteArrayOutputStream resultAsByteArray = new ByteArrayOutputStream(); mapper.writeValue(resultAsByteArray, result); context.setInputStream(new ByteArrayInputStream(resultAsByteArray.toByteArray())); return context.proceed(); } catch (JsonPatchException | JsonMappingException e) { throw new WebApplicationException(e.getMessage(), e, Response.status(Response.Status.BAD_REQUEST).build()); } } else { throw new IllegalArgumentException("No matching GET method on resource"); } }
@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; }