re base code
[sdc.git] / openecomp-be / lib / openecomp-sdc-validation-lib / openecomp-sdc-validation-sdk / src / main / java / org / openecomp / sdc / validation / util / ValidationUtil.java
1 /*
2  * Copyright © 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 org.apache.commons.collections4.CollectionUtils;
20 import org.onap.sdc.tosca.services.YamlUtil;
21 import org.openecomp.core.utilities.json.JsonUtil;
22 import org.openecomp.core.validation.errors.ErrorMessagesFormatBuilder;
23 import org.openecomp.core.validation.types.GlobalValidationContext;
24 import org.openecomp.sdc.common.errors.Messages;
25 import org.openecomp.sdc.common.errors.SdcRuntimeException;
26 import org.openecomp.sdc.common.utils.SdcCommon;
27 import org.openecomp.sdc.datatypes.error.ErrorLevel;
28 import org.openecomp.sdc.heat.datatypes.manifest.ManifestContent;
29 import org.openecomp.sdc.heat.datatypes.model.*;
30 import org.openecomp.sdc.heat.services.HeatStructureUtil;
31 import org.openecomp.sdc.logging.api.Logger;
32 import org.openecomp.sdc.logging.api.LoggerFactory;
33
34 import java.io.InputStream;
35 import java.util.Map;
36 import java.util.Objects;
37 import java.util.Optional;
38 import java.util.Set;
39 import java.util.regex.Pattern;
40
41 import static java.util.Objects.nonNull;
42
43 public class ValidationUtil {
44   private static final Logger LOG = LoggerFactory.getLogger(ValidationUtil.class.getName());
45
46   private ValidationUtil(){}
47
48   public static void removeExposedResourcesCalledByGetResource(String fileName,
49                                                                Set<String> actualExposedResources,
50                                                                HeatOrchestrationTemplate
51                                                                    heatOrchestrationTemplate,
52                                                                GlobalValidationContext globalContext) {
53     Map<String, Resource> resourcesMap = heatOrchestrationTemplate.getResources();
54
55     for (Map.Entry<String, Resource> resourceEntry : resourcesMap.entrySet()) {
56       Set<String> referencedResources =
57           HeatStructureUtil.getReferencedValuesByFunctionName(fileName, ResourceReferenceFunctions
58               .GET_RESOURCE
59               .getFunction(), resourceEntry.getValue().getProperties(), globalContext);
60
61       removeExposedResourcesCalledByGetResource(referencedResources, actualExposedResources,
62           resourcesMap);
63     }
64   }
65
66   private static void removeExposedResourcesCalledByGetResource(Set<String> referencedResources,
67                                                                 Set<String>
68                                                                     actualExposedResources,
69                                                                 Map<String, Resource> resourcesMap) {
70     for (String referencedResourceName : referencedResources) {
71       Resource currResource = resourcesMap.get(referencedResourceName);
72       if (Objects.nonNull(currResource) && isExpectedToBeExposed(currResource.getType())) {
73           actualExposedResources.add(referencedResourceName);
74       }
75     }
76   }
77
78   public static boolean isExpectedToBeExposed(String type) {
79     return HeatResourcesTypes.isResourceExpectedToBeExposed(type);
80   }
81
82   public static String getWantedNameFromPropertyValueGetParam(Object value) {
83     Set<String> paramName = HeatStructureUtil
84         .getReferencedValuesByFunctionName(null, ResourceReferenceFunctions.GET_PARAM.getFunction(),
85             value, null);
86     if (paramName != null && CollectionUtils.isNotEmpty(paramName)) {
87       return (String) paramName.toArray()[0];
88     }
89     return null;
90   }
91
92   public static boolean evalPattern(Object paramVal, String[] regexList) {
93     String value = "";
94     if (paramVal instanceof String) {
95       value = (String) paramVal;
96     }
97     if (paramVal instanceof Integer) {
98       value = paramVal.toString();
99     }
100     return evalPattern(value, regexList);
101   }
102
103   private static boolean evalPattern(String paramVal, String[] regexList) {
104
105     for (String regex : regexList) {
106       if (Pattern.matches(regex, paramVal)) {
107         return true;
108       }
109     }
110
111     return false;
112   }
113
114   public static String getMessagePartAccordingToResourceType(Map.Entry<String, Resource>
115                                                              resourceEntry) {
116     HeatResourcesTypes resourcesType =
117         HeatResourcesTypes.findByHeatResource(resourceEntry.getValue().getType());
118     if (resourcesType == HeatResourcesTypes.NOVA_SERVER_RESOURCE_TYPE) {
119       return "Server";
120     } else if (resourcesType == HeatResourcesTypes.CONTRAIL_SERVICE_TEMPLATE) {
121       return "Service Template";
122     } else if (resourcesType == HeatResourcesTypes.CONTRAIL_SERVICE_INSTANCE) {
123       return "Service Instance";
124     } else {
125       return "";
126     }
127   }
128
129   public static Environment validateEnvContent(String envFileName,
130                                          GlobalValidationContext globalContext) {
131     Environment envContent;
132     try {
133       Optional<InputStream> fileContent = globalContext.getFileContent(envFileName);
134       if (fileContent.isPresent()) {
135         envContent = new YamlUtil().yamlToObject(fileContent.get(), Environment.class);
136       } else {
137         throw new Exception("The file '" + envFileName + "' has no content");
138       }
139     } catch (Exception exception) {
140       LOG.error("Invalid envFile name : " + envFileName, exception);
141       return null;
142     }
143     return envContent;
144   }
145
146   public static boolean validateMapPropertyValue(String fileName,
147                                            Map.Entry<String, Resource> resourceEntry,
148                                            GlobalValidationContext globalContext,
149                                            String propertyName, Object nameValue,
150                                            String[] regexList) {
151     String propertyValue = getWantedNameFromPropertyValueGetParam(nameValue);
152     if (nonNull(propertyValue) && !evalPattern(propertyValue, regexList)) {
153         globalContext.addMessage(
154             fileName,
155             ErrorLevel.WARNING,
156             ErrorMessagesFormatBuilder.getErrorWithParameters(globalContext.getMessageCode(),
157                 Messages.PARAMETER_NAME_NOT_ALIGNED_WITH_GUIDELINES.getErrorMessage(),
158                 getMessagePartAccordingToResourceType(resourceEntry), propertyName, propertyValue,
159                 resourceEntry.getKey()));
160         return true;
161       }
162     return false;
163   }
164
165   public static ManifestContent validateManifest(GlobalValidationContext globalContext) {
166     Optional<InputStream> manifest = globalContext.getFileContent(SdcCommon.MANIFEST_NAME);
167     if (!manifest.isPresent()) {
168       throw new RuntimeException("Can't load manifest file for Heat Validator");
169     }
170     ManifestContent manifestContent;
171     try {
172       manifestContent = JsonUtil.json2Object(manifest.get(), ManifestContent.class);
173     } catch (Exception exception) {
174       throw new SdcRuntimeException("Can't load manifest file for Heat Validator", exception);
175     }
176
177     return manifestContent;
178   }
179
180   public static String getParserExceptionReason(Exception exception) {
181     String reason;
182
183     if (exception.getCause() != null && exception.getCause().getCause() != null) {
184       reason = exception.getCause().getCause().getMessage();
185     } else if (exception.getCause() != null) {
186       reason = exception.getCause().getMessage();
187     } else {
188       reason = Messages.GENERAL_HEAT_PARSER_ERROR.getErrorMessage();
189     }
190     return reason;
191   }
192
193   public static HeatOrchestrationTemplate checkHeatOrchestrationPreCondition(String fileName,
194                                                                          GlobalValidationContext globalContext) {
195     HeatOrchestrationTemplate heatOrchestrationTemplate;
196     try {
197       Optional<InputStream> fileContent = globalContext.getFileContent(fileName);
198       if (fileContent.isPresent()) {
199         heatOrchestrationTemplate =
200             new YamlUtil().yamlToObject(fileContent.get(), HeatOrchestrationTemplate.class);
201       } else {
202         heatOrchestrationTemplate = null;
203       }
204     } catch (Exception exception) {
205       globalContext.addMessage(fileName, ErrorLevel.ERROR, ErrorMessagesFormatBuilder
206               .getErrorWithParameters(globalContext.getMessageCode(),
207                       Messages.INVALID_HEAT_FORMAT_REASON.getErrorMessage()
208                       , getParserExceptionReason(exception)));
209       return null;
210     }
211     return heatOrchestrationTemplate;
212   }
213
214
215 }