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