Fix bug 'Pattern constraint validation failure'
[sdc.git] / catalog-be / src / main / java / org / openecomp / sdc / be / tosca / PropertyConvertor.java
1 /*-
2  * ============LICENSE_START=======================================================
3  * SDC
4  * ================================================================================
5  * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved.
6  * ================================================================================
7  * Licensed under the Apache License, Version 2.0 (the "License");
8  * you may not use this file except in compliance with the License.
9  * You may obtain a copy of the License at
10  *
11  *      http://www.apache.org/licenses/LICENSE-2.0
12  *
13  * Unless required by applicable law or agreed to in writing, software
14  * distributed under the License is distributed on an "AS IS" BASIS,
15  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
16  * See the License for the specific language governing permissions and
17  * limitations under the License.
18  * ============LICENSE_END=========================================================
19  */
20 package org.openecomp.sdc.be.tosca;
21
22 import com.google.gson.JsonElement;
23 import com.google.gson.JsonObject;
24 import com.google.gson.JsonParseException;
25 import com.google.gson.JsonParser;
26 import com.google.gson.stream.JsonReader;
27 import fj.data.Either;
28 import java.io.StringReader;
29 import java.util.ArrayList;
30 import java.util.HashMap;
31 import java.util.List;
32 import java.util.Map;
33 import java.util.Objects;
34 import java.util.function.Supplier;
35 import org.apache.commons.collections.CollectionUtils;
36 import org.apache.commons.lang3.StringUtils;
37 import org.openecomp.sdc.be.datatypes.elements.PropertyDataDefinition;
38 import org.openecomp.sdc.be.datatypes.elements.SchemaDefinition;
39 import org.openecomp.sdc.be.datatypes.elements.ToscaFunctionType;
40 import org.openecomp.sdc.be.model.Component;
41 import org.openecomp.sdc.be.model.DataTypeDefinition;
42 import org.openecomp.sdc.be.model.PropertyConstraint;
43 import org.openecomp.sdc.be.model.PropertyDefinition;
44 import org.openecomp.sdc.be.model.Resource;
45 import org.openecomp.sdc.be.model.tosca.ToscaPropertyType;
46 import org.openecomp.sdc.be.model.tosca.constraints.EqualConstraint;
47 import org.openecomp.sdc.be.model.tosca.constraints.GreaterOrEqualConstraint;
48 import org.openecomp.sdc.be.model.tosca.constraints.GreaterThanConstraint;
49 import org.openecomp.sdc.be.model.tosca.constraints.InRangeConstraint;
50 import org.openecomp.sdc.be.model.tosca.constraints.LengthConstraint;
51 import org.openecomp.sdc.be.model.tosca.constraints.LessOrEqualConstraint;
52 import org.openecomp.sdc.be.model.tosca.constraints.LessThanConstraint;
53 import org.openecomp.sdc.be.model.tosca.constraints.MaxLengthConstraint;
54 import org.openecomp.sdc.be.model.tosca.constraints.MinLengthConstraint;
55 import org.openecomp.sdc.be.model.tosca.constraints.PatternConstraint;
56 import org.openecomp.sdc.be.model.tosca.constraints.ValidValuesConstraint;
57 import org.openecomp.sdc.be.model.tosca.converters.DataTypePropertyConverter;
58 import org.openecomp.sdc.be.model.tosca.converters.ToscaMapValueConverter;
59 import org.openecomp.sdc.be.model.tosca.converters.ToscaValueBaseConverter;
60 import org.openecomp.sdc.be.model.tosca.converters.ToscaValueConverter;
61 import org.openecomp.sdc.be.tosca.model.ToscaNodeType;
62 import org.openecomp.sdc.be.tosca.model.ToscaProperty;
63 import org.openecomp.sdc.be.tosca.model.ToscaPropertyConstraint;
64 import org.openecomp.sdc.be.tosca.model.ToscaPropertyConstraintEqual;
65 import org.openecomp.sdc.be.tosca.model.ToscaPropertyConstraintGreaterOrEqual;
66 import org.openecomp.sdc.be.tosca.model.ToscaPropertyConstraintGreaterThan;
67 import org.openecomp.sdc.be.tosca.model.ToscaPropertyConstraintInRange;
68 import org.openecomp.sdc.be.tosca.model.ToscaPropertyConstraintLength;
69 import org.openecomp.sdc.be.tosca.model.ToscaPropertyConstraintLessOrEqual;
70 import org.openecomp.sdc.be.tosca.model.ToscaPropertyConstraintLessThan;
71 import org.openecomp.sdc.be.tosca.model.ToscaPropertyConstraintMaxLength;
72 import org.openecomp.sdc.be.tosca.model.ToscaPropertyConstraintMinLength;
73 import org.openecomp.sdc.be.tosca.model.ToscaPropertyConstraintPattern;
74 import org.openecomp.sdc.be.tosca.model.ToscaPropertyConstraintValidValues;
75 import org.openecomp.sdc.be.tosca.model.ToscaSchemaDefinition;
76 import org.openecomp.sdc.common.log.wrappers.Logger;
77 import org.openecomp.sdc.tosca.datatypes.ToscaFunctions;
78 import org.springframework.stereotype.Service;
79 import org.yaml.snakeyaml.Yaml;
80
81
82 @Service
83 public class PropertyConvertor {
84
85     private static final Logger log = Logger.getLogger(PropertyConvertor.class);
86
87     public Either<ToscaNodeType, ToscaError> convertProperties(Component component, ToscaNodeType toscaNodeType,
88                                                                Map<String, DataTypeDefinition> dataTypes) {
89         if (component instanceof Resource) {
90             Resource resource = (Resource) component;
91             List<PropertyDefinition> props = resource.getProperties();
92             if (props != null) {
93                 Map<String, ToscaProperty> properties = new HashMap<>();
94                 // take only the properties of this resource
95                 props.stream().filter(p -> p.getOwnerId() == null || p.getOwnerId().equals(component.getUniqueId())).forEach(property ->
96                     properties.put(property.getName(), convertProperty(dataTypes, property, PropertyType.PROPERTY))
97                 );
98                 if (!properties.isEmpty()) {
99                     toscaNodeType.setProperties(properties);
100                 }
101             }
102         }
103         return Either.left(toscaNodeType);
104     }
105
106     public ToscaProperty convertProperty(Map<String, DataTypeDefinition> dataTypes, PropertyDefinition property, PropertyType propertyType) {
107         ToscaProperty prop = new ToscaProperty();
108         log.trace("try to convert property {} from type {} with default value [{}]", property.getName(), property.getType(),
109             property.getDefaultValue());
110         SchemaDefinition schema = property.getSchema();
111         if (schema != null && schema.getProperty() != null && schema.getProperty().getType() != null && !schema.getProperty().getType().isEmpty()) {
112             final ToscaSchemaDefinition toscaSchemaDefinition = new ToscaSchemaDefinition();
113             toscaSchemaDefinition.setType(schema.getProperty().getType());
114             toscaSchemaDefinition.setDescription(schema.getProperty().getDescription());
115             prop.setEntry_schema(toscaSchemaDefinition);
116         }
117         String defaultValue = property.getDefaultValue();
118         if (Objects.isNull(defaultValue)) {
119             defaultValue = property.getValue();
120         }
121         Object convertedObj = convertToToscaObject(property, defaultValue, dataTypes, false);
122         if (convertedObj != null) {
123             prop.setDefaultp(convertedObj);
124         }
125         prop.setType(property.getType());
126         prop.setDescription(property.getDescription());
127         prop.setRequired(property.isRequired());
128         if (propertyType.equals(PropertyType.CAPABILITY)) {
129             prop.setStatus(property.getStatus());
130         }
131         prop.setMetadata(property.getMetadata());
132
133         if (CollectionUtils.isNotEmpty(property.getConstraints())) {
134             prop.setConstraints(convertConstraints(property.getConstraints()));
135         }
136         return prop;
137     }
138
139     private List<ToscaPropertyConstraint> convertConstraints(List<PropertyConstraint> constraints) {
140         List<ToscaPropertyConstraint> convertedConstraints = new ArrayList<>();
141         for (PropertyConstraint constraint : constraints) {
142             if (constraint instanceof EqualConstraint) {
143                 convertedConstraints.add(new ToscaPropertyConstraintEqual(((EqualConstraint) constraint).getEqual()));
144             }
145             if (constraint instanceof GreaterThanConstraint) {
146                 convertedConstraints.add(new ToscaPropertyConstraintGreaterThan(((GreaterThanConstraint) constraint).getGreaterThan()));
147             }
148             if (constraint instanceof GreaterOrEqualConstraint) {
149                 convertedConstraints.add(new ToscaPropertyConstraintGreaterOrEqual(((GreaterOrEqualConstraint) constraint).getGreaterOrEqual()));
150             }
151             if (constraint instanceof LessThanConstraint) {
152                 convertedConstraints.add(new ToscaPropertyConstraintLessThan(((LessThanConstraint) constraint).getLessThan()));
153             }
154             if (constraint instanceof LessOrEqualConstraint) {
155                 convertedConstraints.add(new ToscaPropertyConstraintLessOrEqual(((LessOrEqualConstraint) constraint).getLessOrEqual()));
156             }
157             if (constraint instanceof InRangeConstraint) {
158                 InRangeConstraint inRangeConstraint = (InRangeConstraint) constraint;
159                 List<Object> range = new ArrayList<>();
160                 range.add(inRangeConstraint.getRangeMinValue());
161                 range.add(inRangeConstraint.getRangeMaxValue());
162                 convertedConstraints.add(new ToscaPropertyConstraintInRange(range));
163             }
164             if (constraint instanceof ValidValuesConstraint) {
165                 List validValues = ((ValidValuesConstraint) constraint).getValidValues();
166                 convertedConstraints.add(new ToscaPropertyConstraintValidValues(validValues));
167             }
168             if (constraint instanceof LengthConstraint) {
169                 convertedConstraints.add(new ToscaPropertyConstraintLength(((LengthConstraint) constraint).getLength()));
170             }
171             if (constraint instanceof MinLengthConstraint) {
172                 convertedConstraints.add(new ToscaPropertyConstraintMinLength(((MinLengthConstraint) constraint).getMinLength()));
173             }
174             if (constraint instanceof MaxLengthConstraint) {
175                 convertedConstraints.add(new ToscaPropertyConstraintMaxLength(((MaxLengthConstraint) constraint).getMaxLength()));
176             }
177             if (constraint instanceof PatternConstraint) {
178                 convertedConstraints.add(new ToscaPropertyConstraintPattern(((PatternConstraint) constraint).getPattern()));
179             }
180         }
181         return convertedConstraints;
182     }
183
184     public Object convertToToscaObject(PropertyDataDefinition property, String value, Map<String, DataTypeDefinition> dataTypes,
185                                        boolean preserveEmptyValue) {
186         String propertyType = property.getType();
187         String innerType = property.getSchemaType();
188         log.trace("try to convert propertyType {} , value [{}], innerType {}", propertyType, value, innerType);
189         if (StringUtils.isEmpty(value)) {
190             value = DataTypePropertyConverter.getInstance().getDataTypePropertiesDefaultValuesRec(propertyType, dataTypes);
191             if (StringUtils.isEmpty(value)) {
192                 return null;
193             }
194         }
195         if (property.isToscaFunction() && property.getToscaFunction().getType() == ToscaFunctionType.YAML) {
196             return new Yaml().load(property.getValue());
197         }
198         try {
199             ToscaMapValueConverter mapConverterInst = ToscaMapValueConverter.getInstance();
200             ToscaValueConverter innerConverter = null;
201             boolean isScalar = true;
202             ToscaPropertyType type = ToscaPropertyType.isValidType(propertyType);
203             if (type == null) {
204                 log.trace("isn't prederfined type, get from all data types");
205                 DataTypeDefinition dataTypeDefinition = dataTypes.get(propertyType);
206                 if (innerType == null) {
207                     innerType = propertyType;
208                 }
209                 if ((type = mapConverterInst.isScalarType(dataTypeDefinition)) != null) {
210                     log.trace("This is scalar type. get suitable converter for type {}", type);
211                     innerConverter = type.getValueConverter();
212                 } else {
213                     isScalar = false;
214                 }
215             } else {
216                 ToscaPropertyType typeIfScalar = ToscaPropertyType.getTypeIfScalar(type.getType());
217                 if (typeIfScalar == null) {
218                     isScalar = false;
219                 }
220                 innerConverter = type.getValueConverter();
221                 if (ToscaPropertyType.STRING == type && valueStartsWithNonJsonChar(value)) {
222                     return innerConverter.convertToToscaValue(value, innerType, dataTypes);
223                 }
224             }
225             JsonElement jsonElement = null;
226             StringReader reader = new StringReader(value);
227             JsonReader jsonReader = new JsonReader(reader);
228             jsonReader.setLenient(true);
229             jsonElement = JsonParser.parseReader(jsonReader);
230             if (value.equals("")) {
231                 return value;
232             }
233             if (jsonElement.isJsonPrimitive() && isScalar) {
234                 log.trace("It's well defined type. convert it");
235                 ToscaValueConverter converter = type.getValueConverter();
236                 return converter.convertToToscaValue(value, innerType, dataTypes);
237             }
238             log.trace("It's data type or inputs in primitive type. convert as map");
239             if (jsonElement.isJsonObject()) {
240                 JsonObject jsonObj = jsonElement.getAsJsonObject();
241                 // check if value is a get_input function
242                 if (jsonObj.entrySet().size() == 1 && jsonObj.has(ToscaFunctions.GET_INPUT.getFunctionName())) {
243                     Object obj = mapConverterInst.handleComplexJsonValue(jsonElement);
244                     log.debug("It's get_input function. obj={}", obj);
245                     return obj;
246                 }
247             }
248             Object convertedValue;
249             if (innerConverter != null && (ToscaPropertyType.MAP == type || ToscaPropertyType.LIST == type)) {
250                 convertedValue = innerConverter.convertToToscaValue(value, innerType, dataTypes);
251             } else if (isScalar) {
252                 // complex json for scalar type
253                 convertedValue = mapConverterInst.handleComplexJsonValue(jsonElement);
254             } else if (innerConverter != null) {
255                 convertedValue = innerConverter.convertToToscaValue(value, innerType, dataTypes);
256             } else {
257                 convertedValue = mapConverterInst
258                     .convertDataTypeToToscaObject(innerType, dataTypes, innerConverter, isScalar, jsonElement, preserveEmptyValue);
259             }
260             return convertedValue;
261
262         } catch (JsonParseException e) {
263             log.trace("{} not parsable as JSON. Convert as YAML instead", value);
264             return new Yaml().load(value);
265         } catch (Exception e) {
266             log.debug("convertToToscaValue failed to parse json value :", e);
267             return null;
268         }
269     }
270
271     private boolean valueStartsWithNonJsonChar(String value) {
272         return value.startsWith("/") || value.startsWith(":");
273     }
274
275     public void convertAndAddValue(Map<String, DataTypeDefinition> dataTypes, Map<String, Object> props, PropertyDataDefinition prop,
276                                    Supplier<String> supplier) {
277         Object convertedValue = convertValue(dataTypes, prop, supplier);
278         if (!ToscaValueBaseConverter.isEmptyObjectValue(convertedValue)) {
279             props.put(prop.getName(), convertedValue);
280         }
281     }
282
283     private <T extends PropertyDataDefinition> Object convertValue(Map<String, DataTypeDefinition> dataTypes, T input, Supplier<String> supplier) {
284         return convertToToscaObject(input, supplier.get(), dataTypes, false);
285     }
286
287     public enum PropertyType {CAPABILITY, INPUT, PROPERTY}
288 }