1 package org.openecomp.sdc.be.view;
3 import com.fasterxml.jackson.databind.ObjectMapper;
5 import javax.ws.rs.Produces;
6 import javax.ws.rs.core.MediaType;
7 import javax.ws.rs.core.MultivaluedMap;
8 import javax.ws.rs.ext.MessageBodyWriter;
9 import javax.ws.rs.ext.Provider;
10 import java.io.IOException;
11 import java.io.OutputStream;
12 import java.lang.annotation.Annotation;
13 import java.lang.reflect.Type;
14 import java.util.List;
15 import java.util.Objects;
16 import java.util.stream.Collectors;
17 import java.util.stream.Stream;
20 * A class that is then responsible for converting a message payload with a dedicated mixin from an instance of a specific Java type into a json representation.
23 @Produces(MediaType.APPLICATION_JSON)
24 public class MixinModelWriter implements MessageBodyWriter<Object> {
27 public boolean isWriteable(Class<?> type, Type genericType, Annotation[] annotations, MediaType mediaType) {
28 return hasResponseViewAndMixinTargetAnnotations(annotations) && mediaType.isCompatible(MediaType.APPLICATION_JSON_TYPE);
32 public long getSize(Object object, Class<?> type, Type genericType, Annotation[] annotations, MediaType mediaType) {
37 public void writeTo(Object object, Class<?> type, Type genericType, Annotation[] annotations, MediaType mediaType, MultivaluedMap<String, Object> httpHeaders, OutputStream entityStream) throws IOException {
38 ObjectMapper objectMapper = new ObjectMapper();
39 List<MixinSourceTarget> mixinSourceTargets = getMixinSourceTarget(annotations);
40 mixinSourceTargets.forEach(mixinSourceTarget -> objectMapper.addMixIn(mixinSourceTarget.getTarget(), mixinSourceTarget.getMixinSource()));
41 objectMapper.writeValue(entityStream, object);
44 private List<MixinSourceTarget> getMixinSourceTarget(Annotation[] annotations) {
45 return Stream.of(annotations)
46 .filter(annotation -> annotation.annotationType().equals(ResponseView.class))
47 .map(annotation -> (ResponseView) annotation)
48 .flatMap(responseView -> Stream.of(responseView.mixin()))
49 .map(mixinClass -> new MixinSourceTarget(mixinClass, mixinClass.getAnnotation(MixinTarget.class).target()))
50 .collect(Collectors.toList());
53 private boolean hasResponseViewAndMixinTargetAnnotations(Annotation[] annotations) {
54 return Stream.of(annotations)
55 .filter(annotation -> annotation.annotationType().equals(ResponseView.class))
56 .map(annotation -> (ResponseView) annotation)
57 .flatMap(responseView -> Stream.of(responseView.mixin()))
58 .anyMatch(mixinClass -> Objects.nonNull(mixinClass.getAnnotation(MixinTarget.class)));