2 * ============LICENSE_START=======================================================
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
11 * http://www.apache.org/licenses/LICENSE-2.0
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=========================================================
20 package org.openecomp.sdc.be.tosca;
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;
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;
82 public class PropertyConvertor {
84 private static final Logger log = Logger.getLogger(PropertyConvertor.class);
86 public Either<ToscaNodeType, ToscaError> convertProperties(Component component, ToscaNodeType toscaNodeType,
87 Map<String, DataTypeDefinition> dataTypes) {
88 if (component instanceof Resource) {
89 Resource resource = (Resource) component;
90 List<PropertyDefinition> props = resource.getProperties();
92 Map<String, ToscaProperty> properties = new HashMap<>();
93 // take only the properties of this resource
94 props.stream().filter(p -> p.getOwnerId() == null || p.getOwnerId().equals(component.getUniqueId())).forEach(property ->
95 properties.put(property.getName(), convertProperty(dataTypes, property, PropertyType.PROPERTY))
97 if (!properties.isEmpty()) {
98 toscaNodeType.setProperties(properties);
102 return Either.left(toscaNodeType);
105 public ToscaProperty convertProperty(Map<String, DataTypeDefinition> dataTypes, PropertyDefinition property, PropertyType propertyType) {
106 ToscaProperty prop = new ToscaProperty();
107 log.trace("try to convert property {} from type {} with default value [{}]", property.getName(), property.getType(),
108 property.getDefaultValue());
109 SchemaDefinition schema = property.getSchema();
110 if (schema != null && schema.getProperty() != null && schema.getProperty().getType() != null && !schema.getProperty().getType().isEmpty()) {
111 final ToscaSchemaDefinition toscaSchemaDefinition = new ToscaSchemaDefinition();
112 toscaSchemaDefinition.setType(schema.getProperty().getType());
113 toscaSchemaDefinition.setDescription(schema.getProperty().getDescription());
114 prop.setEntry_schema(toscaSchemaDefinition);
116 String defaultValue = property.getDefaultValue();
117 if (Objects.isNull(defaultValue)) {
118 defaultValue = property.getValue();
120 Object convertedObj = convertToToscaObject(property, defaultValue, dataTypes, false);
121 if (convertedObj != null) {
122 prop.setDefaultp(convertedObj);
124 prop.setType(property.getType());
125 prop.setDescription(property.getDescription());
126 prop.setRequired(property.isRequired());
127 if (propertyType.equals(PropertyType.CAPABILITY)) {
128 prop.setStatus(property.getStatus());
130 prop.setMetadata(property.getMetadata());
132 if (CollectionUtils.isNotEmpty(property.getConstraints())) {
133 prop.setConstraints(convertConstraints(property.getConstraints()));
138 private List<ToscaPropertyConstraint> convertConstraints(List<PropertyConstraint> constraints) {
139 List<ToscaPropertyConstraint> convertedConstraints = new ArrayList<>();
140 for (PropertyConstraint constraint : constraints) {
141 if (constraint instanceof EqualConstraint) {
142 convertedConstraints.add(new ToscaPropertyConstraintEqual(((EqualConstraint) constraint).getEqual()));
144 if (constraint instanceof GreaterThanConstraint) {
145 convertedConstraints.add(new ToscaPropertyConstraintGreaterThan(((GreaterThanConstraint) constraint).getGreaterThan()));
147 if (constraint instanceof GreaterOrEqualConstraint) {
148 convertedConstraints.add(new ToscaPropertyConstraintGreaterOrEqual(((GreaterOrEqualConstraint) constraint).getGreaterOrEqual()));
150 if (constraint instanceof LessThanConstraint) {
151 convertedConstraints.add(new ToscaPropertyConstraintLessThan(((LessThanConstraint) constraint).getLessThan()));
153 if (constraint instanceof LessOrEqualConstraint) {
154 convertedConstraints.add(new ToscaPropertyConstraintLessOrEqual(((LessOrEqualConstraint) constraint).getLessOrEqual()));
156 if (constraint instanceof InRangeConstraint) {
157 InRangeConstraint inRangeConstraint = (InRangeConstraint) constraint;
158 List<Object> range = new ArrayList<>();
159 range.add(inRangeConstraint.getMin());
160 range.add(inRangeConstraint.getMax());
161 convertedConstraints.add(new ToscaPropertyConstraintInRange(range));
163 if (constraint instanceof ValidValuesConstraint) {
164 List validValues = ((ValidValuesConstraint) constraint).getValidValues();
165 convertedConstraints.add(new ToscaPropertyConstraintValidValues(validValues));
167 if (constraint instanceof LengthConstraint) {
168 convertedConstraints.add(new ToscaPropertyConstraintLength(((LengthConstraint) constraint).getLength()));
170 if (constraint instanceof MinLengthConstraint) {
171 convertedConstraints.add(new ToscaPropertyConstraintMinLength(((MinLengthConstraint) constraint).getMinLength()));
173 if (constraint instanceof MaxLengthConstraint) {
174 convertedConstraints.add(new ToscaPropertyConstraintMaxLength(((MaxLengthConstraint) constraint).getMaxLength()));
176 if (constraint instanceof PatternConstraint) {
177 convertedConstraints.add(new ToscaPropertyConstraintPattern(((PatternConstraint) constraint).getPattern()));
180 return convertedConstraints;
183 public Object convertToToscaObject(PropertyDataDefinition property, String value, Map<String, DataTypeDefinition> dataTypes,
184 boolean preserveEmptyValue) {
185 String propertyType = property.getType();
186 String innerType = property.getSchemaType();
187 log.trace("try to convert propertyType {} , value [{}], innerType {}", propertyType, value, innerType);
188 if (StringUtils.isEmpty(value)) {
189 value = DataTypePropertyConverter.getInstance().getDataTypePropertiesDefaultValuesRec(propertyType, dataTypes);
190 if (StringUtils.isEmpty(value)) {
194 if (property.isToscaFunction() && property.getToscaFunction().getType() == ToscaFunctionType.YAML) {
195 return new Yaml().load(property.getValue());
198 ToscaMapValueConverter mapConverterInst = ToscaMapValueConverter.getInstance();
199 ToscaValueConverter innerConverter = null;
200 boolean isScalar = true;
201 ToscaPropertyType type = ToscaPropertyType.isValidType(propertyType);
203 log.trace("isn't prederfined type, get from all data types");
204 DataTypeDefinition dataTypeDefinition = dataTypes.get(propertyType);
205 if (innerType == null) {
206 innerType = propertyType;
208 if ((type = mapConverterInst.isScalarType(dataTypeDefinition)) != null) {
209 log.trace("This is scalar type. get suitable converter for type {}", type);
210 innerConverter = type.getValueConverter();
215 ToscaPropertyType typeIfScalar = ToscaPropertyType.getTypeIfScalar(type.getType());
216 if (typeIfScalar == null) {
219 innerConverter = type.getValueConverter();
220 if (ToscaPropertyType.STRING == type && valueStartsWithNonJsonChar(value)) {
221 return innerConverter.convertToToscaValue(value, innerType, dataTypes);
224 JsonElement jsonElement = null;
225 StringReader reader = new StringReader(value);
226 JsonReader jsonReader = new JsonReader(reader);
227 jsonReader.setLenient(true);
228 jsonElement = JsonParser.parseReader(jsonReader);
229 if (value.equals("")) {
232 if (jsonElement.isJsonPrimitive() && isScalar) {
233 log.trace("It's well defined type. convert it");
234 ToscaValueConverter converter = type.getValueConverter();
235 return converter.convertToToscaValue(value, innerType, dataTypes);
237 log.trace("It's data type or inputs in primitive type. convert as map");
238 if (jsonElement.isJsonObject()) {
239 JsonObject jsonObj = jsonElement.getAsJsonObject();
240 // check if value is a get_input function
241 if (jsonObj.entrySet().size() == 1 && jsonObj.has(ToscaFunctions.GET_INPUT.getFunctionName())) {
242 Object obj = mapConverterInst.handleComplexJsonValue(jsonElement);
243 log.debug("It's get_input function. obj={}", obj);
247 Object convertedValue;
248 if (innerConverter != null && (ToscaPropertyType.MAP == type || ToscaPropertyType.LIST == type)) {
249 convertedValue = innerConverter.convertToToscaValue(value, innerType, dataTypes);
250 } else if (isScalar) {
251 // complex json for scalar type
252 convertedValue = mapConverterInst.handleComplexJsonValue(jsonElement);
253 } else if (innerConverter != null) {
254 convertedValue = innerConverter.convertToToscaValue(value, innerType, dataTypes);
256 convertedValue = mapConverterInst
257 .convertDataTypeToToscaObject(innerType, dataTypes, innerConverter, isScalar, jsonElement, preserveEmptyValue);
259 return convertedValue;
261 } catch (JsonParseException e) {
262 log.trace("{} not parsable as JSON. Convert as YAML instead", value);
263 return new Yaml().load(value);
264 } catch (Exception e) {
265 log.debug("convertToToscaValue failed to parse json value :", e);
270 private boolean valueStartsWithNonJsonChar(String value) {
271 return value.startsWith("/") || value.startsWith(":");
274 public void convertAndAddValue(Map<String, DataTypeDefinition> dataTypes, Map<String, Object> props, PropertyDataDefinition prop,
275 Supplier<String> supplier) {
276 Object convertedValue = convertValue(dataTypes, prop, supplier);
277 if (!ToscaValueBaseConverter.isEmptyObjectValue(convertedValue)) {
278 props.put(prop.getName(), convertedValue);
282 private <T extends PropertyDataDefinition> Object convertValue(Map<String, DataTypeDefinition> dataTypes, T input, Supplier<String> supplier) {
283 return convertToToscaObject(input, supplier.get(), dataTypes, false);
286 public enum PropertyType {CAPABILITY, INPUT, PROPERTY}