c72b7482a3c2e78fce342efc8a0eb3184131a596
[policy/models.git] / models-sim / models-sim-dmaap / src / main / java / org / onap / policy / models / sim / dmaap / rest / TextMessageBodyHandler.java
1 /*-
2  * ============LICENSE_START=======================================================
3  * ONAP Policy Models
4  * ================================================================================
5  * Copyright (C) 2019, 2021 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.models.sim.dmaap.rest;
22
23 import java.io.BufferedReader;
24 import java.io.IOException;
25 import java.io.InputStream;
26 import java.io.InputStreamReader;
27 import java.lang.annotation.Annotation;
28 import java.lang.reflect.Type;
29 import java.nio.charset.StandardCharsets;
30 import java.util.LinkedList;
31 import java.util.List;
32 import javax.ws.rs.Consumes;
33 import javax.ws.rs.core.MediaType;
34 import javax.ws.rs.core.MultivaluedMap;
35 import javax.ws.rs.ext.MessageBodyReader;
36 import javax.ws.rs.ext.Provider;
37
38 /**
39  * Provider that decodes "text/plain" messages.
40  */
41 @Provider
42 @Consumes(TextMessageBodyHandler.MEDIA_TYPE_TEXT_PLAIN)
43 public class TextMessageBodyHandler implements MessageBodyReader<Object> {
44     public static final String MEDIA_TYPE_TEXT_PLAIN = "text/plain";
45
46     @Override
47     public boolean isReadable(Class<?> type, Type genericType, Annotation[] annotations, MediaType mediaType) {
48         return (mediaType != null && MEDIA_TYPE_TEXT_PLAIN.equals(mediaType.toString()));
49     }
50
51     @Override
52     public List<Object> readFrom(Class<Object> type, Type genericType, Annotation[] annotations, MediaType mediaType,
53                     MultivaluedMap<String, String> httpHeaders, InputStream entityStream) throws IOException {
54
55         try (var bufferedReader = new BufferedReader(new InputStreamReader(entityStream, StandardCharsets.UTF_8))) {
56             List<Object> messages = new LinkedList<>();
57             String msg;
58             while ((msg = bufferedReader.readLine()) != null) {
59                 messages.add(msg);
60             }
61
62             return messages;
63         }
64     }
65 }