Reformat catalog-be
[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.JsonParser;
25 import com.google.gson.stream.JsonReader;
26 import fj.data.Either;
27 import java.io.StringReader;
28 import java.util.HashMap;
29 import java.util.List;
30 import java.util.Map;
31 import java.util.Objects;
32 import java.util.function.Supplier;
33 import org.apache.commons.lang3.StringUtils;
34 import org.openecomp.sdc.be.datatypes.elements.PropertyDataDefinition;
35 import org.openecomp.sdc.be.datatypes.elements.SchemaDefinition;
36 import org.openecomp.sdc.be.model.Component;
37 import org.openecomp.sdc.be.model.DataTypeDefinition;
38 import org.openecomp.sdc.be.model.PropertyDefinition;
39 import org.openecomp.sdc.be.model.Resource;
40 import org.openecomp.sdc.be.model.tosca.ToscaPropertyType;
41 import org.openecomp.sdc.be.model.tosca.converters.DataTypePropertyConverter;
42 import org.openecomp.sdc.be.model.tosca.converters.ToscaMapValueConverter;
43 import org.openecomp.sdc.be.model.tosca.converters.ToscaValueBaseConverter;
44 import org.openecomp.sdc.be.model.tosca.converters.ToscaValueConverter;
45 import org.openecomp.sdc.be.tosca.model.ToscaNodeType;
46 import org.openecomp.sdc.be.tosca.model.ToscaProperty;
47 import org.openecomp.sdc.be.tosca.model.ToscaSchemaDefinition;
48 import org.openecomp.sdc.common.log.wrappers.Logger;
49 import org.openecomp.sdc.tosca.datatypes.ToscaFunctions;
50 import org.springframework.stereotype.Service;
51
52 @Service
53 public class PropertyConvertor {
54
55     private static final Logger log = Logger.getLogger(PropertyConvertor.class);
56     private JsonParser jsonParser = new JsonParser();
57
58     public Either<ToscaNodeType, ToscaError> convertProperties(Component component, ToscaNodeType toscaNodeType,
59                                                                Map<String, DataTypeDefinition> dataTypes) {
60         if (component instanceof Resource) {
61             Resource resource = (Resource) component;
62             List<PropertyDefinition> props = resource.getProperties();
63             if (props != null) {
64                 Map<String, ToscaProperty> properties = new HashMap<>();
65                 // take only the properties of this resource
66                 props.stream().filter(p -> p.getOwnerId() == null || p.getOwnerId().equals(component.getUniqueId())).forEach(property -> {
67                     properties.put(property.getName(), convertProperty(dataTypes, property, PropertyType.PROPERTY));
68                 });
69                 if (!properties.isEmpty()) {
70                     toscaNodeType.setProperties(properties);
71                 }
72             }
73         }
74         return Either.left(toscaNodeType);
75     }
76
77     public ToscaProperty convertProperty(Map<String, DataTypeDefinition> dataTypes, PropertyDefinition property, PropertyType propertyType) {
78         ToscaProperty prop = new ToscaProperty();
79         log.trace("try to convert property {} from type {} with default value [{}]", property.getName(), property.getType(),
80             property.getDefaultValue());
81         SchemaDefinition schema = property.getSchema();
82         if (schema != null && schema.getProperty() != null && schema.getProperty().getType() != null && !schema.getProperty().getType().isEmpty()) {
83             final ToscaSchemaDefinition toscaSchemaDefinition = new ToscaSchemaDefinition();
84             toscaSchemaDefinition.setType(schema.getProperty().getType());
85             toscaSchemaDefinition.setDescription(schema.getProperty().getDescription());
86             prop.setEntry_schema(toscaSchemaDefinition);
87         }
88         String defaultValue = property.getDefaultValue();
89         if (Objects.isNull(defaultValue)) {
90             defaultValue = property.getValue();
91         }
92         Object convertedObj = convertToToscaObject(property, defaultValue, dataTypes, false);
93         if (convertedObj != null) {
94             prop.setDefaultp(convertedObj);
95         }
96         prop.setType(property.getType());
97         prop.setDescription(property.getDescription());
98         prop.setRequired(property.isRequired());
99         if (propertyType.equals(PropertyType.CAPABILITY)) {
100             prop.setStatus(property.getStatus());
101         }
102         prop.setMetadata(property.getMetadata());
103         return prop;
104     }
105
106     public Object convertToToscaObject(PropertyDataDefinition property, String value, Map<String, DataTypeDefinition> dataTypes,
107                                        boolean preserveEmptyValue) {
108         String propertyType = property.getType();
109         String innerType = property.getSchemaType();
110         log.trace("try to convert propertyType {} , value [{}], innerType {}", propertyType, value, innerType);
111         if (StringUtils.isEmpty(value)) {
112             value = DataTypePropertyConverter.getInstance().getDataTypePropertiesDefaultValuesRec(propertyType, dataTypes);
113             if (StringUtils.isEmpty(value)) {
114                 return null;
115             }
116         }
117         try {
118             ToscaMapValueConverter mapConverterInst = ToscaMapValueConverter.getInstance();
119             ToscaValueConverter innerConverter = null;
120             boolean isScalar = true;
121             ToscaPropertyType type = ToscaPropertyType.isValidType(propertyType);
122             if (type == null) {
123                 log.trace("isn't prederfined type, get from all data types");
124                 DataTypeDefinition dataTypeDefinition = dataTypes.get(propertyType);
125                 if (innerType == null) {
126                     innerType = propertyType;
127                 }
128                 if ((type = mapConverterInst.isScalarType(dataTypeDefinition)) != null) {
129                     log.trace("This is scalar type. get suitable converter for type {}", type);
130                     innerConverter = type.getValueConverter();
131                 } else {
132                     isScalar = false;
133                 }
134             } else {
135                 ToscaPropertyType typeIfScalar = ToscaPropertyType.getTypeIfScalar(type.getType());
136                 if (typeIfScalar == null) {
137                     isScalar = false;
138                 }
139                 innerConverter = type.getValueConverter();
140                 if (ToscaPropertyType.STRING == type && valueStartsWithNonJsonChar(value)) {
141                     return innerConverter.convertToToscaValue(value, innerType, dataTypes);
142                 }
143             }
144             JsonElement jsonElement = null;
145             StringReader reader = new StringReader(value);
146             JsonReader jsonReader = new JsonReader(reader);
147             jsonReader.setLenient(true);
148             jsonElement = jsonParser.parse(jsonReader);
149             if (value.equals("")) {
150                 return value;
151             }
152             if (jsonElement.isJsonPrimitive() && isScalar) {
153                 log.trace("It's well defined type. convert it");
154                 ToscaValueConverter converter = type.getValueConverter();
155                 return converter.convertToToscaValue(value, innerType, dataTypes);
156             }
157             log.trace("It's data type or inputs in primitive type. convert as map");
158             if (jsonElement.isJsonObject()) {
159                 JsonObject jsonObj = jsonElement.getAsJsonObject();
160                 // check if value is a get_input function
161                 if (jsonObj.entrySet().size() == 1 && jsonObj.has(ToscaFunctions.GET_INPUT.getFunctionName())) {
162                     Object obj = mapConverterInst.handleComplexJsonValue(jsonElement);
163                     log.debug("It's get_input function. obj={}", obj);
164                     return obj;
165                 }
166             }
167             Object convertedValue;
168             if (innerConverter != null && (ToscaPropertyType.MAP == type || ToscaPropertyType.LIST == type)) {
169                 convertedValue = innerConverter.convertToToscaValue(value, innerType, dataTypes);
170             } else if (isScalar) {
171                 // complex json for scalar type
172                 convertedValue = mapConverterInst.handleComplexJsonValue(jsonElement);
173             } else if (innerConverter != null) {
174                 convertedValue = innerConverter.convertToToscaValue(value, innerType, dataTypes);
175             } else {
176                 convertedValue = mapConverterInst
177                     .convertDataTypeToToscaObject(innerType, dataTypes, innerConverter, isScalar, jsonElement, preserveEmptyValue);
178             }
179             return convertedValue;
180         } catch (Exception e) {
181             log.debug("convertToToscaValue failed to parse json value :", e);
182             return null;
183         }
184     }
185
186     private boolean valueStartsWithNonJsonChar(String value) {
187         return value.startsWith("/") || value.startsWith(":");
188     }
189
190     public void convertAndAddValue(Map<String, DataTypeDefinition> dataTypes, Map<String, Object> props, PropertyDataDefinition prop,
191                                    Supplier<String> supplier) {
192         Object convertedValue = convertValue(dataTypes, prop, supplier);
193         if (!ToscaValueBaseConverter.isEmptyObjectValue(convertedValue)) {
194             props.put(prop.getName(), convertedValue);
195         }
196     }
197
198     private <T extends PropertyDataDefinition> Object convertValue(Map<String, DataTypeDefinition> dataTypes, T input, Supplier<String> supplier) {
199         return convertToToscaObject(input, supplier.get(), dataTypes, false);
200     }
201
202     public enum PropertyType {CAPABILITY, INPUT, PROPERTY}
203 }