aboutsummaryrefslogtreecommitdiffstats
path: root/catalog-be/src/main/java/org/openecomp/sdc/be/tosca/PropertyConvertor.java
blob: d1cd4952221c4e3756c321c82d8ff2a594c18f9e (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
/*-
 * ============LICENSE_START=======================================================
 * SDC
 * ================================================================================
 * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved.
 * ================================================================================
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 * ============LICENSE_END=========================================================
 */
package org.openecomp.sdc.be.tosca;

import com.google.gson.JsonElement;
import com.google.gson.JsonObject;
import com.google.gson.JsonParseException;
import com.google.gson.JsonParser;
import com.google.gson.stream.JsonReader;
import fj.data.Either;
import java.io.StringReader;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.function.Supplier;
import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.lang3.StringUtils;
import org.openecomp.sdc.be.datatypes.elements.PropertyDataDefinition;
import org.openecomp.sdc.be.datatypes.elements.SchemaDefinition;
import org.openecomp.sdc.be.datatypes.elements.ToscaFunctionType;
import org.openecomp.sdc.be.model.Component;
import org.openecomp.sdc.be.model.DataTypeDefinition;
import org.openecomp.sdc.be.model.PropertyConstraint;
import org.openecomp.sdc.be.model.PropertyDefinition;
import org.openecomp.sdc.be.model.Resource;
import org.openecomp.sdc.be.model.tosca.ToscaPropertyType;
import org.openecomp.sdc.be.model.tosca.ToscaType;
import org.openecomp.sdc.be.model.tosca.constraints.EqualConstraint;
import org.openecomp.sdc.be.model.tosca.constraints.GreaterOrEqualConstraint;
import org.openecomp.sdc.be.model.tosca.constraints.GreaterThanConstraint;
import org.openecomp.sdc.be.model.tosca.constraints.InRangeConstraint;
import org.openecomp.sdc.be.model.tosca.constraints.LengthConstraint;
import org.openecomp.sdc.be.model.tosca.constraints.LessOrEqualConstraint;
import org.openecomp.sdc.be.model.tosca.constraints.LessThanConstraint;
import org.openecomp.sdc.be.model.tosca.constraints.MaxLengthConstraint;
import org.openecomp.sdc.be.model.tosca.constraints.MinLengthConstraint;
import org.openecomp.sdc.be.model.tosca.constraints.PatternConstraint;
import org.openecomp.sdc.be.model.tosca.constraints.ValidValuesConstraint;
import org.openecomp.sdc.be.model.tosca.constraints.exception.ConstraintValueDoNotMatchPropertyTypeException;
import org.openecomp.sdc.be.model.tosca.converters.DataTypePropertyConverter;
import org.openecomp.sdc.be.model.tosca.converters.ToscaMapValueConverter;
import org.openecomp.sdc.be.model.tosca.converters.ToscaValueBaseConverter;
import org.openecomp.sdc.be.model.tosca.converters.ToscaValueConverter;
import org.openecomp.sdc.be.tosca.model.ToscaNodeType;
import org.openecomp.sdc.be.tosca.model.ToscaProperty;
import org.openecomp.sdc.be.tosca.model.ToscaPropertyConstraint;
import org.openecomp.sdc.be.tosca.model.ToscaPropertyConstraintEqual;
import org.openecomp.sdc.be.tosca.model.ToscaPropertyConstraintGreaterOrEqual;
import org.openecomp.sdc.be.tosca.model.ToscaPropertyConstraintGreaterThan;
import org.openecomp.sdc.be.tosca.model.ToscaPropertyConstraintInRange;
import org.openecomp.sdc.be.tosca.model.ToscaPropertyConstraintLength;
import org.openecomp.sdc.be.tosca.model.ToscaPropertyConstraintLessOrEqual;
import org.openecomp.sdc.be.tosca.model.ToscaPropertyConstraintLessThan;
import org.openecomp.sdc.be.tosca.model.ToscaPropertyConstraintMaxLength;
import org.openecomp.sdc.be.tosca.model.ToscaPropertyConstraintMinLength;
import org.openecomp.sdc.be.tosca.model.ToscaPropertyConstraintPattern;
import org.openecomp.sdc.be.tosca.model.ToscaPropertyConstraintValidValues;
import org.openecomp.sdc.be.tosca.model.ToscaSchemaDefinition;
import org.openecomp.sdc.common.log.wrappers.Logger;
import org.openecomp.sdc.tosca.datatypes.ToscaFunctions;
import org.springframework.stereotype.Service;
import org.yaml.snakeyaml.Yaml;

@Service
public class PropertyConvertor {

    private static final Logger log = Logger.getLogger(PropertyConvertor.class);

    public Either<ToscaNodeType, ToscaError> convertProperties(Component component, ToscaNodeType toscaNodeType,
                                                               Map<String, DataTypeDefinition> dataTypes) {
        if (component instanceof Resource) {
            Resource resource = (Resource) component;
            List<PropertyDefinition> props = resource.getProperties();
            if (props != null) {
                Map<String, ToscaProperty> properties = new HashMap<>();
                // take only the properties of this resource
                props.stream().filter(p -> p.getOwnerId() == null || p.getOwnerId().equals(component.getUniqueId())).forEach(property ->
                    properties.put(property.getName(), convertProperty(dataTypes, property, PropertyType.PROPERTY))
                );
                if (!properties.isEmpty()) {
                    toscaNodeType.setProperties(properties);
                }
            }
        }
        return Either.left(toscaNodeType);
    }

    public ToscaProperty convertProperty(Map<String, DataTypeDefinition> dataTypes, PropertyDefinition property, PropertyType propertyType) {
        ToscaProperty prop = new ToscaProperty();
        log.trace("try to convert property {} from type {} with default value [{}]", property.getName(), property.getType(),
            property.getDefaultValue());
        SchemaDefinition schema = property.getSchema();
        if (schema != null && schema.getProperty() != null && schema.getProperty().getType() != null && !schema.getProperty().getType().isEmpty()) {
            final ToscaSchemaDefinition toscaSchemaDefinition = new ToscaSchemaDefinition();
            toscaSchemaDefinition.setType(schema.getProperty().getType());
            toscaSchemaDefinition.setDescription(schema.getProperty().getDescription());
            prop.setEntry_schema(toscaSchemaDefinition);
        }
        String defaultValue = property.getDefaultValue();
        if (Objects.isNull(defaultValue)) {
            defaultValue = property.getValue();
        }
        Object convertedObj = convertToToscaObject(property, defaultValue, dataTypes, false);
        if (convertedObj != null) {
            prop.setDefaultp(convertedObj);
        }
        prop.setType(property.getType());
        prop.setDescription(property.getDescription());
        prop.setRequired(property.isRequired());
        if (propertyType.equals(PropertyType.CAPABILITY)) {
            prop.setStatus(property.getStatus());
        }
        prop.setMetadata(property.getMetadata());

        if (CollectionUtils.isNotEmpty(property.getConstraints())) {
            try {
                prop.setConstraints(convertConstraints(property.getConstraints(), property.getType(), property.getSchemaType()));
            } catch (ConstraintValueDoNotMatchPropertyTypeException e) {
                log.error(e.getMessage());
            }
        }
        return prop;
    }

    private List<ToscaPropertyConstraint> convertConstraints(List<PropertyConstraint> constraints, String propertyType, String schemaType)
        throws ConstraintValueDoNotMatchPropertyTypeException {
        List<ToscaPropertyConstraint> convertedConstraints = new ArrayList<>();
        for (PropertyConstraint constraint : constraints) {
            if (constraint instanceof EqualConstraint) {
                EqualConstraint equalConstraint = ((EqualConstraint) constraint);

                if (doesTypeNeedConvertingToIntOrFloat(propertyType)) {
                    equalConstraint.changeConstraintValueTypeTo(propertyType);
                }

                ToscaPropertyConstraintEqual prop = new ToscaPropertyConstraintEqual(equalConstraint.getEqual());
                convertedConstraints.add(prop);
            }
            if (constraint instanceof GreaterThanConstraint) {
                GreaterThanConstraint greaterThanConstraint = ((GreaterThanConstraint) constraint);

                if (doesTypeNeedConvertingToIntOrFloat(propertyType)) {
                    greaterThanConstraint.changeConstraintValueTypeTo(propertyType);
                }

                ToscaPropertyConstraintGreaterThan prop = new ToscaPropertyConstraintGreaterThan(greaterThanConstraint.getGreaterThan());
                convertedConstraints.add(prop);
            }
            if (constraint instanceof GreaterOrEqualConstraint) {
                GreaterOrEqualConstraint greaterOrEqualConstraint = ((GreaterOrEqualConstraint) constraint);

                if (doesTypeNeedConvertingToIntOrFloat(propertyType)) {
                    greaterOrEqualConstraint.changeConstraintValueTypeTo(propertyType);
                }

                ToscaPropertyConstraintGreaterOrEqual prop = new ToscaPropertyConstraintGreaterOrEqual(greaterOrEqualConstraint.getGreaterOrEqual());
                convertedConstraints.add(prop);
            }
            if (constraint instanceof LessThanConstraint) {
                LessThanConstraint lessThanConstraint = ((LessThanConstraint) constraint);

                if (doesTypeNeedConvertingToIntOrFloat(propertyType)) {
                    lessThanConstraint.changeConstraintValueTypeTo(propertyType);
                }

                ToscaPropertyConstraintLessThan prop = new ToscaPropertyConstraintLessThan(lessThanConstraint.getLessThan());
                convertedConstraints.add(prop);
            }
            if (constraint instanceof LessOrEqualConstraint) {
                LessOrEqualConstraint lessOrEqualConstraint = ((LessOrEqualConstraint) constraint);

                if (doesTypeNeedConvertingToIntOrFloat(propertyType)) {
                    lessOrEqualConstraint.changeConstraintValueTypeTo(propertyType);
                }

                ToscaPropertyConstraintLessOrEqual prop = new ToscaPropertyConstraintLessOrEqual(lessOrEqualConstraint.getLessOrEqual());
                convertedConstraints.add(prop);
            }
            if (constraint instanceof InRangeConstraint) {
                InRangeConstraint inRangeConstraint = (InRangeConstraint) constraint;

                if (doesTypeNeedConvertingToIntOrFloat(propertyType)) {
                    inRangeConstraint.changeConstraintValueTypeTo(propertyType);
                }

                convertedConstraints.add(new ToscaPropertyConstraintInRange(inRangeConstraint.getInRange()));
            }
            if (constraint instanceof ValidValuesConstraint) {
                ValidValuesConstraint validValues = ((ValidValuesConstraint) constraint);

                if (isTypeMapOrList(propertyType) && doesTypeNeedConvertingToIntOrFloat(schemaType)) {
                    validValues.changeConstraintValueTypeTo(schemaType);
                } else if (doesTypeNeedConvertingToIntOrFloat(propertyType)) {
                    validValues.changeConstraintValueTypeTo(propertyType);
                }

                List prop = validValues.getValidValues();
                convertedConstraints.add(new ToscaPropertyConstraintValidValues(prop));
            }
            if (constraint instanceof LengthConstraint) {
                convertedConstraints.add(new ToscaPropertyConstraintLength(((LengthConstraint) constraint).getLength()));
            }
            if (constraint instanceof MinLengthConstraint) {
                convertedConstraints.add(new ToscaPropertyConstraintMinLength(((MinLengthConstraint) constraint).getMinLength()));
            }
            if (constraint instanceof MaxLengthConstraint) {
                convertedConstraints.add(new ToscaPropertyConstraintMaxLength(((MaxLengthConstraint) constraint).getMaxLength()));
            }
            if (constraint instanceof PatternConstraint) {
                convertedConstraints.add(new ToscaPropertyConstraintPattern(((PatternConstraint) constraint).getPattern()));
            }
        }
        return convertedConstraints;
    }

    private boolean doesTypeNeedConvertingToIntOrFloat(String propertyType) {
        return ToscaType.INTEGER.getType().equals(propertyType) || ToscaType.FLOAT.getType().equals(propertyType);
    }

    private boolean isTypeMapOrList (String type) {
        return ToscaType.MAP.getType().equals(type) || ToscaType.LIST.getType().equals(type);
    }

    public Object convertToToscaObject(PropertyDataDefinition property, String value, Map<String, DataTypeDefinition> dataTypes,
                                       boolean preserveEmptyValue) {
        String propertyType = property.getType();
        String innerType = property.getSchemaType();
        log.trace("try to convert propertyType {} , value [{}], innerType {}", propertyType, value, innerType);
        if (StringUtils.isEmpty(value)) {
            value = DataTypePropertyConverter.getInstance().getDataTypePropertiesDefaultValuesRec(propertyType, dataTypes);
            if (StringUtils.isEmpty(value)) {
                return null;
            }
        }
        if (property.isToscaFunction() && property.getToscaFunction().getType() == ToscaFunctionType.YAML) {
            return new Yaml().load(property.getValue());
        }
        try {
            ToscaMapValueConverter mapConverterInst = ToscaMapValueConverter.getInstance();
            ToscaValueConverter innerConverter = null;
            boolean isScalar = true;
            ToscaPropertyType type = ToscaPropertyType.isValidType(propertyType);
            if (type == null) {
                log.trace("isn't prederfined type, get from all data types");
                DataTypeDefinition dataTypeDefinition = dataTypes.get(propertyType);
                if (innerType == null) {
                    innerType = propertyType;
                }
                if ((type = mapConverterInst.isScalarType(dataTypeDefinition)) != null) {
                    log.trace("This is scalar type. get suitable converter for type {}", type);
                    innerConverter = type.getValueConverter();
                } else {
                    isScalar = false;
                }
            } else {
                ToscaPropertyType typeIfScalar = ToscaPropertyType.getTypeIfScalar(type.getType());
                if (typeIfScalar == null) {
                    isScalar = false;
                }
                innerConverter = type.getValueConverter();
                if (ToscaPropertyType.STRING == type && valueStartsWithNonJsonChar(value)) {
                    return innerConverter.convertToToscaValue(value, innerType, dataTypes);
                }
            }
            JsonElement jsonElement = null;
            StringReader reader = new StringReader(value);
            JsonReader jsonReader = new JsonReader(reader);
            jsonReader.setLenient(true);
            jsonElement = JsonParser.parseReader(jsonReader);
            if (value.equals("")) {
                return value;
            }
            if (jsonElement.isJsonPrimitive() && isScalar) {
                log.trace("It's well defined type. convert it");
                ToscaValueConverter converter = type.getValueConverter();
                return converter.convertToToscaValue(value, innerType, dataTypes);
            }
            log.trace("It's data type or inputs in primitive type. convert as map");
            if (jsonElement.isJsonObject()) {
                JsonObject jsonObj = jsonElement.getAsJsonObject();
                // check if value is a get_input function
                if (jsonObj.entrySet().size() == 1 && jsonObj.has(ToscaFunctions.GET_INPUT.getFunctionName())) {
                    Object obj = mapConverterInst.handleComplexJsonValue(jsonElement);
                    log.debug("It's get_input function. obj={}", obj);
                    return obj;
                }
            }
            Object convertedValue;
            if (innerConverter != null && (ToscaPropertyType.MAP == type || ToscaPropertyType.LIST == type)) {
                convertedValue = innerConverter.convertToToscaValue(value, innerType, dataTypes);
            } else if (isScalar) {
                // complex json for scalar type
                convertedValue = mapConverterInst.handleComplexJsonValue(jsonElement);
            } else if (innerConverter != null) {
                convertedValue = innerConverter.convertToToscaValue(value, innerType, dataTypes);
            } else {
                convertedValue = mapConverterInst
                    .convertDataTypeToToscaObject(innerType, dataTypes, innerConverter, isScalar, jsonElement, preserveEmptyValue);
            }
            return convertedValue;

        } catch (JsonParseException e) {
            log.trace("{} not parsable as JSON. Convert as YAML instead", value);
            return new Yaml().load(value);
        } catch (Exception e) {
            log.debug("convertToToscaValue failed to parse json value :", e);
            return null;
        }
    }

    private boolean valueStartsWithNonJsonChar(String value) {
        return value.startsWith("/") || value.startsWith(":");
    }

    public void convertAndAddValue(Map<String, DataTypeDefinition> dataTypes, Map<String, Object> props, PropertyDataDefinition prop,
                                   Supplier<String> supplier) {
        Object convertedValue = convertValue(dataTypes, prop, supplier);
        if (!ToscaValueBaseConverter.isEmptyObjectValue(convertedValue)) {
            props.put(prop.getName(), convertedValue);
        }
    }

    private <T extends PropertyDataDefinition> Object convertValue(Map<String, DataTypeDefinition> dataTypes, T input, Supplier<String> supplier) {
        return convertToToscaObject(input, supplier.get(), dataTypes, false);
    }

    public enum PropertyType {CAPABILITY, INPUT, PROPERTY}
}