1 package org.openecomp.sdc.be.view;
3 import com.fasterxml.jackson.databind.ObjectMapper;
4 import com.fasterxml.jackson.databind.SerializationFeature;
6 import javax.ws.rs.Produces;
7 import javax.ws.rs.core.MediaType;
8 import javax.ws.rs.core.MultivaluedMap;
9 import javax.ws.rs.ext.MessageBodyWriter;
10 import javax.ws.rs.ext.Provider;
11 import java.io.IOException;
12 import java.io.OutputStream;
13 import java.lang.annotation.Annotation;
14 import java.lang.reflect.Type;
15 import java.util.List;
16 import java.util.Objects;
17 import java.util.stream.Collectors;
18 import java.util.stream.Stream;
21 * 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.
24 @Produces(MediaType.APPLICATION_JSON)
25 public class MixinModelWriter implements MessageBodyWriter<Object> {
28 public boolean isWriteable(Class<?> type, Type genericType, Annotation[] annotations, MediaType mediaType) {
29 return hasResponseViewAndMixinTargetAnnotations(annotations) && mediaType.isCompatible(MediaType.APPLICATION_JSON_TYPE);
33 public long getSize(Object object, Class<?> type, Type genericType, Annotation[] annotations, MediaType mediaType) {
38 public void writeTo(Object object, Class<?> type, Type genericType, Annotation[] annotations, MediaType mediaType, MultivaluedMap<String, Object> httpHeaders, OutputStream entityStream) throws IOException {
39 ObjectMapper objectMapper = new ObjectMapper();
40 objectMapper.configure(SerializationFeature.FAIL_ON_EMPTY_BEANS, false);
41 List<MixinSourceTarget> mixinSourceTargets = getMixinSourceTarget(annotations);
42 mixinSourceTargets.forEach(mixinSourceTarget -> objectMapper.addMixIn(mixinSourceTarget.getTarget(), mixinSourceTarget.getMixinSource()));
43 objectMapper.writeValue(entityStream, object);
46 private List<MixinSourceTarget> getMixinSourceTarget(Annotation[] annotations) {
47 return Stream.of(annotations)
48 .filter(annotation -> annotation.annotationType().equals(ResponseView.class))
49 .map(annotation -> (ResponseView) annotation)
50 .flatMap(responseView -> Stream.of(responseView.mixin()))
51 .map(mixinClass -> new MixinSourceTarget(mixinClass, mixinClass.getAnnotation(MixinTarget.class).target()))
52 .collect(Collectors.toList());
55 private boolean hasResponseViewAndMixinTargetAnnotations(Annotation[] annotations) {
56 return Stream.of(annotations)
57 .filter(annotation -> annotation.annotationType().equals(ResponseView.class))
58 .map(annotation -> (ResponseView) annotation)
59 .flatMap(responseView -> Stream.of(responseView.mixin()))
60 .anyMatch(mixinClass -> Objects.nonNull(mixinClass.getAnnotation(MixinTarget.class)));