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