89aa8ff6b0580cd4f0438b981d11947b9a8f3853
[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.JsonSyntaxException;
24 import java.io.IOException;
25 import java.io.InputStream;
26 import java.io.InputStreamReader;
27 import java.io.OutputStream;
28 import java.io.OutputStreamWriter;
29 import java.lang.annotation.Annotation;
30 import java.lang.reflect.Type;
31 import java.nio.charset.StandardCharsets;
32 import javax.ws.rs.Consumes;
33 import javax.ws.rs.Produces;
34 import javax.ws.rs.core.MediaType;
35 import javax.ws.rs.core.MultivaluedMap;
36 import javax.ws.rs.ext.MessageBodyReader;
37 import javax.ws.rs.ext.MessageBodyWriter;
38 import javax.ws.rs.ext.Provider;
39 import org.onap.policy.common.gson.GsonMessageBodyHandler;
40 import org.onap.policy.common.utils.coder.YamlJsonTranslator;
41 import org.slf4j.Logger;
42 import org.slf4j.LoggerFactory;
43 import org.yaml.snakeyaml.error.YAMLException;
44
45 /**
46  * Provider that serializes and de-serializes YAML via snakeyaml and gson.
47  */
48 @Provider
49 @Consumes(MediaType.WILDCARD)
50 @Produces(MediaType.WILDCARD)
51 public class YamlMessageBodyHandler implements MessageBodyReader<Object>, MessageBodyWriter<Object> {
52
53     public static final Logger logger = LoggerFactory.getLogger(YamlMessageBodyHandler.class);
54
55     public static final String APPLICATION_YAML = "application/yaml";
56
57     /**
58      * Translator that's used when none is specified. We want a GSON object that's
59      * configured the same way as it is in {@link GsonMessageBodyHandler}, so just get it
60      * from there.
61      */
62     private static final YamlJsonTranslator DEFAULT_TRANSLATOR =
63                     new YamlJsonTranslator(new GsonMessageBodyHandler().getGson());
64
65     private final YamlJsonTranslator translator;
66
67     /**
68      * Constructs the object.
69      */
70     public YamlMessageBodyHandler() {
71         this(DEFAULT_TRANSLATOR);
72     }
73
74     /**
75      * Constructs the object.
76      *
77      * @param translator translator to use to translate to/from YAML
78      */
79     public YamlMessageBodyHandler(YamlJsonTranslator translator) {
80         logger.info("Accepting YAML for REST calls");
81         this.translator = translator;
82     }
83
84     @Override
85     public boolean isWriteable(Class<?> type, Type genericType, Annotation[] annotations, MediaType mediaType) {
86         return canHandle(mediaType);
87     }
88
89     @Override
90     public long getSize(Object object, Class<?> type, Type genericType, Annotation[] annotations, MediaType mediaType) {
91         return -1;
92     }
93
94     @Override
95     public void writeTo(Object object, Class<?> type, Type genericType, Annotation[] annotations, MediaType mediaType,
96                     MultivaluedMap<String, Object> httpHeaders, OutputStream entityStream) throws IOException {
97
98         try (OutputStreamWriter writer = new OutputStreamWriter(entityStream, StandardCharsets.UTF_8)) {
99             translator.toYaml(writer, object);
100         }
101     }
102
103     @Override
104     public boolean isReadable(Class<?> type, Type genericType, Annotation[] annotations, MediaType mediaType) {
105         return canHandle(mediaType);
106     }
107
108     /**
109      * Determines if this provider can handle the given media type.
110      *
111      * @param mediaType the media type of interest
112      * @return {@code true} if this provider handles the given media type, {@code false}
113      *         otherwise
114      */
115     private boolean canHandle(MediaType mediaType) {
116         return (mediaType != null && "yaml".equalsIgnoreCase(mediaType.getSubtype()));
117     }
118
119     @Override
120     public Object readFrom(Class<Object> type, Type genericType, Annotation[] annotations, MediaType mediaType,
121                     MultivaluedMap<String, String> httpHeaders, InputStream entityStream) throws IOException {
122
123         try (InputStreamReader streamReader = new InputStreamReader(entityStream, StandardCharsets.UTF_8)) {
124             Class<?> clazz = (Class<?>) genericType;
125             return translator.fromYaml(streamReader, clazz);
126
127         } catch (JsonSyntaxException e) {
128             throw new YAMLException(e);
129         }
130     }
131 }