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