4f5015bc8fa4bfa3c16c04494f2e4da1644ab4b5
[dcaegen2/analytics/tca.git] / dcae-analytics-test / src / main / java / org / openecomp / dcae / apod / analytics / test / BaseDCAEAnalyticsCommonTest.java
1 /*\r
2  * ===============================LICENSE_START======================================\r
3  *  dcae-analytics\r
4  * ================================================================================\r
5  *    Copyright © 2017 AT&T Intellectual Property. All rights reserved.\r
6  * ================================================================================\r
7  *  Licensed under the Apache License, Version 2.0 (the "License");\r
8  *  you may not use this file except in compliance with the License.\r
9  *   You may obtain a copy of the License at\r
10  *\r
11  *          http://www.apache.org/licenses/LICENSE-2.0\r
12  *\r
13  *  Unless required by applicable law or agreed to in writing, software\r
14  *  distributed under the License is distributed on an "AS IS" BASIS,\r
15  *  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r
16  *  See the License for the specific language governing permissions and\r
17  *  limitations under the License.\r
18  *  ============================LICENSE_END===========================================\r
19  */\r
20 \r
21 package org.openecomp.dcae.apod.analytics.test;\r
22 \r
23 import org.json.JSONException;\r
24 import org.junit.Assert;\r
25 import org.skyscreamer.jsonassert.JSONAssert;\r
26 import org.slf4j.Logger;\r
27 import org.slf4j.LoggerFactory;\r
28 \r
29 import java.io.BufferedReader;\r
30 import java.io.File;\r
31 import java.io.FileOutputStream;\r
32 import java.io.IOException;\r
33 import java.io.InputStream;\r
34 import java.io.InputStreamReader;\r
35 import java.io.ObjectOutputStream;\r
36 import java.io.OutputStreamWriter;\r
37 import java.lang.reflect.Field;\r
38 import java.net.URL;\r
39 import java.net.URLClassLoader;\r
40 import java.nio.charset.Charset;\r
41 import java.nio.file.Paths;\r
42 import java.security.AccessController;\r
43 import java.security.PrivilegedAction;\r
44 import java.util.Arrays;\r
45 \r
46 import static java.nio.file.Files.deleteIfExists;\r
47 import static java.nio.file.Files.exists;\r
48 \r
49 /**\r
50  * Base common test class for all DCAE Analytics Test e.g. unit tests, integration test, CDAP tests etc.\r
51  * <p>\r
52  * @author Rajiv Singla . Creation Date: 10/19/2016.\r
53  */\r
54 abstract class BaseDCAEAnalyticsCommonTest {\r
55 \r
56     protected static final Logger LOG = LoggerFactory.getLogger(BaseDCAEAnalyticsCommonTest.class);\r
57 \r
58     /**\r
59      * Asserts if expected Json String and actual Json String contain the same properties ignoring\r
60      * property order. Simple String assertion might fail as property order during serialization and deserialization\r
61      * is generally non-deterministic. Also proper error message are generated more missing or unexpected\r
62      * properties\r
63      *\r
64      * @param expectedJsonString expected Json String\r
65      * @param actualJsonString actual Json String\r
66      * @throws JSONException Json Exception\r
67      */\r
68     public static void assertJson(String expectedJsonString, String actualJsonString) throws JSONException {\r
69         JSONAssert.assertEquals(expectedJsonString, actualJsonString, true);\r
70     }\r
71 \r
72     /**\r
73      * Converts given file location to String\r
74      *\r
75      * @param fileLocation location of the file which needs to be converted to String\r
76      * @return Contents of file as string\r
77      * @throws IOException IOException\r
78      */\r
79     public static String fromStream(String fileLocation) throws IOException {\r
80         final InputStream jsonFileInputStream =\r
81                 BaseDCAEAnalyticsCommonTest.class.getClassLoader().getResourceAsStream(fileLocation);\r
82         Assert.assertNotNull("Json File Location must be valid", jsonFileInputStream);\r
83         try (BufferedReader reader =\r
84                      new BufferedReader(new InputStreamReader(jsonFileInputStream, Charset.forName("UTF-8")))) {\r
85             final StringBuilder result = new StringBuilder();\r
86             final String newLine = System.getProperty("line.separator");\r
87             String line = reader.readLine();\r
88             while (line != null) {\r
89                 result.append(line)\r
90                     .append(newLine);\r
91                 line = reader.readLine();\r
92             }\r
93             jsonFileInputStream.close();\r
94             return result.toString();\r
95         }\r
96     }\r
97 \r
98 \r
99     /**\r
100      * Checks if object can be serialized properly\r
101      *\r
102      * @param object input object\r
103      * @param callingClass calling class\r
104      * @throws IOException IOException\r
105      */\r
106     public static void testSerialization(Object object, Class<?> callingClass) throws IOException {\r
107         final URL location = callingClass.getProtectionDomain().getCodeSource().getLocation();\r
108         final File serializedOutputFile =\r
109                 new File(location.getPath() + String.format("serialization/%s.ser", object.getClass().getSimpleName()));\r
110 \r
111         // Maybe file already try deleting it first\r
112         final boolean deleteIfExists = deleteIfExists(Paths.get(serializedOutputFile.getPath()));\r
113 \r
114         if (deleteIfExists) {\r
115             LOG.warn("Previous serialization file was overwritten at location: {}", serializedOutputFile.getPath());\r
116         }\r
117 \r
118         boolean mkdirs = true;\r
119         if (!exists(Paths.get(serializedOutputFile.getParentFile().getPath()))) {\r
120             mkdirs = serializedOutputFile.getParentFile().mkdirs();\r
121         }\r
122         if (mkdirs) {\r
123             try (FileOutputStream fileOutputStream = new FileOutputStream(serializedOutputFile);\r
124                  ObjectOutputStream objectOutputStream = new ObjectOutputStream(fileOutputStream)) {\r
125                 objectOutputStream.writeObject(object);\r
126                 LOG.debug("Successfully created serialization file at location: {}", serializedOutputFile.getPath());\r
127             }\r
128         } else {\r
129             throw new IllegalStateException(\r
130                     String.format("Failed to create location to store serialization file: %s",\r
131                             serializedOutputFile));\r
132         }\r
133     }\r
134 \r
135     /**\r
136      * Writes Text to Output file\r
137      *\r
138      * @param textFileLocation - location of text file e.g. textfiles/fileName.json\r
139      * @param content           - file content\r
140      * @param callingClass      - calling class\r
141      * @throws IOException      - ioException\r
142      */\r
143     public static void writeToOutputTextFile(String textFileLocation, String content, Class<?> callingClass) throws\r
144             IOException {\r
145         final URL location = callingClass.getProtectionDomain().getCodeSource().getLocation();\r
146         final File fileLocation = new File(location.getPath() + textFileLocation);\r
147 \r
148         // Maybe file already try deleting it first\r
149         final boolean deleteIfExists = deleteIfExists(Paths.get(fileLocation.getPath()));\r
150 \r
151         if (deleteIfExists) {\r
152             LOG.warn("Previous file will be overwritten at location: {}", fileLocation.getPath());\r
153         }\r
154 \r
155         boolean mkdirs = true;\r
156         if (!exists(Paths.get(fileLocation.getParentFile().getPath()))) {\r
157             mkdirs = fileLocation.getParentFile().mkdirs();\r
158         }\r
159         if (mkdirs) {\r
160             try (\r
161                     FileOutputStream fileOutputStream = new FileOutputStream(fileLocation);\r
162                     OutputStreamWriter outputStream =\r
163                             new OutputStreamWriter(fileOutputStream, Charset.forName("UTF-8"))) {\r
164                 outputStream.write(content);\r
165                 LOG.debug("Successfully created text file at location: {}", fileLocation.getPath());\r
166             }\r
167         } else {\r
168             throw new IllegalStateException(\r
169                     String.format("Failed to create location to store text file: %s", fileLocation));\r
170         }\r
171 \r
172     }\r
173 \r
174 \r
175     /**\r
176      * For testing purposes only we may sometime we may want to access private fields of underlying\r
177      * object to confirm the values are setup correctly.\r
178      * <p>\r
179      * This method uses java reflection to get the value to private object in the class\r
180      *\r
181      * @param object            Actual object which has the private field you want to check\r
182      * @param fieldName         Field name in the Actual Object you want to get the value of\r
183      * @param privateFieldClass Type of the private field\r
184      * @param <T>               Class of Actual Object\r
185      * @param <U>               Class of private field\r
186      * @return value of the private field\r
187      */\r
188     public static <T, U> U getPrivateFiledValue(T object, String fieldName, Class<U> privateFieldClass) {\r
189 \r
190         final Class<?> objectClass = object.getClass();\r
191         try {\r
192             final Field privateField = objectClass.getDeclaredField(fieldName);\r
193             try {\r
194 \r
195                 // mark private field to be accessible for testing purposes\r
196                 AccessController.doPrivileged(new PrivilegedAction() {\r
197                     @Override\r
198                     public Object run() {\r
199                         privateField.setAccessible(true);\r
200                         return null;\r
201                     }\r
202                 });\r
203 \r
204 \r
205                 return privateFieldClass.cast(privateField.get(object));\r
206 \r
207             } catch (IllegalAccessException e) {\r
208                 LOG.error("Unable to access field: {}", fieldName);\r
209                 throw new IllegalStateException(e);\r
210             }\r
211         } catch (NoSuchFieldException e) {\r
212             LOG.error("Unable to locate field name: {} in class: {}", fieldName, objectClass.getSimpleName());\r
213             throw new IllegalStateException(e);\r
214         }\r
215 \r
216 \r
217     }\r
218 \r
219 \r
220     /**\r
221      * Prints classpath jars which are visible inside the class\r
222      *\r
223      * @param classLoader classloader of the calling class\r
224      */\r
225     public static void dumpClasspath(ClassLoader classLoader) {\r
226 \r
227         LOG.info("Dumping ClassPath for classloader: {}", classLoader);\r
228 \r
229         if (classLoader instanceof URLClassLoader) {\r
230 \r
231             URLClassLoader ucl = (URLClassLoader) classLoader;\r
232             LOG.info("\t ==========>>>" + Arrays.toString(ucl.getURLs()));\r
233 \r
234         } else {\r
235             LOG.info("\t(cannot display components as not a URLClassLoader)");\r
236         }\r
237 \r
238         if (classLoader.getParent() != null) {\r
239             dumpClasspath(classLoader.getParent());\r
240         }\r
241     }\r
242 \r
243 }\r