TCA: Support for VES/A&AI enrichment
[dcaegen2/analytics/tca.git] / dcae-analytics-test / src / main / java / org / openecomp / dcae / apod / analytics / test / BaseDCAEAnalyticsCommonTest.java
index 4698f21..4f5015b 100644 (file)
-/*
- * ===============================LICENSE_START======================================
- *  dcae-analytics
- * ================================================================================
- *    Copyright © 2017 AT&T Intellectual Property. All rights reserved.
- * ================================================================================
- *  Licensed under the Apache License, Version 2.0 (the "License");
- *  you may not use this file except in compliance with the License.
- *   You may obtain a copy of the License at
- *
- *          http://www.apache.org/licenses/LICENSE-2.0
- *
- *  Unless required by applicable law or agreed to in writing, software
- *  distributed under the License is distributed on an "AS IS" BASIS,
- *  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- *  See the License for the specific language governing permissions and
- *  limitations under the License.
- *  ============================LICENSE_END===========================================
- */
-
-package org.openecomp.dcae.apod.analytics.test;
-
-import org.json.JSONException;
-import org.junit.Assert;
-import org.skyscreamer.jsonassert.JSONAssert;
-import org.slf4j.Logger;
-import org.slf4j.LoggerFactory;
-
-import java.io.BufferedReader;
-import java.io.File;
-import java.io.FileOutputStream;
-import java.io.IOException;
-import java.io.InputStream;
-import java.io.InputStreamReader;
-import java.io.ObjectOutputStream;
-import java.io.OutputStreamWriter;
-import java.lang.reflect.Field;
-import java.net.URL;
-import java.net.URLClassLoader;
-import java.nio.charset.Charset;
-import java.nio.file.Paths;
-import java.security.AccessController;
-import java.security.PrivilegedAction;
-import java.util.Arrays;
-
-import static java.nio.file.Files.deleteIfExists;
-import static java.nio.file.Files.exists;
-
-/**
- * Base common test class for all DCAE Analytics Test e.g. unit tests, integration test, CDAP tests etc.
- * <p>
- * @author Rajiv Singla . Creation Date: 10/19/2016.
- */
-abstract class BaseDCAEAnalyticsCommonTest {
-
-    protected static final Logger LOG = LoggerFactory.getLogger(BaseDCAEAnalyticsCommonTest.class);
-
-    /**
-     * Asserts if expected Json String and actual Json String contain the same properties ignoring
-     * property order. Simple String assertion might fail as property order during serialization and deserialization
-     * is generally non-deterministic. Also proper error message are generated more missing or unexpected
-     * properties
-     *
-     * @param expectedJsonString expected Json String
-     * @param actualJsonString actual Json String
-     * @throws JSONException Json Exception
-     */
-    public static void assertJson(String expectedJsonString, String actualJsonString) throws JSONException {
-        JSONAssert.assertEquals(expectedJsonString, actualJsonString, true);
-    }
-
-    /**
-     * Converts given file location to String
-     *
-     * @param fileLocation location of the file which needs to be converted to String
-     * @return Contents of file as string
-     * @throws IOException IOException
-     */
-    public static String fromStream(String fileLocation) throws IOException {
-        final InputStream jsonFileInputStream =
-                BaseDCAEAnalyticsCommonTest.class.getClassLoader().getResourceAsStream(fileLocation);
-        Assert.assertNotNull("Json File Location must be valid", jsonFileInputStream);
-        try (BufferedReader reader =
-                     new BufferedReader(new InputStreamReader(jsonFileInputStream, Charset.forName("UTF-8")))) {
-            final StringBuilder result = new StringBuilder();
-            final String newLine = System.getProperty("line.separator");
-            String line = reader.readLine();
-            while (line != null) {
-                result.append(line)
-                    .append(newLine);
-                line = reader.readLine();
-            }
-            jsonFileInputStream.close();
-            return result.toString();
-        }
-    }
-
-
-    /**
-     * Checks if object can be serialized properly
-     *
-     * @param object input object
-     * @param callingClass calling class
-     * @throws IOException IOException
-     */
-    public static void testSerialization(Object object, Class<?> callingClass) throws IOException {
-        final URL location = callingClass.getProtectionDomain().getCodeSource().getLocation();
-        final File serializedOutputFile =
-                new File(location.getPath() + String.format("serialization/%s.ser", object.getClass().getSimpleName()));
-
-        // Maybe file already try deleting it first
-        final boolean deleteIfExists = deleteIfExists(Paths.get(serializedOutputFile.getPath()));
-
-        if (deleteIfExists) {
-            LOG.warn("Previous serialization file was overwritten at location: {}", serializedOutputFile.getPath());
-        }
-
-        boolean mkdirs = true;
-        if (!exists(Paths.get(serializedOutputFile.getParentFile().getPath()))) {
-            mkdirs = serializedOutputFile.getParentFile().mkdirs();
-        }
-        if (mkdirs) {
-            try (FileOutputStream fileOutputStream = new FileOutputStream(serializedOutputFile);
-                 ObjectOutputStream objectOutputStream = new ObjectOutputStream(fileOutputStream)) {
-                objectOutputStream.writeObject(object);
-                LOG.debug("Successfully created serialization file at location: {}", serializedOutputFile.getPath());
-            }
-        } else {
-            throw new IllegalStateException(
-                    String.format("Failed to create location to store serialization file: %s",
-                            serializedOutputFile));
-        }
-    }
-
-    /**
-     * Writes Text to Output file
-     *
-     * @param textFileLocation - location of text file e.g. textfiles/fileName.json
-     * @param content           - file content
-     * @param callingClass      - calling class
-     * @throws IOException      - ioException
-     */
-    public static void writeToOutputTextFile(String textFileLocation, String content, Class<?> callingClass) throws
-            IOException {
-        final URL location = callingClass.getProtectionDomain().getCodeSource().getLocation();
-        final File fileLocation = new File(location.getPath() + textFileLocation);
-
-        // Maybe file already try deleting it first
-        final boolean deleteIfExists = deleteIfExists(Paths.get(fileLocation.getPath()));
-
-        if (deleteIfExists) {
-            LOG.warn("Previous file will be overwritten at location: {}", fileLocation.getPath());
-        }
-
-        boolean mkdirs = true;
-        if (!exists(Paths.get(fileLocation.getParentFile().getPath()))) {
-            mkdirs = fileLocation.getParentFile().mkdirs();
-        }
-        if (mkdirs) {
-            try (
-                    FileOutputStream fileOutputStream = new FileOutputStream(fileLocation);
-                    OutputStreamWriter outputStream =
-                            new OutputStreamWriter(fileOutputStream, Charset.forName("UTF-8"))) {
-                outputStream.write(content);
-                LOG.debug("Successfully created text file at location: {}", fileLocation.getPath());
-            }
-        } else {
-            throw new IllegalStateException(
-                    String.format("Failed to create location to store text file: %s", fileLocation));
-        }
-
-    }
-
-
-    /**
-     * For testing purposes only we may sometime we may want to access private fields of underlying
-     * object to confirm the values are setup correctly.
-     * <p>
-     * This method uses java reflection to get the value to private object in the class
-     *
-     * @param object            Actual object which has the private field you want to check
-     * @param fieldName         Field name in the Actual Object you want to get the value of
-     * @param privateFieldClass Type of the private field
-     * @param <T>               Class of Actual Object
-     * @param <U>               Class of private field
-     * @return value of the private field
-     */
-    public static <T, U> U getPrivateFiledValue(T object, String fieldName, Class<U> privateFieldClass) {
-
-        final Class<?> objectClass = object.getClass();
-        try {
-            final Field privateField = objectClass.getDeclaredField(fieldName);
-            try {
-
-                // mark private field to be accessible for testing purposes
-                AccessController.doPrivileged(new PrivilegedAction() {
-                    @Override
-                    public Object run() {
-                        privateField.setAccessible(true);
-                        return null;
-                    }
-                });
-
-
-                return privateFieldClass.cast(privateField.get(object));
-
-            } catch (IllegalAccessException e) {
-                LOG.error("Unable to access field: {}", fieldName);
-                throw new IllegalStateException(e);
-            }
-        } catch (NoSuchFieldException e) {
-            LOG.error("Unable to locate field name: {} in class: {}", fieldName, objectClass.getSimpleName());
-            throw new IllegalStateException(e);
-        }
-
-
-    }
-
-
-    /**
-     * Prints classpath jars which are visible inside the class
-     *
-     * @param classLoader classloader of the calling class
-     */
-    public static void dumpClasspath(ClassLoader classLoader) {
-
-        LOG.info("Dumping ClassPath for classloader: {}", classLoader);
-
-        if (classLoader instanceof URLClassLoader) {
-
-            URLClassLoader ucl = (URLClassLoader) classLoader;
-            LOG.info("\t ==========>>>" + Arrays.toString(ucl.getURLs()));
-
-        } else {
-            LOG.info("\t(cannot display components as not a URLClassLoader)");
-        }
-
-        if (classLoader.getParent() != null) {
-            dumpClasspath(classLoader.getParent());
-        }
-    }
-
-}
+/*\r
+ * ===============================LICENSE_START======================================\r
+ *  dcae-analytics\r
+ * ================================================================================\r
+ *    Copyright © 2017 AT&T Intellectual Property. All rights reserved.\r
+ * ================================================================================\r
+ *  Licensed under the Apache License, Version 2.0 (the "License");\r
+ *  you may not use this file except in compliance with the License.\r
+ *   You may obtain a copy of the License at\r
+ *\r
+ *          http://www.apache.org/licenses/LICENSE-2.0\r
+ *\r
+ *  Unless required by applicable law or agreed to in writing, software\r
+ *  distributed under the License is distributed on an "AS IS" BASIS,\r
+ *  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r
+ *  See the License for the specific language governing permissions and\r
+ *  limitations under the License.\r
+ *  ============================LICENSE_END===========================================\r
+ */\r
+\r
+package org.openecomp.dcae.apod.analytics.test;\r
+\r
+import org.json.JSONException;\r
+import org.junit.Assert;\r
+import org.skyscreamer.jsonassert.JSONAssert;\r
+import org.slf4j.Logger;\r
+import org.slf4j.LoggerFactory;\r
+\r
+import java.io.BufferedReader;\r
+import java.io.File;\r
+import java.io.FileOutputStream;\r
+import java.io.IOException;\r
+import java.io.InputStream;\r
+import java.io.InputStreamReader;\r
+import java.io.ObjectOutputStream;\r
+import java.io.OutputStreamWriter;\r
+import java.lang.reflect.Field;\r
+import java.net.URL;\r
+import java.net.URLClassLoader;\r
+import java.nio.charset.Charset;\r
+import java.nio.file.Paths;\r
+import java.security.AccessController;\r
+import java.security.PrivilegedAction;\r
+import java.util.Arrays;\r
+\r
+import static java.nio.file.Files.deleteIfExists;\r
+import static java.nio.file.Files.exists;\r
+\r
+/**\r
+ * Base common test class for all DCAE Analytics Test e.g. unit tests, integration test, CDAP tests etc.\r
+ * <p>\r
+ * @author Rajiv Singla . Creation Date: 10/19/2016.\r
+ */\r
+abstract class BaseDCAEAnalyticsCommonTest {\r
+\r
+    protected static final Logger LOG = LoggerFactory.getLogger(BaseDCAEAnalyticsCommonTest.class);\r
+\r
+    /**\r
+     * Asserts if expected Json String and actual Json String contain the same properties ignoring\r
+     * property order. Simple String assertion might fail as property order during serialization and deserialization\r
+     * is generally non-deterministic. Also proper error message are generated more missing or unexpected\r
+     * properties\r
+     *\r
+     * @param expectedJsonString expected Json String\r
+     * @param actualJsonString actual Json String\r
+     * @throws JSONException Json Exception\r
+     */\r
+    public static void assertJson(String expectedJsonString, String actualJsonString) throws JSONException {\r
+        JSONAssert.assertEquals(expectedJsonString, actualJsonString, true);\r
+    }\r
+\r
+    /**\r
+     * Converts given file location to String\r
+     *\r
+     * @param fileLocation location of the file which needs to be converted to String\r
+     * @return Contents of file as string\r
+     * @throws IOException IOException\r
+     */\r
+    public static String fromStream(String fileLocation) throws IOException {\r
+        final InputStream jsonFileInputStream =\r
+                BaseDCAEAnalyticsCommonTest.class.getClassLoader().getResourceAsStream(fileLocation);\r
+        Assert.assertNotNull("Json File Location must be valid", jsonFileInputStream);\r
+        try (BufferedReader reader =\r
+                     new BufferedReader(new InputStreamReader(jsonFileInputStream, Charset.forName("UTF-8")))) {\r
+            final StringBuilder result = new StringBuilder();\r
+            final String newLine = System.getProperty("line.separator");\r
+            String line = reader.readLine();\r
+            while (line != null) {\r
+                result.append(line)\r
+                    .append(newLine);\r
+                line = reader.readLine();\r
+            }\r
+            jsonFileInputStream.close();\r
+            return result.toString();\r
+        }\r
+    }\r
+\r
+\r
+    /**\r
+     * Checks if object can be serialized properly\r
+     *\r
+     * @param object input object\r
+     * @param callingClass calling class\r
+     * @throws IOException IOException\r
+     */\r
+    public static void testSerialization(Object object, Class<?> callingClass) throws IOException {\r
+        final URL location = callingClass.getProtectionDomain().getCodeSource().getLocation();\r
+        final File serializedOutputFile =\r
+                new File(location.getPath() + String.format("serialization/%s.ser", object.getClass().getSimpleName()));\r
+\r
+        // Maybe file already try deleting it first\r
+        final boolean deleteIfExists = deleteIfExists(Paths.get(serializedOutputFile.getPath()));\r
+\r
+        if (deleteIfExists) {\r
+            LOG.warn("Previous serialization file was overwritten at location: {}", serializedOutputFile.getPath());\r
+        }\r
+\r
+        boolean mkdirs = true;\r
+        if (!exists(Paths.get(serializedOutputFile.getParentFile().getPath()))) {\r
+            mkdirs = serializedOutputFile.getParentFile().mkdirs();\r
+        }\r
+        if (mkdirs) {\r
+            try (FileOutputStream fileOutputStream = new FileOutputStream(serializedOutputFile);\r
+                 ObjectOutputStream objectOutputStream = new ObjectOutputStream(fileOutputStream)) {\r
+                objectOutputStream.writeObject(object);\r
+                LOG.debug("Successfully created serialization file at location: {}", serializedOutputFile.getPath());\r
+            }\r
+        } else {\r
+            throw new IllegalStateException(\r
+                    String.format("Failed to create location to store serialization file: %s",\r
+                            serializedOutputFile));\r
+        }\r
+    }\r
+\r
+    /**\r
+     * Writes Text to Output file\r
+     *\r
+     * @param textFileLocation - location of text file e.g. textfiles/fileName.json\r
+     * @param content           - file content\r
+     * @param callingClass      - calling class\r
+     * @throws IOException      - ioException\r
+     */\r
+    public static void writeToOutputTextFile(String textFileLocation, String content, Class<?> callingClass) throws\r
+            IOException {\r
+        final URL location = callingClass.getProtectionDomain().getCodeSource().getLocation();\r
+        final File fileLocation = new File(location.getPath() + textFileLocation);\r
+\r
+        // Maybe file already try deleting it first\r
+        final boolean deleteIfExists = deleteIfExists(Paths.get(fileLocation.getPath()));\r
+\r
+        if (deleteIfExists) {\r
+            LOG.warn("Previous file will be overwritten at location: {}", fileLocation.getPath());\r
+        }\r
+\r
+        boolean mkdirs = true;\r
+        if (!exists(Paths.get(fileLocation.getParentFile().getPath()))) {\r
+            mkdirs = fileLocation.getParentFile().mkdirs();\r
+        }\r
+        if (mkdirs) {\r
+            try (\r
+                    FileOutputStream fileOutputStream = new FileOutputStream(fileLocation);\r
+                    OutputStreamWriter outputStream =\r
+                            new OutputStreamWriter(fileOutputStream, Charset.forName("UTF-8"))) {\r
+                outputStream.write(content);\r
+                LOG.debug("Successfully created text file at location: {}", fileLocation.getPath());\r
+            }\r
+        } else {\r
+            throw new IllegalStateException(\r
+                    String.format("Failed to create location to store text file: %s", fileLocation));\r
+        }\r
+\r
+    }\r
+\r
+\r
+    /**\r
+     * For testing purposes only we may sometime we may want to access private fields of underlying\r
+     * object to confirm the values are setup correctly.\r
+     * <p>\r
+     * This method uses java reflection to get the value to private object in the class\r
+     *\r
+     * @param object            Actual object which has the private field you want to check\r
+     * @param fieldName         Field name in the Actual Object you want to get the value of\r
+     * @param privateFieldClass Type of the private field\r
+     * @param <T>               Class of Actual Object\r
+     * @param <U>               Class of private field\r
+     * @return value of the private field\r
+     */\r
+    public static <T, U> U getPrivateFiledValue(T object, String fieldName, Class<U> privateFieldClass) {\r
+\r
+        final Class<?> objectClass = object.getClass();\r
+        try {\r
+            final Field privateField = objectClass.getDeclaredField(fieldName);\r
+            try {\r
+\r
+                // mark private field to be accessible for testing purposes\r
+                AccessController.doPrivileged(new PrivilegedAction() {\r
+                    @Override\r
+                    public Object run() {\r
+                        privateField.setAccessible(true);\r
+                        return null;\r
+                    }\r
+                });\r
+\r
+\r
+                return privateFieldClass.cast(privateField.get(object));\r
+\r
+            } catch (IllegalAccessException e) {\r
+                LOG.error("Unable to access field: {}", fieldName);\r
+                throw new IllegalStateException(e);\r
+            }\r
+        } catch (NoSuchFieldException e) {\r
+            LOG.error("Unable to locate field name: {} in class: {}", fieldName, objectClass.getSimpleName());\r
+            throw new IllegalStateException(e);\r
+        }\r
+\r
+\r
+    }\r
+\r
+\r
+    /**\r
+     * Prints classpath jars which are visible inside the class\r
+     *\r
+     * @param classLoader classloader of the calling class\r
+     */\r
+    public static void dumpClasspath(ClassLoader classLoader) {\r
+\r
+        LOG.info("Dumping ClassPath for classloader: {}", classLoader);\r
+\r
+        if (classLoader instanceof URLClassLoader) {\r
+\r
+            URLClassLoader ucl = (URLClassLoader) classLoader;\r
+            LOG.info("\t ==========>>>" + Arrays.toString(ucl.getURLs()));\r
+\r
+        } else {\r
+            LOG.info("\t(cannot display components as not a URLClassLoader)");\r
+        }\r
+\r
+        if (classLoader.getParent() != null) {\r
+            dumpClasspath(classLoader.getParent());\r
+        }\r
+    }\r
+\r
+}\r