Fix numeric constraint values generated as strings
[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         List<ToscaPropertyConstraint> constraints = new ArrayList<>();
134         if (CollectionUtils.isNotEmpty(property.getConstraints())) {
135             constraints = convertConstraints(property.getConstraints());
136             prop.setConstraints(constraints);
137         }
138         return prop;
139     }
140     
141     private List<ToscaPropertyConstraint> convertConstraints(List<PropertyConstraint> constraints) {
142         List<ToscaPropertyConstraint> convertedConstraints = new ArrayList<>();
143         for (PropertyConstraint constraint: constraints){
144             if (constraint instanceof EqualConstraint) {
145                 convertedConstraints.add(new ToscaPropertyConstraintEqual(((EqualConstraint) constraint).getEqual()));
146             }
147             if (constraint instanceof GreaterThanConstraint) {
148                 convertedConstraints.add(new ToscaPropertyConstraintGreaterThan(((GreaterThanConstraint) constraint).getGreaterThan()));
149             }
150             if (constraint instanceof GreaterOrEqualConstraint) {
151                 convertedConstraints.add(new ToscaPropertyConstraintGreaterOrEqual(((GreaterOrEqualConstraint) constraint).getGreaterOrEqual()));
152             }
153             if (constraint instanceof LessThanConstraint) {
154                 convertedConstraints.add(new ToscaPropertyConstraintLessThan(((LessThanConstraint) constraint).getLessThan()));
155             }
156             if (constraint instanceof LessOrEqualConstraint) {
157                 convertedConstraints.add(new ToscaPropertyConstraintLessOrEqual(((LessOrEqualConstraint) constraint).getLessOrEqual()));
158             }
159             if (constraint instanceof InRangeConstraint) {
160                 InRangeConstraint inRangeConstraint = (InRangeConstraint) constraint;
161                 List<Object> range = new ArrayList<>();
162                 range.add(inRangeConstraint.getRangeMinValue());
163                 range.add(inRangeConstraint.getRangeMaxValue());
164                 convertedConstraints.add(new ToscaPropertyConstraintInRange(range));
165             }
166             if (constraint instanceof ValidValuesConstraint) {
167                 List validValues = ((ValidValuesConstraint) constraint).getValidValues();
168                 convertedConstraints.add(new ToscaPropertyConstraintValidValues(validValues));
169             }
170             if (constraint instanceof LengthConstraint) {
171                 convertedConstraints.add(new ToscaPropertyConstraintLength(((LengthConstraint) constraint).getLength()));
172             }
173             if (constraint instanceof MinLengthConstraint) {
174                 convertedConstraints.add(new ToscaPropertyConstraintMinLength(((MinLengthConstraint) constraint).getMinLength()));
175             }
176             if (constraint instanceof MaxLengthConstraint) {
177                 convertedConstraints.add(new ToscaPropertyConstraintMaxLength(((MaxLengthConstraint) constraint).getMaxLength()));
178             }
179             if (constraint instanceof PatternConstraint) {
180                 convertedConstraints.add(new ToscaPropertyConstraintPattern(((PatternConstraint) constraint).getPattern()));
181             }
182         }
183         return convertedConstraints;
184     }
185
186     public Object convertToToscaObject(PropertyDataDefinition property, String value, Map<String, DataTypeDefinition> dataTypes,
187                                        boolean preserveEmptyValue) {
188         String propertyType = property.getType();
189         String innerType = property.getSchemaType();
190         log.trace("try to convert propertyType {} , value [{}], innerType {}", propertyType, value, innerType);
191         if (StringUtils.isEmpty(value)) {
192             value = DataTypePropertyConverter.getInstance().getDataTypePropertiesDefaultValuesRec(propertyType, dataTypes);
193             if (StringUtils.isEmpty(value)) {
194                 return null;
195             }
196         }
197         if (property.isToscaFunction() && property.getToscaFunction().getType() == ToscaFunctionType.YAML) {
198             return new Yaml().load(property.getValue());
199         }
200         try {
201             ToscaMapValueConverter mapConverterInst = ToscaMapValueConverter.getInstance();
202             ToscaValueConverter innerConverter = null;
203             boolean isScalar = true;
204             ToscaPropertyType type = ToscaPropertyType.isValidType(propertyType);
205             if (type == null) {
206                 log.trace("isn't prederfined type, get from all data types");
207                 DataTypeDefinition dataTypeDefinition = dataTypes.get(propertyType);
208                 if (innerType == null) {
209                     innerType = propertyType;
210                 }
211                 if ((type = mapConverterInst.isScalarType(dataTypeDefinition)) != null) {
212                     log.trace("This is scalar type. get suitable converter for type {}", type);
213                     innerConverter = type.getValueConverter();
214                 } else {
215                     isScalar = false;
216                 }
217             } else {
218                 ToscaPropertyType typeIfScalar = ToscaPropertyType.getTypeIfScalar(type.getType());
219                 if (typeIfScalar == null) {
220                     isScalar = false;
221                 }
222                 innerConverter = type.getValueConverter();
223                 if (ToscaPropertyType.STRING == type && valueStartsWithNonJsonChar(value)) {
224                     return innerConverter.convertToToscaValue(value, innerType, dataTypes);
225                 }
226             }
227             JsonElement jsonElement = null;
228             StringReader reader = new StringReader(value);
229             JsonReader jsonReader = new JsonReader(reader);
230             jsonReader.setLenient(true);
231             jsonElement = JsonParser.parseReader(jsonReader);
232             if (value.equals("")) {
233                 return value;
234             }
235             if (jsonElement.isJsonPrimitive() && isScalar) {
236                 log.trace("It's well defined type. convert it");
237                 ToscaValueConverter converter = type.getValueConverter();
238                 return converter.convertToToscaValue(value, innerType, dataTypes);
239             }
240             log.trace("It's data type or inputs in primitive type. convert as map");
241             if (jsonElement.isJsonObject()) {
242                 JsonObject jsonObj = jsonElement.getAsJsonObject();
243                 // check if value is a get_input function
244                 if (jsonObj.entrySet().size() == 1 && jsonObj.has(ToscaFunctions.GET_INPUT.getFunctionName())) {
245                     Object obj = mapConverterInst.handleComplexJsonValue(jsonElement);
246                     log.debug("It's get_input function. obj={}", obj);
247                     return obj;
248                 }
249             }
250             Object convertedValue;
251             if (innerConverter != null && (ToscaPropertyType.MAP == type || ToscaPropertyType.LIST == type)) {
252                 convertedValue = innerConverter.convertToToscaValue(value, innerType, dataTypes);
253             } else if (isScalar) {
254                 // complex json for scalar type
255                 convertedValue = mapConverterInst.handleComplexJsonValue(jsonElement);
256             } else if (innerConverter != null) {
257                 convertedValue = innerConverter.convertToToscaValue(value, innerType, dataTypes);
258             } else {
259                 convertedValue = mapConverterInst
260                     .convertDataTypeToToscaObject(innerType, dataTypes, innerConverter, isScalar, jsonElement, preserveEmptyValue);
261             }
262             return convertedValue;
263         
264         } catch (JsonParseException e) {
265             log.trace("{} not parsable as JSON. Convert as YAML instead", value);
266             return  new Yaml().load(value);
267         } catch (Exception e) {
268             log.debug("convertToToscaValue failed to parse json value :", e);
269             return null;
270         }
271     }
272
273     private boolean valueStartsWithNonJsonChar(String value) {
274         return value.startsWith("/") || value.startsWith(":");
275     }
276
277     public void convertAndAddValue(Map<String, DataTypeDefinition> dataTypes, Map<String, Object> props, PropertyDataDefinition prop,
278                                    Supplier<String> supplier) {
279         Object convertedValue = convertValue(dataTypes, prop, supplier);
280         if (!ToscaValueBaseConverter.isEmptyObjectValue(convertedValue)) {
281             props.put(prop.getName(), convertedValue);
282         }
283     }
284
285     private <T extends PropertyDataDefinition> Object convertValue(Map<String, DataTypeDefinition> dataTypes, T input, Supplier<String> supplier) {
286         return convertToToscaObject(input, supplier.get(), dataTypes, false);
287     }
288
289     public enum PropertyType {CAPABILITY, INPUT, PROPERTY}
290 }