IT Test Import tosca types for a model
[sdc.git] / integration-tests / src / test / java / org / onap / sdc / backend / ci / tests / utils / Utils.java
1 /*-
2  * ============LICENSE_START=======================================================
3  * SDC
4  * ================================================================================
5  * Copyright (C) 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.onap.sdc.backend.ci.tests.utils;
22
23 import static org.testng.AssertJUnit.assertEquals;
24 import static org.testng.AssertJUnit.assertNotNull;
25 import static org.testng.AssertJUnit.assertTrue;
26
27 import com.google.gson.JsonElement;
28 import com.google.gson.JsonObject;
29 import com.google.gson.JsonParser;
30 import java.io.File;
31 import java.io.FileInputStream;
32 import java.io.FileNotFoundException;
33 import java.io.InputStream;
34 import java.text.ParseException;
35 import java.text.SimpleDateFormat;
36 import java.util.ArrayList;
37 import java.util.HashMap;
38 import java.util.List;
39 import java.util.Map;
40 import java.util.Map.Entry;
41 import java.util.concurrent.TimeUnit;
42 import org.apache.commons.lang3.StringUtils;
43 import org.onap.sdc.backend.ci.tests.config.Config;
44 import org.onap.sdc.backend.ci.tests.datatypes.ServiceReqDetails;
45 import org.onap.sdc.backend.ci.tests.datatypes.enums.ArtifactTypeEnum;
46 import org.onap.sdc.backend.ci.tests.tosca.model.ToscaMetadataFieldsPresentationEnum;
47 import org.openecomp.sdc.be.model.Component;
48 import org.openecomp.sdc.common.api.ToscaNodeTypeInfo;
49 import org.openecomp.sdc.common.api.YamlConstants;
50 import org.yaml.snakeyaml.Yaml;
51
52 public final class Utils {
53
54     @SuppressWarnings("unchecked")
55     public ToscaNodeTypeInfo parseToscaNodeYaml(String fileContent) {
56
57         ToscaNodeTypeInfo result = new ToscaNodeTypeInfo();
58
59         if (fileContent != null) {
60             Yaml yaml = new Yaml();
61             Map<String, Object> yamlObject = (Map<String, Object>) yaml.load(fileContent);
62
63             final Object templateVersion = yamlObject.get(YamlConstants.TEMPLATE_VERSION);
64             if (templateVersion != null) {
65                 result.setTemplateVersion(templateVersion.toString());
66             }
67
68             final Object templateName = yamlObject.get(YamlConstants.TEMPLATE_NAME);
69             if (templateName != null) {
70                 result.setTemplateName(templateName.toString());
71             }
72
73             Object nodeTypes = yamlObject.get(YamlConstants.NODE_TYPES);
74             if (nodeTypes != null) {
75                 Map<String, Object> nodeTypesMap = (Map<String, Object>) nodeTypes;
76                 for (Entry<String, Object> entry : nodeTypesMap.entrySet()) {
77
78                     String nodeName = entry.getKey();
79                     if (nodeName != null) {
80                         result.setNodeName(nodeName);
81                     }
82                     break;
83                 }
84             }
85         }
86
87         return result;
88     }
89
90     public static String getJsonObjectValueByKey(String metadata, String key) {
91         JsonElement jelement = new JsonParser().parse(metadata);
92
93         JsonObject jobject = jelement.getAsJsonObject();
94         Object obj = jobject.get(key);
95         if (obj == null) {
96             return null;
97         } else {
98             return (String) jobject.get(key).getAsString();
99         }
100     }
101
102     public static Config getConfig() throws FileNotFoundException {
103         return Config.instance();
104     }
105
106     public static Config getConfigHandleException() {
107         Config config = null;
108         try {
109             config = Config.instance();
110         } catch (Exception e) {
111             System.out.println("Configuration file not found. " + e);
112         }
113         return config;
114     }
115
116     public static void compareArrayLists(List<String> actualArraylList, List<String> expectedArrayList, String message) {
117
118         ArrayList<String> actual = new ArrayList<String>(actualArraylList);
119         ArrayList<String> expected = new ArrayList<String>(expectedArrayList);
120         expected.removeAll(actual);
121         assertEquals(message + " content got by rest API not match to " + message + " actual content", 0, expected.size());
122     }
123
124     public static Object parseYamlConfig(String pattern) throws FileNotFoundException {
125
126         Yaml yaml = new Yaml();
127         Config config = getConfig();
128         String configurationFile = config.getConfigurationFile();
129         File file = new File(configurationFile);
130         InputStream inputStream = new FileInputStream(file);
131         Map<?, ?> map = (Map<?, ?>) yaml.load(inputStream);
132         return (Object) map.get(pattern);
133     }
134
135     public static String getDepArtLabelFromConfig(ArtifactTypeEnum artifactTypeEnum) throws FileNotFoundException {
136
137         @SuppressWarnings("unchecked")
138         Map<String, Object> mapOfDepResArtTypesObjects = (Map<String, Object>) parseYamlConfig(
139             "deploymentResourceArtifacts");
140         for (Map.Entry<String, Object> iter : mapOfDepResArtTypesObjects.entrySet()) {
141             if (iter.getValue().toString().contains(artifactTypeEnum.getType())) {
142                 return iter.getKey().toLowerCase();
143             }
144         }
145
146         return "defaultLabelName";
147     }
148
149
150     public static String multipleChar(String ch, int repeat) {
151         return StringUtils.repeat(ch, repeat);
152     }
153
154     public static List<String> getListOfDepResArtLabels(Boolean isLowerCase) throws FileNotFoundException {
155
156         List<String> listOfResDepArtTypesFromConfig = new ArrayList<String>();
157         @SuppressWarnings("unchecked")
158         Map<String, Object> resourceDeploymentArtifacts = (Map<String, Object>) parseYamlConfig(
159             "deploymentResourceArtifacts");
160         if (resourceDeploymentArtifacts != null) {
161
162             if (isLowerCase) {
163                 for (Map.Entry<String, Object> iter : resourceDeploymentArtifacts.entrySet()) {
164                     listOfResDepArtTypesFromConfig.add(iter.getKey().toLowerCase());
165                 }
166             } else {
167
168                 for (Map.Entry<String, Object> iter : resourceDeploymentArtifacts.entrySet()) {
169                     listOfResDepArtTypesFromConfig.add(iter.getKey());
170                 }
171             }
172         }
173         return listOfResDepArtTypesFromConfig;
174     }
175
176     public static List<String> getListOfToscaArtLabels(Boolean isLowerCase) throws FileNotFoundException {
177
178         List<String> listOfToscaArtTypesFromConfig = new ArrayList<String>();
179         @SuppressWarnings("unchecked")
180         Map<String, Object> toscaArtifacts = (Map<String, Object>) parseYamlConfig("toscaArtifacts");
181         if (toscaArtifacts != null) {
182
183             if (isLowerCase) {
184                 for (Map.Entry<String, Object> iter : toscaArtifacts.entrySet()) {
185                     listOfToscaArtTypesFromConfig.add(iter.getKey().toLowerCase());
186                 }
187             } else {
188                 for (Map.Entry<String, Object> iter : toscaArtifacts.entrySet()) {
189                     listOfToscaArtTypesFromConfig.add(iter.getKey());
190                 }
191             }
192         }
193         return listOfToscaArtTypesFromConfig;
194     }
195
196     public static List<String> getListOfResPlaceHoldersDepArtTypes() throws FileNotFoundException {
197         List<String> listResDepArtTypesFromConfig = new ArrayList<String>();
198         List<String> listOfResDepArtLabelsFromConfig = getListOfDepResArtLabels(false);
199         assertNotNull("deployment artifact types list is null", listOfResDepArtLabelsFromConfig);
200         Object parseYamlConfig = Utils.parseYamlConfig("deploymentResourceArtifacts");
201         Map<String, Object> mapOfDepResArtTypesObjects = (Map<String, Object>) Utils
202             .parseYamlConfig("deploymentResourceArtifacts");
203
204         if (listOfResDepArtLabelsFromConfig != null) {
205             for (String resDepArtType : listOfResDepArtLabelsFromConfig) {
206                 Object object = mapOfDepResArtTypesObjects.get(resDepArtType);
207                 if (object instanceof Map<?, ?>) {
208                     Map<String, Object> map = (Map<String, Object>) object;
209                     listResDepArtTypesFromConfig.add((String) map.get("type"));
210                 } else {
211                     assertTrue("return object does not instance of map", false);
212                 }
213             }
214         }
215         return listResDepArtTypesFromConfig;
216     }
217
218     public static Long getEpochTimeFromUTC(String time) throws ParseException {
219         SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss.SSS zzz");
220         java.util.Date date = df.parse(time);
221         return date.getTime();
222     }
223
224     public static Long getActionDuration(Runnable func) throws Exception {
225         long startTime = System.nanoTime();
226         func.run();
227         long estimateTime = System.nanoTime();
228         return TimeUnit.NANOSECONDS.toSeconds(estimateTime - startTime);
229     }
230
231     public static Long getAndValidateActionDuration(Runnable action, int regularTestRunTime) {
232         Long actualTestRunTime = null;
233         try {
234             actualTestRunTime = Utils.getActionDuration(() -> {
235                 try {
236                     action.run();
237                 } catch (Throwable throwable) {
238                     throwable.printStackTrace();
239                 }
240             });
241         } catch (Exception e) {
242             e.printStackTrace();
243         }
244         double factor = 1.5;
245
246         assertTrue("Expected test run time should be less than " + regularTestRunTime * factor + ", " +
247             "actual time is " + actualTestRunTime, regularTestRunTime * factor > actualTestRunTime);
248         return actualTestRunTime;
249     }
250
251
252     public static Map<String, String> generateServiceMetadataToExpectedObject(ServiceReqDetails serviceReqDetails, Component component) {
253
254         Map<String, String> metadata = new HashMap<>();
255
256         metadata.put(ToscaMetadataFieldsPresentationEnum.ToscaMetadataFieldsEnum.CATEGORY.value, serviceReqDetails.getCategories().get(0).getName());
257         metadata.put(ToscaMetadataFieldsPresentationEnum.ToscaMetadataFieldsEnum.DESCRIPTION.value, serviceReqDetails.getDescription());
258         metadata.put(ToscaMetadataFieldsPresentationEnum.ToscaMetadataFieldsEnum.INVARIANT_UUID.value, component.getInvariantUUID());
259         metadata.put(ToscaMetadataFieldsPresentationEnum.ToscaMetadataFieldsEnum.TYPE.value, "Service");
260         metadata.put(ToscaMetadataFieldsPresentationEnum.ToscaMetadataFieldsEnum.UUID.value, component.getUUID());
261         metadata.put(ToscaMetadataFieldsPresentationEnum.ToscaMetadataFieldsEnum.NAME.value, component.getName());
262         metadata.put(ToscaMetadataFieldsPresentationEnum.ToscaMetadataFieldsEnum.INSTANTIATION_TYPE.value, serviceReqDetails.getInstantiationType());
263         metadata.put(ToscaMetadataFieldsPresentationEnum.ToscaMetadataFieldsEnum.SERVICE_TYPE.value, serviceReqDetails.getServiceType());
264         metadata.put(ToscaMetadataFieldsPresentationEnum.ToscaMetadataFieldsEnum.SERVICE_ROLE.value, serviceReqDetails.getServiceRole());
265         metadata.put(ToscaMetadataFieldsPresentationEnum.ToscaMetadataFieldsEnum.NAMING_POLICY.value, serviceReqDetails.getNamingPolicy());
266         metadata.put(ToscaMetadataFieldsPresentationEnum.ToscaMetadataFieldsEnum.ECOMP_GENERATED_NAMING.value,
267             serviceReqDetails.getEcompGeneratedNaming().toString());
268         metadata.put(ToscaMetadataFieldsPresentationEnum.ToscaMetadataFieldsEnum.SERVICE_ECOMP_NAMING.value,
269             serviceReqDetails.getEcompGeneratedNaming().toString());//equals to ECOMP_GENERATED_NAMING
270
271         return metadata;
272     }
273 }