4b8d88fa79633d404c5489f8a3c9f0f693b18aa3
[sdc.git] /
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 package org.openecomp.sdc.be.datamodel.utils;
17
18 import com.fasterxml.jackson.core.JsonProcessingException;
19 import com.fasterxml.jackson.core.type.TypeReference;
20 import com.fasterxml.jackson.databind.ObjectMapper;
21 import fj.data.Either;
22 import java.io.IOException;
23 import java.util.ArrayList;
24 import java.util.Collection;
25 import java.util.HashMap;
26 import java.util.List;
27 import java.util.Map;
28 import java.util.Objects;
29 import org.apache.commons.collections4.CollectionUtils;
30 import org.apache.commons.collections4.ListUtils;
31 import org.apache.commons.collections4.MapUtils;
32 import org.apache.commons.lang3.ArrayUtils;
33 import org.apache.commons.lang3.StringUtils;
34 import org.openecomp.sdc.be.components.impl.ResponseFormatManager;
35 import org.openecomp.sdc.be.dao.api.ActionStatus;
36 import org.openecomp.sdc.be.datatypes.elements.SchemaDefinition;
37 import org.openecomp.sdc.be.model.ComponentInstanceInput;
38 import org.openecomp.sdc.be.model.DataTypeDefinition;
39 import org.openecomp.sdc.be.model.InputDefinition;
40 import org.openecomp.sdc.be.model.PropertyConstraint;
41 import org.openecomp.sdc.be.model.PropertyDefinition;
42 import org.openecomp.sdc.be.model.cache.ApplicationDataTypeCache;
43 import org.openecomp.sdc.be.model.tosca.ToscaType;
44 import org.openecomp.sdc.be.model.tosca.constraints.ConstraintUtil;
45 import org.openecomp.sdc.be.model.tosca.constraints.ValidValuesConstraint;
46 import org.openecomp.sdc.be.model.tosca.constraints.exception.ConstraintValueDoNotMatchPropertyTypeException;
47 import org.openecomp.sdc.be.model.tosca.constraints.exception.ConstraintViolationException;
48 import org.openecomp.sdc.exception.ResponseFormat;
49 import org.slf4j.Logger;
50 import org.slf4j.LoggerFactory;
51
52 public class PropertyValueConstraintValidationUtil {
53
54     private static final String UNDERSCORE = "_";
55     private static final String VALUE_PROVIDED_IN_INVALID_FORMAT_FOR_PROPERTY = "%nValue provided in invalid format for %s property";
56     private static final Logger logger = LoggerFactory.getLogger(PropertyValueConstraintValidationUtil.class);
57     private static final String IGNORE_PROPERTY_VALUE_START_WITH = "{\"get_input\":";
58     private Map<String, DataTypeDefinition> dataTypeDefinitionCache;
59     private final ObjectMapper objectMapper = new ObjectMapper();
60     private final List<String> errorMessages = new ArrayList<>();
61     private StringBuilder completePropertyName;
62     private String completeInputName;
63
64     public Either<Boolean, ResponseFormat> validatePropertyConstraints(final Collection<? extends PropertyDefinition> propertyDefinitionList,
65                                                                        final ApplicationDataTypeCache applicationDataTypeCache,
66                                                                        final String model) {
67
68         dataTypeDefinitionCache = applicationDataTypeCache.getAll(model).left().value();
69         CollectionUtils.emptyIfNull(propertyDefinitionList).stream()
70             .filter(this::isValuePresent)
71             .forEach(this::evaluatePropertyTypeForConstraintValidation);
72         if (CollectionUtils.isNotEmpty(errorMessages)) {
73             final String errorMsgAsString = String.join(",", errorMessages);
74             logger.debug("Properties with Invalid Data: {}", errorMsgAsString);
75             return Either.right(getResponseFormatManager().getResponseFormat(ActionStatus.INVALID_PROPERTY_VALUES, errorMsgAsString));
76         }
77         return Either.left(Boolean.TRUE);
78     }
79
80     private boolean isValuePresent(PropertyDefinition propertyDefinition) {
81         if (propertyDefinition instanceof ComponentInstanceInput) {
82             return StringUtils.isNotEmpty(propertyDefinition.getValue());
83         }
84         if (propertyDefinition instanceof InputDefinition) {
85             return StringUtils.isNotEmpty(propertyDefinition.getDefaultValue());
86         }
87         return StringUtils.isNotEmpty(propertyDefinition.getValue());
88     }
89
90     private void evaluatePropertyTypeForConstraintValidation(PropertyDefinition propertyDefinition) {
91         if (propertyDefinition == null || propertyDefinition.getType() == null || !dataTypeDefinitionCache.containsKey(propertyDefinition.getType())) {
92             errorMessages.add("\nUnsupported datatype found for property " + getCompletePropertyName(propertyDefinition));
93             return;
94         }
95         completeInputName = "";
96         completePropertyName = new StringBuilder();
97         if (propertyDefinition instanceof ComponentInstanceInput) {
98             setCompletePropertyName(propertyDefinition);
99             evaluateComplexTypeProperties(propertyDefinition);
100             return;
101         }
102         if (propertyDefinition instanceof InputDefinition) {
103             completeInputName = propertyDefinition.getName();
104             propertyDefinition = getPropertyDefinitionObjectFromInputs(propertyDefinition);
105         }
106         if (propertyDefinition != null) {
107             if (ToscaType.isPrimitiveType(propertyDefinition.getType())) {
108                 propertyDefinition.setConstraints(org.openecomp.sdc.be.dao.utils.CollectionUtils.merge(propertyDefinition.safeGetConstraints(),
109                     dataTypeDefinitionCache.get(propertyDefinition.getType()).safeGetConstraints()));
110                 evaluateConstraintsOnProperty(propertyDefinition);
111             } else if (ToscaType.isCollectionType(propertyDefinition.getType())) {
112                 propertyDefinition.setConstraints(org.openecomp.sdc.be.dao.utils.CollectionUtils.merge(propertyDefinition.safeGetConstraints(),
113                     dataTypeDefinitionCache.get(propertyDefinition.getType()).safeGetConstraints()));
114                 evaluateConstraintsOnProperty(propertyDefinition);
115                 evaluateCollectionTypeProperties(propertyDefinition);
116             } else {
117                 setCompletePropertyName(propertyDefinition);
118                 evaluateComplexTypeProperties(propertyDefinition);
119             }
120         }
121     }
122
123     private void setCompletePropertyName(PropertyDefinition propertyDefinition) {
124         if (StringUtils.isNotBlank(propertyDefinition.getUniqueId())) {
125             completePropertyName.append(propertyDefinition.getUniqueId().substring(propertyDefinition.getUniqueId().lastIndexOf('.') + 1));
126         }
127     }
128
129     private void evaluateConstraintsOnProperty(PropertyDefinition propertyDefinition) {
130         ToscaType toscaType = ToscaType.isValidType(propertyDefinition.getType());
131         if (isPropertyNotMappedAsInput(propertyDefinition) && CollectionUtils.isNotEmpty(propertyDefinition.getConstraints())) {
132             for (PropertyConstraint propertyConstraint : propertyDefinition.getConstraints()) {
133                 try {
134                     propertyConstraint.initialize(toscaType);
135                     propertyConstraint.validate(toscaType, propertyDefinition.getValue());
136                 } catch (ConstraintValueDoNotMatchPropertyTypeException | ConstraintViolationException exception) {
137                     errorMessages.add("\n" + propertyConstraint.getErrorMessage(toscaType, exception, getCompletePropertyName(propertyDefinition)));
138                 }
139             }
140         } else if (isPropertyNotMappedAsInput(propertyDefinition) && ToscaType.isPrimitiveType(propertyDefinition.getType()) && !toscaType
141             .isValidValue(propertyDefinition.getValue())) {
142             errorMessages.add(String
143                 .format("\nUnsupported value provided for %s property supported value " + "type is %s.", getCompletePropertyName(propertyDefinition),
144                     toscaType.getType()));
145         }
146     }
147
148     private boolean isPropertyNotMappedAsInput(PropertyDefinition propertyDefinition) {
149         return !propertyDefinition.getValue().startsWith(IGNORE_PROPERTY_VALUE_START_WITH);
150     }
151
152     private void checkAndEvaluatePrimitiveProperty(PropertyDefinition propertyDefinition, DataTypeDefinition dataTypeDefinition) {
153         if (ToscaType.isPrimitiveType(dataTypeDefinition.getName()) && CollectionUtils.isNotEmpty(dataTypeDefinition.getConstraints())) {
154             PropertyDefinition definition = new PropertyDefinition();
155             definition.setValue(propertyDefinition.getValue());
156             definition.setType(dataTypeDefinition.getName());
157             definition.setConstraints(dataTypeDefinition.getConstraints());
158             evaluateConstraintsOnProperty(propertyDefinition);
159         }
160     }
161
162     private void evaluateComplexTypeProperties(PropertyDefinition propertyDefinition) {
163         List<PropertyDefinition> propertyDefinitions = dataTypeDefinitionCache.get(propertyDefinition.getType()).getProperties();
164         try {
165             Map<String, Object> valueMap = MapUtils
166                 .emptyIfNull(ConstraintUtil.parseToCollection(propertyDefinition.getValue(), new TypeReference<>() {
167                 }));
168             if (CollectionUtils.isEmpty(propertyDefinitions)) {
169                 checkAndEvaluatePrimitiveProperty(propertyDefinition, dataTypeDefinitionCache.get(propertyDefinition.getType()));
170             } else {
171                 ListUtils.emptyIfNull(propertyDefinitions).forEach(prop -> evaluateRegularComplexType(propertyDefinition, prop, valueMap));
172             }
173         } catch (ConstraintValueDoNotMatchPropertyTypeException e) {
174             logger.debug(e.getMessage(), e);
175             errorMessages.add(String.format(VALUE_PROVIDED_IN_INVALID_FORMAT_FOR_PROPERTY, getCompletePropertyName(propertyDefinition)));
176         }
177     }
178
179     private void evaluateRegularComplexType(PropertyDefinition propertyDefinition, PropertyDefinition prop, Map<String, Object> valueMap) {
180         try {
181             if (valueMap.containsKey(prop.getName())) {
182                 if (ToscaType.isPrimitiveType(prop.getType())) {
183                     evaluateConstraintsOnProperty(copyPropertyWithNewValue(prop, String.valueOf(valueMap.get(prop.getName()))));
184                 } else if (ToscaType.isCollectionType(prop.getType())) {
185                     evaluateCollectionTypeProperties(copyPropertyWithNewValue(prop, objectMapper.writeValueAsString(valueMap.get(prop.getName()))));
186                 } else {
187                     completePropertyName.append(UNDERSCORE);
188                     completePropertyName.append(prop.getName());
189                     evaluateComplexTypeProperties(copyPropertyWithNewValue(prop, objectMapper.writeValueAsString(valueMap.get(prop.getName()))));
190                 }
191             }
192         } catch (IOException e) {
193             logger.error(e.getMessage(), e);
194             errorMessages.add(String.format(VALUE_PROVIDED_IN_INVALID_FORMAT_FOR_PROPERTY, getCompletePropertyName(propertyDefinition)));
195         }
196     }
197
198     private void evaluateCollectionTypeProperties(PropertyDefinition propertyDefinition) {
199         ToscaType toscaPropertyType = ToscaType.isValidType(propertyDefinition.getType());
200         if (ToscaType.LIST == toscaPropertyType) {
201             evaluateListType(propertyDefinition);
202         } else if (ToscaType.MAP == toscaPropertyType) {
203             evaluateMapType(propertyDefinition);
204         }
205     }
206
207     private void evaluateListType(PropertyDefinition propertyDefinition) {
208         try {
209             if (propertyDefinition.getSchemaType() == null) {
210                 propertyDefinition.setSchema(createStringSchema());
211             }
212             List<Object> list = ConstraintUtil.parseToCollection(propertyDefinition.getValue(), new TypeReference<>() {});
213             evaluateCollectionType(propertyDefinition, list);
214         } catch (ConstraintValueDoNotMatchPropertyTypeException e) {
215             logger.debug(e.getMessage(), e);
216             errorMessages.add(String.format(VALUE_PROVIDED_IN_INVALID_FORMAT_FOR_PROPERTY, getCompletePropertyName(propertyDefinition)));
217         }
218     }
219
220     private SchemaDefinition createStringSchema() {
221         final SchemaDefinition schemaDefinition = new SchemaDefinition();
222         final PropertyDefinition schemaStringProperty = new PropertyDefinition();
223         schemaStringProperty.setType(ToscaType.STRING.getType());
224         schemaDefinition.setProperty(schemaStringProperty);
225         return schemaDefinition;
226     }
227
228     private void evaluateMapType(final PropertyDefinition propertyDefinition) {
229         try {
230             if (propertyDefinition.getSchemaType() == null) {
231                 propertyDefinition.setSchema(createStringSchema());
232             }
233             final Map<String, Object> map = ConstraintUtil.parseToCollection(propertyDefinition.getValue(), new TypeReference<>() {});
234             evaluateCollectionType(propertyDefinition, map.values());
235         } catch (ConstraintValueDoNotMatchPropertyTypeException e) {
236             logger.debug(e.getMessage(), e);
237             errorMessages.add(String.format(VALUE_PROVIDED_IN_INVALID_FORMAT_FOR_PROPERTY, getCompletePropertyName(propertyDefinition)));
238         }
239     }
240
241     private void evaluateCollectionPrimitiveSchemaType(final PropertyDefinition propertyDefinition,
242                                                        final String schemaType) throws JsonProcessingException {
243         if (propertyDefinition.getSchema() != null && propertyDefinition.getSchema().getProperty() instanceof PropertyDefinition) {
244             propertyDefinition.setConstraints(((PropertyDefinition) propertyDefinition.getSchema().getProperty()).getConstraints());
245             propertyDefinition.setValue(objectMapper.readValue(propertyDefinition.getValue(), String.class));
246             propertyDefinition.setType(schemaType);
247             evaluateConstraintsOnProperty(propertyDefinition);
248         }
249     }
250
251     private void evaluateCollectionType(final PropertyDefinition propertyDefinition, final Collection<Object> valueList) {
252         final String schemaType = propertyDefinition.getSchemaType();
253         for (final Object value : valueList) {
254             try {
255                 final PropertyDefinition propertyCopyWithNewValue = copyPropertyWithNewValue(propertyDefinition, objectMapper.writeValueAsString(value));
256                 if (ToscaType.isPrimitiveType(schemaType)) {
257                     evaluateCollectionPrimitiveSchemaType(propertyCopyWithNewValue, schemaType);
258                 } else if (ToscaType.isCollectionType(schemaType)) {
259                     propertyCopyWithNewValue.setType(schemaType);
260                     propertyCopyWithNewValue.setSchemaType(propertyDefinition.getSchemaProperty().getSchemaType());
261                     evaluateCollectionTypeProperties(propertyCopyWithNewValue);
262                 } else {
263                     propertyCopyWithNewValue.setType(schemaType);
264                     completePropertyName.append(UNDERSCORE);
265                     completePropertyName.append(propertyCopyWithNewValue.getName());
266                     evaluateComplexTypeProperties(propertyCopyWithNewValue);
267                 }
268             } catch (final Exception e) {
269                 logger.debug(e.getMessage(), e);
270                 errorMessages.add(String.format(VALUE_PROVIDED_IN_INVALID_FORMAT_FOR_PROPERTY, getCompletePropertyName(propertyDefinition)));
271             }
272         }
273     }
274
275     private String getCompletePropertyName(final PropertyDefinition propertyDefinition) {
276         if (StringUtils.isNotBlank(completeInputName)) {
277             return completeInputName;
278         }
279
280         final String propertyName = propertyDefinition == null ? "" : propertyDefinition.getName();
281         if (StringUtils.isNotBlank(completePropertyName)) {
282             return completePropertyName + UNDERSCORE + propertyName;
283         }
284
285         return propertyName;
286     }
287
288     private PropertyDefinition copyPropertyWithNewValue(final PropertyDefinition propertyToCopy, final String value) {
289         final var propertyDefinition = new PropertyDefinition(propertyToCopy);
290         propertyDefinition.setValue(value);
291         return propertyDefinition;
292     }
293
294     private boolean isValidValueConstraintPresent(List<PropertyConstraint> propertyConstraints) {
295         return propertyConstraints != null && propertyConstraints.stream().anyMatch(ValidValuesConstraint.class::isInstance);
296     }
297
298     private PropertyDefinition getPropertyDefinitionObjectFromInputs(PropertyDefinition property) {
299         InputDefinition inputDefinition = (InputDefinition) property;
300         PropertyDefinition propertyDefinition = null;
301         if (CollectionUtils.isEmpty(inputDefinition.getProperties()) || ToscaType.isPrimitiveType(inputDefinition.getProperties().get(0).getType())) {
302             propertyDefinition = new PropertyDefinition();
303             propertyDefinition.setType(inputDefinition.getType());
304             propertyDefinition.setValue(inputDefinition.getDefaultValue());
305             propertyDefinition.setName(inputDefinition.getName());
306         } else if (Objects.nonNull(inputDefinition.getInputPath())) {
307             propertyDefinition = evaluateComplexTypeInputs(inputDefinition);
308         }
309         return propertyDefinition;
310     }
311
312     private PropertyDefinition evaluateComplexTypeInputs(InputDefinition inputDefinition) {
313         Map<String, Object> inputMap = new HashMap<>();
314         PropertyDefinition propertyDefinition = new PropertyDefinition();
315         String[] inputPathArr = inputDefinition.getInputPath().split("#");
316         if (inputPathArr.length > 1) {
317             inputPathArr = ArrayUtils.remove(inputPathArr, 0);
318         }
319         try {
320             Map<String, Object> presentMap = inputMap;
321             for (int i = 0; i < inputPathArr.length; i++) {
322                 if (i == inputPathArr.length - 1) {
323                     presentMap.computeIfAbsent(inputPathArr[i], k -> inputDefinition.getDefaultValue());
324                 } else {
325                     presentMap.computeIfAbsent(inputPathArr[i], k -> new HashMap<String, Object>());
326                     presentMap = (Map<String, Object>) presentMap.get(inputPathArr[i]);
327                 }
328             }
329             if (CollectionUtils.isNotEmpty(inputDefinition.getProperties())) {
330                 propertyDefinition.setType(inputDefinition.getProperties().get(0).getType());
331             }
332             propertyDefinition.setName(inputDefinition.getName());
333             propertyDefinition.setValue(objectMapper.writeValueAsString(inputMap));
334         } catch (IOException e) {
335             logger.error(e.getMessage(), e);
336             errorMessages.add(String.format(VALUE_PROVIDED_IN_INVALID_FORMAT_FOR_PROPERTY, inputDefinition.getName()));
337         }
338         return propertyDefinition;
339     }
340
341     protected ResponseFormatManager getResponseFormatManager() {
342         return ResponseFormatManager.getInstance();
343     }
344 }