re base code
[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 /*
2  * Copyright © 2016-2017 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.impl.validators.namingconvention;
18
19 import static java.util.Objects.nonNull;
20
21 import java.util.Arrays;
22 import java.util.List;
23 import java.util.Map;
24 import java.util.Objects;
25 import java.util.Optional;
26 import java.util.regex.Pattern;
27
28 import org.apache.commons.collections4.CollectionUtils;
29 import org.apache.commons.collections4.MapUtils;
30 import org.apache.commons.lang3.tuple.ImmutablePair;
31 import org.apache.commons.lang3.tuple.Pair;
32 import org.openecomp.core.validation.ErrorMessageCode;
33 import org.openecomp.core.validation.errors.ErrorMessagesFormatBuilder;
34 import org.openecomp.core.validation.types.GlobalValidationContext;
35 import org.openecomp.sdc.common.errors.Messages;
36 import org.openecomp.sdc.datatypes.error.ErrorLevel;
37 import org.openecomp.sdc.heat.datatypes.model.Resource;
38 import org.openecomp.sdc.validation.ResourceValidator;
39 import org.openecomp.sdc.validation.ValidationContext;
40 import org.openecomp.sdc.validation.util.ValidationUtil;
41
42
43 public class ContrailServiceTemplateNamingConventionValidator implements ResourceValidator {
44   private static final ErrorMessageCode ERROR_CODE_NST1 = new ErrorMessageCode("NST1");
45   private static final ErrorMessageCode ERROR_CODE_NST2 = new ErrorMessageCode("NST2");
46   private static final ErrorMessageCode ERROR_CODE_NST3 = new ErrorMessageCode("NST3");
47
48   @Override
49   public void validate(String fileName, Map.Entry<String, Resource> resourceEntry,
50                        GlobalValidationContext globalContext, ValidationContext validationContext) {
51     validateServiceTemplateImageAndFlavor(fileName, resourceEntry, globalContext);
52   }
53
54   private void validateServiceTemplateImageAndFlavor(String fileName,
55                                                      Map.Entry<String, Resource> entry,
56                                                      GlobalValidationContext globalContext) {
57     if (MapUtils.isEmpty(entry.getValue().getProperties())) {
58       return;
59     }
60
61     Pair<String, String> imagePair = new ImmutablePair<>("image_name", ".*_image_name");
62     Pair<String, String> flavorPair = new ImmutablePair<>("flavor", ".*_flavor_name");
63     List<Pair<String, String>> imageFlavorPairs = Arrays.asList(imagePair, flavorPair);
64
65     Map<String, Object> propertiesMap = entry.getValue().getProperties();
66
67     boolean errorExistValidatingImageOrFlavor = false;
68     for (Pair<String, String> imageOrFlavor : imageFlavorPairs) {
69       boolean errorExistWhenValidatingImageOrFlavorNames =
70               isErrorExistWhenValidatingImageOrFlavorNames(fileName, imageOrFlavor, entry,
71                       propertiesMap, globalContext);
72       errorExistValidatingImageOrFlavor =
73               errorExistValidatingImageOrFlavor || errorExistWhenValidatingImageOrFlavorNames;
74     }
75
76     if (!errorExistValidatingImageOrFlavor) {
77       validateServiceTemplatePropertiesValuesVmtypesAreIdentical(fileName, entry, globalContext,
78               propertiesMap);
79     }
80   }
81
82   private void validateServiceTemplatePropertiesValuesVmtypesAreIdentical(String fileName,
83                                                                           Map.Entry<String, Resource> entry,
84                                                                           GlobalValidationContext globalContext,
85                                                                           Map<String, Object> propertiesMap) {
86     Pair<String, String> vmTypeImagePair = new ImmutablePair<>("image_name", "\\_image\\_name");
87     Pair<String, String> vmTypeFlavorPair = new ImmutablePair<>("flavor", "\\_flavor\\_name");
88     validatePropertiesValuesVmtypesAreIdentical(Arrays.asList(vmTypeImagePair, vmTypeFlavorPair),
89             fileName, entry, propertiesMap, globalContext);
90   }
91
92   private void validatePropertiesValuesVmtypesAreIdentical(List<Pair> propertiesToMatch,
93                                                            String fileName,
94                                                            Map.Entry<String, Resource> resourceEntry,
95                                                            Map<String, Object> propertiesMap,
96                                                            GlobalValidationContext globalContext) {
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           return;
113         }
114       }
115     }
116   }
117
118   private boolean addWarningIfCurrentVmTypeIsDifferentFromPrevious(String fileName,
119                                                                    Map.Entry<String, Resource> resourceEntry,
120                                                                    GlobalValidationContext globalContext,
121                                                                    String previousPropertyValueValue,
122                                                                    String currentPropVmType) {
123     if (!Objects.equals(previousPropertyValueValue, currentPropVmType)) {
124       globalContext.addMessage(fileName, ErrorLevel.WARNING, ErrorMessagesFormatBuilder
125                       .getErrorWithParameters(
126                               ERROR_CODE_NST1, Messages.CONTRAIL_VM_TYPE_NAME_NOT_ALIGNED_WITH_NAMING_CONVENSION
127                                       .getErrorMessage(),
128                               resourceEntry.getKey()));
129       return true;
130     }
131
132     return false;
133   }
134
135   private boolean isErrorExistWhenValidatingImageOrFlavorNames(String fileName,
136                                                                Pair<String, String> propertyNameAndRegex,
137                                                                Map.Entry<String, Resource> resourceEntry,
138                                                                Map<String, Object> propertiesMap,
139                                                                GlobalValidationContext globalContext) {
140     String propertyName = propertyNameAndRegex.getKey();
141     Object nameValue = propertiesMap.get(propertyName);
142     String[] regexList = new String[]{propertyNameAndRegex.getValue()};
143     if (nonNull(nameValue)) {
144       if (nameValue instanceof Map) {
145         globalContext.setMessageCode(ERROR_CODE_NST3);
146         if (ValidationUtil.validateMapPropertyValue(fileName, resourceEntry, globalContext,
147                 propertyName,
148                 nameValue, regexList)) {
149           return true;
150         }
151       } else {
152         globalContext.addMessage(
153                 fileName,
154                 ErrorLevel.WARNING, ErrorMessagesFormatBuilder
155                         .getErrorWithParameters(
156                                 ERROR_CODE_NST2, Messages.MISSING_GET_PARAM.getErrorMessage(),
157                                 propertyName,
158                                 resourceEntry.getKey()));
159         return true;
160       }
161
162       return false;
163     }
164     return false;
165   }
166
167
168   private Optional<String> extractVmTypeFromProperty(String fileName,
169                                                      Map.Entry<String, Resource> resourceEntry,
170                                                      Map<String, Object> propertiesMap,
171                                                      GlobalValidationContext globalContext,
172                                                      Pair propertyKeyRegex) {
173     String propertyName = (String) propertyKeyRegex.getKey();
174     Object propertyVal = propertiesMap.get(propertyName);
175     if (nonNull(propertyVal)) {
176       if (propertyVal instanceof Map) {
177         String propertyValFromGetParam = ValidationUtil.getWantedNameFromPropertyValueGetParam
178                 (propertyVal);
179         if (nonNull(propertyValFromGetParam)) {
180           Pattern pattern = Pattern.compile("" + propertyKeyRegex.getValue());
181           return Optional.ofNullable(pattern.split(propertyValFromGetParam)[0]);
182         }
183       } else {
184         globalContext.addMessage(
185                 fileName,
186                 ErrorLevel.WARNING, ErrorMessagesFormatBuilder
187                         .getErrorWithParameters(
188                                 ERROR_CODE_NST2, Messages.MISSING_GET_PARAM.getErrorMessage(),
189                                 propertyName,
190                                 resourceEntry.getKey()));
191         return Optional.empty();
192       }
193     }
194     return Optional.empty();
195   }
196
197   private String handleFirstIteration(String previousPropertyValueValue, String currentPropVmType) {
198     String previousPropertyValue;
199     if (Objects.isNull(previousPropertyValueValue)) {
200       previousPropertyValue = currentPropVmType;
201       return previousPropertyValue;
202     }
203
204    return previousPropertyValueValue;
205   }
206 }