4c8d324c690a3b45ddb9b41936c862057b77cafe
[policy/clamp.git] /
1 /*-
2  * ============LICENSE_START=======================================================
3  *  Copyright (C) 2021 Nordix Foundation.
4  * ================================================================================
5  * Licensed under the Apache License, Version 2.0 (the "License");
6  * you may not use this file except in compliance with the License.
7  * You may obtain a copy of the License at
8  *
9  *      http://www.apache.org/licenses/LICENSE-2.0
10  *
11  * Unless required by applicable law or agreed to in writing, software
12  * distributed under the License is distributed on an "AS IS" BASIS,
13  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14  * See the License for the specific language governing permissions and
15  * limitations under the License.
16  *
17  * SPDX-License-Identifier: Apache-2.0
18  * ============LICENSE_END=========================================================
19  */
20
21 package org.onap.policy.clamp.controlloop.participant.simulator.config;
22
23 import java.io.IOException;
24 import java.io.OutputStreamWriter;
25 import java.nio.charset.StandardCharsets;
26 import org.springframework.http.HttpInputMessage;
27 import org.springframework.http.HttpOutputMessage;
28 import org.springframework.http.MediaType;
29 import org.springframework.http.converter.AbstractHttpMessageConverter;
30 import org.springframework.http.converter.HttpMessageNotReadableException;
31 import org.springframework.http.converter.HttpMessageNotWritableException;
32 import org.yaml.snakeyaml.Yaml;
33
34 public class YamlHttpMessageConverter<T> extends AbstractHttpMessageConverter<T> {
35
36     public YamlHttpMessageConverter() {
37         super(new MediaType("application", "yaml"));
38     }
39
40     @Override
41     protected boolean supports(Class<?> clazz) {
42         return true;
43     }
44
45     @Override
46     protected T readInternal(Class<? extends T> clazz, HttpInputMessage inputMessage)
47             throws IOException, HttpMessageNotReadableException {
48         Yaml yaml = new Yaml();
49         return yaml.loadAs(inputMessage.getBody(), clazz);
50     }
51
52     @Override
53     protected void writeInternal(T t, HttpOutputMessage outputMessage)
54             throws IOException, HttpMessageNotWritableException {
55         Yaml yaml = new Yaml();
56         try (OutputStreamWriter writer = new OutputStreamWriter(outputMessage.getBody(), StandardCharsets.UTF_8)) {
57             yaml.dump(t, writer);
58         }
59     }
60 }