Upgrade Vulnerable Direct Dependencies [snakeyaml]
[sdc.git] / openecomp-be / lib / openecomp-sdc-validation-lib / openecomp-sdc-validation-impl / src / test / java / org / openecomp / sdc / validation / util / ValidationTestUtil.java
1 /*
2  * Copyright © 2016-2018 European Support Limited
3  *
4  * Licensed under the Apache License, Version 2.0 (the "License");
5  * you may not use this file except in compliance with the License.
6  * You may obtain a copy of the License at
7  *
8  *      http://www.apache.org/licenses/LICENSE-2.0
9  *
10  * Unless required by applicable law or agreed to in writing, software
11  * distributed under the License is distributed on an "AS IS" BASIS,
12  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13  * See the License for the specific language governing permissions and
14  * limitations under the License.
15  */
16
17 package org.openecomp.sdc.validation.util;
18
19 import java.io.File;
20 import java.io.FileInputStream;
21 import java.io.IOException;
22 import java.net.URL;
23 import java.util.Collection;
24 import java.util.HashMap;
25 import java.util.Map;
26 import java.util.Objects;
27 import org.apache.commons.collections4.MapUtils;
28 import org.apache.commons.io.IOUtils;
29 import org.junit.Assert;
30 import org.openecomp.core.utilities.file.FileUtils;
31 import org.openecomp.core.utilities.json.JsonUtil;
32 import org.openecomp.core.validation.errors.ErrorMessagesFormatBuilder;
33 import org.openecomp.core.validation.types.GlobalValidationContext;
34 import org.openecomp.core.validation.types.MessageContainer;
35 import org.openecomp.sdc.heat.datatypes.manifest.FileData;
36 import org.openecomp.sdc.heat.datatypes.manifest.ManifestContent;
37 import org.openecomp.sdc.heat.datatypes.model.HeatOrchestrationTemplate;
38 import org.openecomp.sdc.heat.datatypes.model.Resource;
39 import org.openecomp.sdc.heat.services.HeatStructureUtil;
40 import org.openecomp.sdc.heat.services.manifest.ManifestUtil;
41 import org.openecomp.sdc.validation.ResourceValidator;
42 import org.openecomp.sdc.validation.ValidationContext;
43 import org.openecomp.sdc.validation.Validator;
44 import org.openecomp.sdc.validation.base.ResourceBaseValidator;
45
46 /**
47  * @author TALIO
48  * @since 26 Feb 2017
49  */
50 public class ValidationTestUtil {
51
52   public ValidationTestUtil(){}
53
54   public GlobalValidationContext createGlobalContextFromPath(String path) {
55     GlobalValidationContext globalValidationContext = new GlobalValidationContext();
56     Map<String, byte[]> contentMap = getContentMapByPath(path);
57     if (contentMap == null) {
58       return null;
59     }
60     contentMap.forEach(globalValidationContext::addFileContext);
61
62     return globalValidationContext;
63   }
64
65   private Map<String, byte[]> getContentMapByPath(String path) {
66     Map<String, byte[]> contentMap = new HashMap<>();
67     URL url = ValidationTestUtil.class.getResource(path);
68     File pathFile = new File(url.getFile());
69     File[] files;
70     if (pathFile.isDirectory()) {
71       files = pathFile.listFiles();
72     } else {
73       files = new File[]{pathFile};
74     }
75
76     if (files == null || files.length == 0) {
77       return null;
78     }
79
80     for (File file : files) {
81
82       try (FileInputStream fis = new FileInputStream(file)) {
83         contentMap.put(file.getName(), FileUtils.toByteArray(fis));
84       } catch (IOException e) {
85         throw new RuntimeException("Failed to read file: " + file, e);
86       }
87
88     }
89     return contentMap;
90   }
91
92   public Map<String, MessageContainer> testValidator(Validator validator, String path) {
93     GlobalValidationContext globalValidationContext = createGlobalContextFromPath(path);
94     validator.validate(globalValidationContext);
95
96     assert globalValidationContext != null;
97     return globalValidationContext.getContextMessageContainers();
98
99
100   }
101
102   public Map<String, MessageContainer> testValidator(ResourceBaseValidator baseValidator,
103           ResourceValidator resourceValidator,
104           String resourceTypeToValidate, String path) {
105
106     GlobalValidationContext globalContext = Objects.requireNonNull(
107             createGlobalContextFromPath(path), "Global validation context cannot be null");
108
109     ManifestContent manifestContent = ValidationUtil.validateManifest(globalContext);
110     Map<String, FileData.Type> fileTypeMap = ManifestUtil.getFileTypeMap(manifestContent);
111     Map<String, FileData> fileEnvMap = ManifestUtil.getFileAndItsEnv(manifestContent);
112
113     validateFiles(baseValidator, resourceValidator, globalContext, fileEnvMap, fileTypeMap,
114             resourceTypeToValidate);
115
116     return globalContext.getContextMessageContainers();
117   }
118
119   private void validateFiles(ResourceBaseValidator baseValidator,
120           ResourceValidator resourceValidator,
121           GlobalValidationContext globalContext,
122           Map<String, FileData> fileEnvMap,
123           Map<String, FileData.Type> fileTypeMap,
124           String resourceTypeToValidate) {
125
126     Collection<String> files = globalContext.getFiles();
127     for(String fileName : files){
128       if(FileData.isHeatFile(fileTypeMap.get(fileName))) {
129         HeatOrchestrationTemplate heatOrchestrationTemplate =
130                 ValidationUtil.checkHeatOrchestrationPreCondition(fileName, globalContext);
131
132         if (Objects.isNull(heatOrchestrationTemplate)) {
133           continue;
134         }
135
136         ValidationContext validationContext = baseValidator.createValidationContext(fileName,
137                 fileEnvMap.get(fileName) == null ? null : fileEnvMap.get(fileName).getFile(),
138                 heatOrchestrationTemplate, globalContext);
139
140         validateResources(fileName, resourceValidator, resourceTypeToValidate, validationContext,
141                 globalContext);
142       }
143     }
144   }
145
146   private void validateResources(String fileName, ResourceValidator resourceValidator,
147           String resourceTypeToValidate, ValidationContext validationContext,
148           GlobalValidationContext globalValidationContext){
149
150     HeatOrchestrationTemplate heatOrchestrationTemplate =
151             ValidationUtil.checkHeatOrchestrationPreCondition(fileName, globalValidationContext);
152
153     Map<String, Resource> resourcesMap =
154             Objects.requireNonNull(heatOrchestrationTemplate, "Orchestration template cannot be null").getResources();
155
156     if(MapUtils.isEmpty(resourcesMap)){
157       return;
158     }
159
160     resourcesMap.entrySet()
161                 .stream()
162                 .filter(resourceEntry -> isResourceNeedToBeTested(resourceEntry.getValue().getType(), resourceTypeToValidate))
163                 .forEach(resourceEntry ->
164                                  resourceValidator.validate
165                                                            (fileName, resourceEntry, globalValidationContext, validationContext));
166   }
167
168   private boolean isResourceNeedToBeTested(String currResource, String resourceToTest){
169     if(Objects.isNull(resourceToTest)){
170       return HeatStructureUtil.isNestedResource(currResource);
171     }
172
173     return currResource.equals(resourceToTest);
174   }
175
176   public void validateErrorMessage(String actualMessage, String expected, String... params) {
177     Assert.assertEquals(actualMessage.replace("\n", "").replace("\r", ""),
178             ErrorMessagesFormatBuilder.getErrorWithParameters(expected, params).replace("\n", "")
179                                       .replace("\r", ""));
180   }
181
182   public Map<String, Object> getResourceMap(String configFileName) throws IOException {
183     URL mockResource = ValidationTestUtil.class.getResource(configFileName);
184     String json = IOUtils.toString(mockResource.openStream(), "UTF-8");
185     return JsonUtil.json2Object(json, Map.class);
186   }
187 }