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