2 * Copyright © 2016-2018 European Support Limited
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
8 * http://www.apache.org/licenses/LICENSE-2.0
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.
16 package org.openecomp.sdc.be.datamodel.utils;
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;
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;
52 public class PropertyValueConstraintValidationUtil {
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;
64 public Either<Boolean, ResponseFormat> validatePropertyConstraints(final Collection<? extends PropertyDefinition> propertyDefinitionList,
65 final ApplicationDataTypeCache applicationDataTypeCache,
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));
77 return Either.left(Boolean.TRUE);
80 private boolean isValuePresent(PropertyDefinition propertyDefinition) {
81 if (propertyDefinition instanceof ComponentInstanceInput) {
82 return StringUtils.isNotEmpty(propertyDefinition.getValue());
84 if (propertyDefinition instanceof InputDefinition) {
85 return StringUtils.isNotEmpty(propertyDefinition.getDefaultValue());
87 return StringUtils.isNotEmpty(propertyDefinition.getValue());
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));
95 completeInputName = "";
96 completePropertyName = new StringBuilder();
97 if (propertyDefinition instanceof ComponentInstanceInput) {
98 setCompletePropertyName(propertyDefinition);
99 evaluateComplexTypeProperties(propertyDefinition);
102 if (propertyDefinition instanceof InputDefinition) {
103 completeInputName = propertyDefinition.getName();
104 propertyDefinition = getPropertyDefinitionObjectFromInputs(propertyDefinition);
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);
117 setCompletePropertyName(propertyDefinition);
118 evaluateComplexTypeProperties(propertyDefinition);
123 private void setCompletePropertyName(PropertyDefinition propertyDefinition) {
124 if (StringUtils.isNotBlank(propertyDefinition.getUniqueId())) {
125 completePropertyName.append(propertyDefinition.getUniqueId().substring(propertyDefinition.getUniqueId().lastIndexOf('.') + 1));
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()) {
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)));
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()));
148 private boolean isPropertyNotMappedAsInput(PropertyDefinition propertyDefinition) {
149 return !propertyDefinition.getValue().startsWith(IGNORE_PROPERTY_VALUE_START_WITH);
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);
162 private void evaluateComplexTypeProperties(PropertyDefinition propertyDefinition) {
163 List<PropertyDefinition> propertyDefinitions = dataTypeDefinitionCache.get(propertyDefinition.getType()).getProperties();
165 Map<String, Object> valueMap = MapUtils
166 .emptyIfNull(ConstraintUtil.parseToCollection(propertyDefinition.getValue(), new TypeReference<>() {
168 if (CollectionUtils.isEmpty(propertyDefinitions)) {
169 checkAndEvaluatePrimitiveProperty(propertyDefinition, dataTypeDefinitionCache.get(propertyDefinition.getType()));
171 ListUtils.emptyIfNull(propertyDefinitions).forEach(prop -> evaluateRegularComplexType(propertyDefinition, prop, valueMap));
173 } catch (ConstraintValueDoNotMatchPropertyTypeException e) {
174 logger.debug(e.getMessage(), e);
175 errorMessages.add(String.format(VALUE_PROVIDED_IN_INVALID_FORMAT_FOR_PROPERTY, getCompletePropertyName(propertyDefinition)));
179 private void evaluateRegularComplexType(PropertyDefinition propertyDefinition, PropertyDefinition prop, Map<String, Object> valueMap) {
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()))));
187 completePropertyName.append(UNDERSCORE);
188 completePropertyName.append(prop.getName());
189 evaluateComplexTypeProperties(copyPropertyWithNewValue(prop, objectMapper.writeValueAsString(valueMap.get(prop.getName()))));
192 } catch (IOException e) {
193 logger.error(e.getMessage(), e);
194 errorMessages.add(String.format(VALUE_PROVIDED_IN_INVALID_FORMAT_FOR_PROPERTY, getCompletePropertyName(propertyDefinition)));
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);
207 private void evaluateListType(PropertyDefinition propertyDefinition) {
209 if (propertyDefinition.getSchemaType() == null) {
210 propertyDefinition.setSchema(createStringSchema());
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)));
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;
228 private void evaluateMapType(final PropertyDefinition propertyDefinition) {
230 if (propertyDefinition.getSchemaType() == null) {
231 propertyDefinition.setSchema(createStringSchema());
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)));
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);
251 private void evaluateCollectionType(final PropertyDefinition propertyDefinition, final Collection<Object> valueList) {
252 final String schemaType = propertyDefinition.getSchemaType();
253 for (final Object value : valueList) {
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);
263 propertyCopyWithNewValue.setType(schemaType);
264 completePropertyName.append(UNDERSCORE);
265 completePropertyName.append(propertyCopyWithNewValue.getName());
266 evaluateComplexTypeProperties(propertyCopyWithNewValue);
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)));
275 private String getCompletePropertyName(final PropertyDefinition propertyDefinition) {
276 if (StringUtils.isNotBlank(completeInputName)) {
277 return completeInputName;
280 final String propertyName = propertyDefinition == null ? "" : propertyDefinition.getName();
281 if (StringUtils.isNotBlank(completePropertyName)) {
282 return completePropertyName + UNDERSCORE + propertyName;
288 private PropertyDefinition copyPropertyWithNewValue(final PropertyDefinition propertyToCopy, final String value) {
289 final var propertyDefinition = new PropertyDefinition(propertyToCopy);
290 propertyDefinition.setValue(value);
291 return propertyDefinition;
294 private boolean isValidValueConstraintPresent(List<PropertyConstraint> propertyConstraints) {
295 return propertyConstraints != null && propertyConstraints.stream().anyMatch(ValidValuesConstraint.class::isInstance);
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);
309 return propertyDefinition;
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);
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());
325 presentMap.computeIfAbsent(inputPathArr[i], k -> new HashMap<String, Object>());
326 presentMap = (Map<String, Object>) presentMap.get(inputPathArr[i]);
329 if (CollectionUtils.isNotEmpty(inputDefinition.getProperties())) {
330 propertyDefinition.setType(inputDefinition.getProperties().get(0).getType());
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()));
338 return propertyDefinition;
341 protected ResponseFormatManager getResponseFormatManager() {
342 return ResponseFormatManager.getInstance();