14784595cf9500a742b4fd844634337db9f7e7d3
[appc.git] / appc-common / src / main / java / org / onap / appc / util / JsonUtil.java
1 /*-
2  * ============LICENSE_START=======================================================
3  * ONAP : APPC
4  * ================================================================================
5  * Copyright (C) 2017-2018 AT&T Intellectual Property. All rights reserved.
6  * ================================================================================
7  * Copyright (C) 2017 Amdocs
8  * =============================================================================
9  * Licensed under the Apache License, Version 2.0 (the "License");
10  * you may not use this file except in compliance with the License.
11  * You may obtain a copy of the License at
12  * 
13  *      http://www.apache.org/licenses/LICENSE-2.0
14  * 
15  * Unless required by applicable law or agreed to in writing, software
16  * distributed under the License is distributed on an "AS IS" BASIS,
17  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
18  * See the License for the specific language governing permissions and
19  * limitations under the License.
20  * 
21  * ============LICENSE_END=========================================================
22  */
23
24 package org.onap.appc.util;
25
26 import java.io.FileNotFoundException;
27 import java.io.IOException;
28 import java.io.InputStream;
29 import java.util.Map;
30 import com.fasterxml.jackson.annotation.JsonInclude;
31 import com.fasterxml.jackson.core.JsonParser;
32 import com.fasterxml.jackson.databind.DeserializationFeature;
33 import com.fasterxml.jackson.databind.ObjectMapper;
34 import com.fasterxml.jackson.databind.SerializationFeature;
35
36 public class JsonUtil {
37
38     static ObjectMapper MAPPER = null;
39     static {
40         MAPPER = new ObjectMapper();
41         MAPPER.enable(SerializationFeature.INDENT_OUTPUT);
42         MAPPER.configure(JsonParser.Feature.ALLOW_COMMENTS, true);
43         MAPPER.setSerializationInclusion(JsonInclude.Include.NON_NULL);
44         MAPPER.disable(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES); // allow translation even
45                                                                            // if extra attrs exist
46                                                                            // in the json
47         MAPPER.configure(SerializationFeature.FAIL_ON_EMPTY_BEANS, false);
48         // Uncomment below when Jackson is upgraded to version 2.7 or above
49         // MAPPER.setPropertyNamingStrategy(PropertyNamingStrategy.KEBAB_CASE);
50     }
51
52     /**
53      * @param valueAsString a valid json Map represented as String
54      * @return a flat map that each entry key derived from hierarchy path in the json object and
55      *         flatted to a dotted separated string. e.g.
56      *         "{\"A\":\"A-value\",\"B\":{\"C\":\"B.C-value\",\"D\":\"B.D-value\"}}"; will be
57      *         represented as {A=A-value, B.C=B.C-value, B.D=B.D-value} when it required that the
58      *         input will not be flatted the json string should be formatted as below example: e.g.
59      *         "{\"A\":\"A-value\",\"B\":\"{\\\"C\\\":\\\"C-value\\\",\\\"D\\\":\\\"D-value\\\"}\"}"
60      *         will be represented as {A=A-value, B={"C":"C-value","D":"D-value"}}
61      * @throws IOException when the object is not valid json Map
62      */
63     public static Map<String, String> convertJsonStringToFlatMap(String valueAsString)
64             throws IOException {
65         Map readValueMap = MAPPER.readValue(valueAsString, Map.class);
66         return org.onap.appc.util.ObjectMapper.map(readValueMap);
67     }
68
69     /**
70      * 0 is the getStackTrace method 1 is the current method 2 is the parent method, 3 is the
71      * grandparent method or the parent class in this case.
72      */
73     private static final int PARENT_CLASS_INDEX = 3;
74
75
76     /**
77      * @see #readInputJson(String, Class, Class)
78      */
79     public static <T> T readInputJson(String location, Class<T> returnClass) throws IOException {
80         return readInputJson(location, returnClass, getCallingClass(PARENT_CLASS_INDEX));
81     }
82
83     /**
84      * @param location The location or name of the file we are trying to read e.g. JsonBody.json
85      * @param returnClass The class *this* Json is suppose to represent.
86      * @param locationClass The starting point for json lookup. the value specified by location is
87      *        relative to this class.
88      * @return The object being returned
89      * @throws IOException Can't find the specified json file at Location.
90      */
91     public static <T> T readInputJson(String location, Class<T> returnClass, Class<?> locationClass)
92             throws IOException {
93         try (InputStream is = locationClass.getResourceAsStream(location)) {
94             validateInput(is, location);
95             return MAPPER.readValue(is, returnClass);
96         }
97     }
98
99     /**
100      * Note that this method is sensitive to the depth of the call stack. For example if a public
101      * method calls a private method, that calls this method likely the desired classIndex value is
102      * 4 rather than 3. However, it's convenient to reduce the input required by callers of this
103      * class.
104      *
105      * @param classIndex How far up the stack trace to find the class we want.
106      * @return The class that called one of the public methods of this class.
107      */
108     private static Class<?> getCallingClass(int classIndex) {
109         String className = Thread.currentThread().getStackTrace()[classIndex].getClassName();
110         try {
111             return Class.forName(className);
112         } catch (ClassNotFoundException e) {
113             // Theoretically impossible.
114             throw new IllegalStateException(
115                     "Could not do class lookup for class in our stack trace?!?");
116         }
117     }
118
119     private static void validateInput(InputStream is, String location)
120             throws FileNotFoundException {
121         if (is == null) {
122             throw new FileNotFoundException(String.format("Could not find file at '%s'", location));
123         }
124     }
125
126 }