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;
83 public class PropertyConvertor {
85 private static final Logger log = Logger.getLogger(PropertyConvertor.class);
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();
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));
98 if (!properties.isEmpty()) {
99 toscaNodeType.setProperties(properties);
103 return Either.left(toscaNodeType);
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);
117 String defaultValue = property.getDefaultValue();
118 if (Objects.isNull(defaultValue)) {
119 defaultValue = property.getValue();
121 Object convertedObj = convertToToscaObject(property, defaultValue, dataTypes, false);
122 if (convertedObj != null) {
123 prop.setDefaultp(convertedObj);
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());
131 prop.setMetadata(property.getMetadata());
133 List<ToscaPropertyConstraint> constraints = new ArrayList<>();
134 if (CollectionUtils.isNotEmpty(property.getConstraints())) {
135 constraints = convertConstraints(property.getConstraints());
136 prop.setConstraints(constraints);
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()));
147 if (constraint instanceof GreaterThanConstraint) {
148 convertedConstraints.add(new ToscaPropertyConstraintGreaterThan(((GreaterThanConstraint) constraint).getGreaterThan()));
150 if (constraint instanceof GreaterOrEqualConstraint) {
151 convertedConstraints.add(new ToscaPropertyConstraintGreaterOrEqual(((GreaterOrEqualConstraint) constraint).getGreaterOrEqual()));
153 if (constraint instanceof LessThanConstraint) {
154 convertedConstraints.add(new ToscaPropertyConstraintLessThan(((LessThanConstraint) constraint).getLessThan()));
156 if (constraint instanceof LessOrEqualConstraint) {
157 convertedConstraints.add(new ToscaPropertyConstraintLessOrEqual(((LessOrEqualConstraint) constraint).getLessOrEqual()));
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));
166 if (constraint instanceof ValidValuesConstraint) {
167 List validValues = ((ValidValuesConstraint) constraint).getValidValues();
168 convertedConstraints.add(new ToscaPropertyConstraintValidValues(validValues));
170 if (constraint instanceof LengthConstraint) {
171 convertedConstraints.add(new ToscaPropertyConstraintLength(((LengthConstraint) constraint).getLength()));
173 if (constraint instanceof MinLengthConstraint) {
174 convertedConstraints.add(new ToscaPropertyConstraintMinLength(((MinLengthConstraint) constraint).getMinLength()));
176 if (constraint instanceof MaxLengthConstraint) {
177 convertedConstraints.add(new ToscaPropertyConstraintMaxLength(((MaxLengthConstraint) constraint).getMaxLength()));
179 if (constraint instanceof PatternConstraint) {
180 convertedConstraints.add(new ToscaPropertyConstraintPattern(((PatternConstraint) constraint).getPattern()));
183 return convertedConstraints;
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)) {
197 if (property.isToscaFunction() && property.getToscaFunction().getType() == ToscaFunctionType.YAML) {
198 return new Yaml().load(property.getValue());
201 ToscaMapValueConverter mapConverterInst = ToscaMapValueConverter.getInstance();
202 ToscaValueConverter innerConverter = null;
203 boolean isScalar = true;
204 ToscaPropertyType type = ToscaPropertyType.isValidType(propertyType);
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;
211 if ((type = mapConverterInst.isScalarType(dataTypeDefinition)) != null) {
212 log.trace("This is scalar type. get suitable converter for type {}", type);
213 innerConverter = type.getValueConverter();
218 ToscaPropertyType typeIfScalar = ToscaPropertyType.getTypeIfScalar(type.getType());
219 if (typeIfScalar == null) {
222 innerConverter = type.getValueConverter();
223 if (ToscaPropertyType.STRING == type && valueStartsWithNonJsonChar(value)) {
224 return innerConverter.convertToToscaValue(value, innerType, dataTypes);
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("")) {
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);
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);
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);
259 convertedValue = mapConverterInst
260 .convertDataTypeToToscaObject(innerType, dataTypes, innerConverter, isScalar, jsonElement, preserveEmptyValue);
262 return convertedValue;
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);
273 private boolean valueStartsWithNonJsonChar(String value) {
274 return value.startsWith("/") || value.startsWith(":");
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);
285 private <T extends PropertyDataDefinition> Object convertValue(Map<String, DataTypeDefinition> dataTypes, T input, Supplier<String> supplier) {
286 return convertToToscaObject(input, supplier.get(), dataTypes, false);
289 public enum PropertyType {CAPABILITY, INPUT, PROPERTY}