Add junit coverage to TimedOutException class
[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 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  * ECOMP is a trademark and service mark of AT&T Intellectual Property.
22  * ============LICENSE_END=========================================================
23  */
24
25 package org.onap.appc.util;
26
27 import java.io.FileNotFoundException;
28 import java.io.IOException;
29 import java.io.InputStream;
30 import java.util.Map;
31 import com.fasterxml.jackson.annotation.JsonInclude;
32 import com.fasterxml.jackson.core.JsonParser;
33 import com.fasterxml.jackson.databind.DeserializationFeature;
34 import com.fasterxml.jackson.databind.ObjectMapper;
35 import com.fasterxml.jackson.databind.SerializationFeature;
36
37 public class JsonUtil {
38
39     static ObjectMapper MAPPER = null;
40     static {
41         MAPPER = new ObjectMapper();
42         MAPPER.enable(SerializationFeature.INDENT_OUTPUT);
43         MAPPER.configure(JsonParser.Feature.ALLOW_COMMENTS, true);
44         MAPPER.setSerializationInclusion(JsonInclude.Include.NON_NULL);
45         MAPPER.disable(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES); // allow translation even
46                                                                            // if extra attrs exist
47                                                                            // in the json
48         MAPPER.configure(SerializationFeature.FAIL_ON_EMPTY_BEANS, false);
49         // Uncomment below when Jackson is upgraded to version 2.7 or above
50         // MAPPER.setPropertyNamingStrategy(PropertyNamingStrategy.KEBAB_CASE);
51     }
52
53     /**
54      * @param valueAsString a valid json Map represented as String
55      * @return a flat map that each entry key derived from hierarchy path in the json object and
56      *         flatted to a dotted separated string. e.g.
57      *         "{\"A\":\"A-value\",\"B\":{\"C\":\"B.C-value\",\"D\":\"B.D-value\"}}"; will be
58      *         represented as {A=A-value, B.C=B.C-value, B.D=B.D-value} when it required that the
59      *         input will not be flatted the json string should be formatted as below example: e.g.
60      *         "{\"A\":\"A-value\",\"B\":\"{\\\"C\\\":\\\"C-value\\\",\\\"D\\\":\\\"D-value\\\"}\"}"
61      *         will be represented as {A=A-value, B={"C":"C-value","D":"D-value"}}
62      * @throws IOException when the object is not valid json Map
63      */
64     public static Map<String, String> convertJsonStringToFlatMap(String valueAsString)
65             throws IOException {
66         Map readValueMap = MAPPER.readValue(valueAsString, Map.class);
67         return org.onap.appc.util.ObjectMapper.map(readValueMap);
68     }
69
70     /**
71      * 0 is the getStackTrace method 1 is the current method 2 is the parent method, 3 is the
72      * grandparent method or the parent class in this case.
73      */
74     private static final int PARENT_CLASS_INDEX = 3;
75
76
77     /**
78      * @see #readInputJson(String, Class, Class)
79      */
80     public static <T> T readInputJson(String location, Class<T> returnClass) throws IOException {
81         return readInputJson(location, returnClass, getCallingClass(PARENT_CLASS_INDEX));
82     }
83
84     /**
85      * @param location The location or name of the file we are trying to read e.g. JsonBody.json
86      * @param returnClass The class *this* Json is suppose to represent.
87      * @param locationClass The starting point for json lookup. the value specified by location is
88      *        relative to this class.
89      * @return The object being returned
90      * @throws IOException Can't find the specified json file at Location.
91      */
92     public static <T> T readInputJson(String location, Class<T> returnClass, Class<?> locationClass)
93             throws IOException {
94         try (InputStream is = locationClass.getResourceAsStream(location)) {
95             validateInput(is, location);
96             return MAPPER.readValue(is, returnClass);
97         }
98     }
99
100     /**
101      * Note that this method is sensitive to the depth of the call stack. For example if a public
102      * method calls a private method, that calls this method likely the desired classIndex value is
103      * 4 rather than 3. However, it's convenient to reduce the input required by callers of this
104      * class.
105      *
106      * @param classIndex How far up the stack trace to find the class we want.
107      * @return The class that called one of the public methods of this class.
108      */
109     private static Class<?> getCallingClass(int classIndex) {
110         String className = Thread.currentThread().getStackTrace()[classIndex].getClassName();
111         try {
112             return Class.forName(className);
113         } catch (ClassNotFoundException e) {
114             // Theoretically impossible.
115             throw new IllegalStateException(
116                     "Could not do class lookup for class in our stack trace?!?");
117         }
118     }
119
120     private static void validateInput(InputStream is, String location)
121             throws FileNotFoundException {
122         if (is == null) {
123             throw new FileNotFoundException(String.format("Could not find file at '%s'", location));
124         }
125     }
126
127 }