[SDC-29] Amdocs OnBoard 1707 initial commit.
[sdc.git] / openecomp-be / lib / openecomp-sdc-validation-lib / openecomp-sdc-validation-impl / src / main / java / org / openecomp / sdc / validation / impl / validators / namingconvention / ContrailServiceTemplateNamingConventionValidator.java
1 package org.openecomp.sdc.validation.impl.validators.namingconvention;
2
3 import org.apache.commons.collections4.CollectionUtils;
4 import org.apache.commons.collections4.MapUtils;
5 import org.apache.commons.lang3.tuple.ImmutablePair;
6 import org.apache.commons.lang3.tuple.Pair;
7 import org.openecomp.core.validation.errors.ErrorMessagesFormatBuilder;
8 import org.openecomp.core.validation.types.GlobalValidationContext;
9 import org.openecomp.sdc.common.errors.Messages;
10 import org.openecomp.sdc.datatypes.error.ErrorLevel;
11 import org.openecomp.sdc.heat.datatypes.model.Resource;
12 import org.openecomp.sdc.logging.context.impl.MdcDataDebugMessage;
13 import org.openecomp.sdc.logging.types.LoggerErrorDescription;
14 import org.openecomp.sdc.logging.types.LoggerTragetServiceName;
15 import org.openecomp.sdc.validation.ResourceValidator;
16 import org.openecomp.sdc.validation.ValidationContext;
17 import org.openecomp.sdc.validation.util.ValidationUtil;
18
19 import java.util.Arrays;
20 import java.util.List;
21 import java.util.Map;
22 import java.util.Objects;
23 import java.util.Optional;
24 import java.util.regex.Pattern;
25
26 import static java.util.Objects.nonNull;
27
28 /**
29  * Created by TALIO on 2/24/2017.
30  */
31 public class ContrailServiceTemplateNamingConventionValidator implements ResourceValidator {
32   private static MdcDataDebugMessage mdcDataDebugMessage = new MdcDataDebugMessage();
33
34   @Override
35   public void validate(String fileName, Map.Entry<String, Resource> resourceEntry,
36                        GlobalValidationContext globalContext, ValidationContext validationContext) {
37     validateServiceTemplateImageAndFlavor(fileName, resourceEntry, globalContext);
38   }
39
40   private void validateServiceTemplateImageAndFlavor(String fileName,
41                                                      Map.Entry<String, Resource> entry,
42                                                      GlobalValidationContext globalContext) {
43
44     mdcDataDebugMessage.debugEntryMessage("file", fileName);
45
46     if (MapUtils.isEmpty(entry.getValue().getProperties())) {
47       return;
48     }
49
50     Pair<String, String> imagePair = new ImmutablePair<>("image_name", ".*_image_name");
51     Pair<String, String> flavorPair = new ImmutablePair<>("flavor", ".*_flavor_name");
52     List<Pair<String, String>> imageFlavorPairs = Arrays.asList(imagePair, flavorPair);
53
54     Map<String, Object> propertiesMap = entry.getValue().getProperties();
55
56     boolean errorExistValidatingImageOrFlavor = false;
57     for (Pair<String, String> imageOrFlavor : imageFlavorPairs) {
58       boolean errorExistWhenValidatingImageOrFlavorNames =
59           isErrorExistWhenValidatingImageOrFlavorNames(fileName, imageOrFlavor, entry,
60               propertiesMap, globalContext);
61       errorExistValidatingImageOrFlavor =
62           errorExistValidatingImageOrFlavor || errorExistWhenValidatingImageOrFlavorNames;
63     }
64
65     if (!errorExistValidatingImageOrFlavor) {
66       validateServiceTemplatePropertiesValuesVmtypesAreIdentical(fileName, entry, globalContext,
67           propertiesMap);
68     }
69
70     mdcDataDebugMessage.debugExitMessage("file", fileName);
71   }
72
73   private void validateServiceTemplatePropertiesValuesVmtypesAreIdentical(String fileName,
74                                                                           Map.Entry<String, Resource> entry,
75                                                                           GlobalValidationContext globalContext,
76                                                                           Map<String, Object> propertiesMap) {
77
78     mdcDataDebugMessage.debugEntryMessage("file", fileName);
79
80     Pair<String, String> vmTypeImagePair = new ImmutablePair<>("image_name", "\\_image\\_name");
81     Pair<String, String> vmTypeFlavorPair = new ImmutablePair<>("flavor", "\\_flavor\\_name");
82     validatePropertiesValuesVmtypesAreIdentical(Arrays.asList(vmTypeImagePair, vmTypeFlavorPair),
83         fileName, entry, propertiesMap, globalContext);
84
85     mdcDataDebugMessage.debugExitMessage("file", fileName);
86   }
87
88   private void validatePropertiesValuesVmtypesAreIdentical(List<Pair> propertiesToMatch,
89                                                            String fileName,
90                                                            Map.Entry<String, Resource> resourceEntry,
91                                                            Map<String, Object> propertiesMap,
92                                                            GlobalValidationContext globalContext) {
93
94
95     mdcDataDebugMessage.debugEntryMessage("file", fileName);
96
97     if (CollectionUtils.isEmpty(propertiesToMatch)) {
98       return;
99     }
100
101     String previousPropertyValueValue = null;
102     for (Pair propertyToMatch : propertiesToMatch) {
103       Optional<String> propertyVmType =
104           extractVmTypeFromProperty(fileName, resourceEntry, propertiesMap, globalContext,
105               propertyToMatch);
106       if (propertyVmType.isPresent()) {
107         String currentPropVmType = propertyVmType.get();
108         previousPropertyValueValue =
109             handleFirstIteration(previousPropertyValueValue, currentPropVmType);
110         if (addWarningIfCurrentVmTypeIsDifferentFromPrevious(fileName, resourceEntry, globalContext,
111             previousPropertyValueValue, currentPropVmType)) {
112           mdcDataDebugMessage.debugExitMessage("file", fileName);
113           return;
114         }
115       }
116     }
117
118     mdcDataDebugMessage.debugExitMessage("file", fileName);
119   }
120
121   private boolean addWarningIfCurrentVmTypeIsDifferentFromPrevious(String fileName,
122                                                                    Map.Entry<String, Resource> resourceEntry,
123                                                                    GlobalValidationContext globalContext,
124                                                                    String previousPropertyValueValue,
125                                                                    String currentPropVmType) {
126     if (!Objects.equals(previousPropertyValueValue, currentPropVmType)) {
127       globalContext.addMessage(fileName, ErrorLevel.WARNING, ErrorMessagesFormatBuilder
128               .getErrorWithParameters(
129                   Messages.CONTRAIL_VM_TYPE_NAME_NOT_ALIGNED_WITH_NAMING_CONVENSION
130                       .getErrorMessage(), resourceEntry.getKey()),
131           LoggerTragetServiceName.VALIDATE_CONTRAIL_VM_NAME,
132           LoggerErrorDescription.NAME_NOT_ALIGNED_WITH_GUIDELINES);
133       return true;
134     }
135
136     return false;
137   }
138
139   private boolean isErrorExistWhenValidatingImageOrFlavorNames(String fileName,
140                                                                Pair<String, String> propertyNameAndRegex,
141                                                                Map.Entry<String, Resource> resourceEntry,
142                                                                Map<String, Object> propertiesMap,
143                                                                GlobalValidationContext globalContext) {
144     String propertyName = propertyNameAndRegex.getKey();
145     Object nameValue =
146         propertiesMap.get(propertyName) == null ? null : propertiesMap.get(propertyName);
147     String[] regexList = new String[]{propertyNameAndRegex.getValue()};
148
149     if (nonNull(nameValue)) {
150       if (nameValue instanceof Map) {
151         if (ValidationUtil.validateMapPropertyValue(fileName, resourceEntry, globalContext,
152             propertyName,
153             nameValue, regexList)) {
154           return true;
155         }
156       } else {
157         globalContext.addMessage(
158             fileName,
159             ErrorLevel.WARNING, ErrorMessagesFormatBuilder
160                 .getErrorWithParameters(Messages.MISSING_GET_PARAM.getErrorMessage(), propertyName,
161                     resourceEntry.getKey()),
162             LoggerTragetServiceName.VALIDATE_IMAGE_AND_FLAVOR_NAME,
163             LoggerErrorDescription.MISSING_GET_PARAM);
164         return true;
165       }
166
167       return false;
168     }
169     return false;
170   }
171
172
173   private Optional<String> extractVmTypeFromProperty(String fileName,
174                                                      Map.Entry<String, Resource> resourceEntry,
175                                                      Map<String, Object> propertiesMap,
176                                                      GlobalValidationContext globalContext,
177                                                      Pair propertyKeyRegex) {
178     String propertyName = (String) propertyKeyRegex.getKey();
179     Object propertyVal = propertiesMap.get(propertyName);
180     if (nonNull(propertyVal)) {
181       if (propertyVal instanceof Map) {
182         String propertyValFromGetParam = ValidationUtil.getWantedNameFromPropertyValueGetParam
183             (propertyVal);
184         if (nonNull(propertyValFromGetParam)) {
185           Pattern pattern = Pattern.compile("" + propertyKeyRegex.getValue());
186           return Optional.ofNullable(pattern.split(propertyValFromGetParam)[0]);
187         }
188       } else {
189         globalContext.addMessage(
190             fileName,
191             ErrorLevel.WARNING, ErrorMessagesFormatBuilder
192                 .getErrorWithParameters(Messages.MISSING_GET_PARAM.getErrorMessage(), propertyName,
193                     resourceEntry.getKey()),
194             LoggerTragetServiceName.VALIDATE_VM_SYNC_IN_IMAGE_FLAVOR,
195             LoggerErrorDescription.MISSING_GET_PARAM);
196         return Optional.empty();
197       }
198     }
199     return Optional.empty();
200   }
201
202   private String handleFirstIteration(String previousPropertyValueValue, String currentPropVmType) {
203     if (Objects.isNull(previousPropertyValueValue)) {
204       previousPropertyValueValue = currentPropVmType;
205     }
206
207     return previousPropertyValueValue;
208   }
209 }