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