8506a283a72e009e4cc777868920369de497ad23
[policy/common.git] /
1 /*
2  * ============LICENSE_START=======================================================
3  * ONAP
4  * ================================================================================
5  * Copyright (C) 2019 AT&T Intellectual Property. All rights reserved.
6  * ================================================================================
7  * Licensed under the Apache License, Version 2.0 (the "License");
8  * you may not use this file except in compliance with the License.
9  * You may obtain a copy of the License at
10  *
11  *      http://www.apache.org/licenses/LICENSE-2.0
12  *
13  * Unless required by applicable law or agreed to in writing, software
14  * distributed under the License is distributed on an "AS IS" BASIS,
15  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
16  * See the License for the specific language governing permissions and
17  * limitations under the License.
18  * ============LICENSE_END=========================================================
19  */
20
21 package org.onap.policy.common.endpoints.http.server;
22
23 import com.google.gson.GsonBuilder;
24 import com.google.gson.JsonSyntaxException;
25 import java.io.IOException;
26 import java.io.InputStream;
27 import java.io.InputStreamReader;
28 import java.io.OutputStream;
29 import java.io.OutputStreamWriter;
30 import java.lang.annotation.Annotation;
31 import java.lang.reflect.Type;
32 import java.nio.charset.StandardCharsets;
33 import javax.ws.rs.Consumes;
34 import javax.ws.rs.Produces;
35 import javax.ws.rs.core.MediaType;
36 import javax.ws.rs.core.MultivaluedMap;
37 import javax.ws.rs.ext.MessageBodyReader;
38 import javax.ws.rs.ext.MessageBodyWriter;
39 import javax.ws.rs.ext.Provider;
40 import org.onap.policy.common.gson.GsonMessageBodyHandler;
41 import org.onap.policy.common.utils.coder.YamlJsonTranslator;
42 import org.slf4j.Logger;
43 import org.slf4j.LoggerFactory;
44 import org.yaml.snakeyaml.error.YAMLException;
45
46 /**
47  * Provider that serializes and de-serializes YAML via snakeyaml and gson.
48  */
49 @Provider
50 @Consumes(MediaType.WILDCARD)
51 @Produces(MediaType.WILDCARD)
52 public class YamlMessageBodyHandler implements MessageBodyReader<Object>, MessageBodyWriter<Object> {
53
54     public static final Logger logger = LoggerFactory.getLogger(YamlMessageBodyHandler.class);
55
56     public static final String APPLICATION_YAML = "application/yaml";
57
58     /**
59      * Translator that's used when none is specified. We want a GSON object that's
60      * configured the same way as it is in {@link GsonMessageBodyHandler}, so just get it
61      * from there.
62      */
63     private static final YamlJsonTranslator DEFAULT_TRANSLATOR =
64                     new YamlJsonTranslator(GsonMessageBodyHandler.configBuilder(new GsonBuilder()).create());
65
66     private final YamlJsonTranslator translator;
67
68     /**
69      * Constructs the object.
70      */
71     public YamlMessageBodyHandler() {
72         this(DEFAULT_TRANSLATOR);
73     }
74
75     /**
76      * Constructs the object.
77      *
78      * @param translator translator to use to translate to/from YAML
79      */
80     public YamlMessageBodyHandler(YamlJsonTranslator translator) {
81         logger.info("Accepting YAML for REST calls");
82         this.translator = translator;
83     }
84
85     @Override
86     public boolean isWriteable(Class<?> type, Type genericType, Annotation[] annotations, MediaType mediaType) {
87         return canHandle(mediaType);
88     }
89
90     @Override
91     public long getSize(Object object, Class<?> type, Type genericType, Annotation[] annotations, MediaType mediaType) {
92         return -1;
93     }
94
95     @Override
96     public void writeTo(Object object, Class<?> type, Type genericType, Annotation[] annotations, MediaType mediaType,
97                     MultivaluedMap<String, Object> httpHeaders, OutputStream entityStream) throws IOException {
98
99         try (OutputStreamWriter writer = new OutputStreamWriter(entityStream, StandardCharsets.UTF_8)) {
100             translator.toYaml(writer, object);
101         }
102     }
103
104     @Override
105     public boolean isReadable(Class<?> type, Type genericType, Annotation[] annotations, MediaType mediaType) {
106         return canHandle(mediaType);
107     }
108
109     /**
110      * Determines if this provider can handle the given media type.
111      *
112      * @param mediaType the media type of interest
113      * @return {@code true} if this provider handles the given media type, {@code false}
114      *         otherwise
115      */
116     private boolean canHandle(MediaType mediaType) {
117         return (mediaType != null && "yaml".equalsIgnoreCase(mediaType.getSubtype()));
118     }
119
120     @Override
121     public Object readFrom(Class<Object> type, Type genericType, Annotation[] annotations, MediaType mediaType,
122                     MultivaluedMap<String, String> httpHeaders, InputStream entityStream) throws IOException {
123
124         try (InputStreamReader streamReader = new InputStreamReader(entityStream, StandardCharsets.UTF_8)) {
125             Class<?> clazz = (Class<?>) genericType;
126             return translator.fromYaml(streamReader, clazz);
127
128         } catch (JsonSyntaxException e) {
129             throw new YAMLException(e);
130         }
131     }
132 }