re base code
[sdc.git] / catalog-model / src / main / java / org / openecomp / sdc / be / model / tosca / converters / ToscaMapValueConverter.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.model.tosca.converters;
22
23 import com.google.gson.*;
24 import com.google.gson.stream.JsonReader;
25 import org.openecomp.sdc.be.config.BeEcompErrorManager;
26 import org.openecomp.sdc.be.model.DataTypeDefinition;
27 import org.openecomp.sdc.be.model.PropertyDefinition;
28 import org.openecomp.sdc.be.model.tosca.ToscaPropertyType;
29 import org.openecomp.sdc.common.log.wrappers.Logger;
30
31 import java.io.StringReader;
32 import java.util.*;
33 import java.util.Map.Entry;
34
35 public class ToscaMapValueConverter extends ToscaValueBaseConverter implements ToscaValueConverter {
36     private static ToscaMapValueConverter mapConverter = new ToscaMapValueConverter();
37
38     private JsonParser jsonParser = new JsonParser();
39     private static final Logger log = Logger.getLogger(ToscaMapValueConverter.class.getName());
40
41     public static ToscaMapValueConverter getInstance() {
42         return mapConverter;
43     }
44
45     private ToscaMapValueConverter() {
46
47     }
48
49     @Override
50     public Object convertToToscaValue(String value, String innerType, Map<String, DataTypeDefinition> dataTypes) {
51         if (value == null) {
52             return value;
53         }
54         try {
55             ToscaPropertyType innerToscaType = ToscaPropertyType.isValidType(innerType);
56             ToscaValueConverter innerConverter = null;
57             boolean isScalar = true;
58             List<PropertyDefinition> allPropertiesRecursive = new ArrayList<>();
59             if (innerToscaType != null) {
60                 innerConverter = innerToscaType.getValueConverter();
61             } else {
62
63                 DataTypeDefinition dataTypeDefinition = dataTypes.get(innerType);
64                 if (dataTypeDefinition != null) {
65                     ToscaPropertyType toscaPropertyType = null;
66                     if ((toscaPropertyType = isScalarType(dataTypeDefinition)) != null) {
67                         innerConverter = toscaPropertyType.getValueConverter();
68                     } else {
69                         isScalar = false;
70                         allPropertiesRecursive.addAll(dataTypeDefinition.getProperties());
71                         DataTypeDefinition derivedFrom = dataTypeDefinition.getDerivedFrom();
72                         while ( !derivedFrom.getName().equals("tosca.datatypes.Root") ){
73                             allPropertiesRecursive.addAll(derivedFrom.getProperties());
74                             derivedFrom = derivedFrom.getDerivedFrom();
75                         }
76                     }
77                 } else {
78                     log.debug("inner Tosca Type is null");
79                     return value;
80                 }
81
82             }
83             JsonElement jsonElement = null;
84             try {
85                 StringReader reader = new StringReader(value);
86                 JsonReader jsonReader = new JsonReader(reader);
87                 jsonReader.setLenient(true);
88
89                 jsonElement = jsonParser.parse(jsonReader);
90
91             } catch (JsonSyntaxException e) {
92                 log.debug("convertToToscaValue failed to parse json value :", e);
93                 return null;
94             }
95             if (jsonElement == null || jsonElement.isJsonNull()) {
96                 log.debug("convertToToscaValue json element is null");
97                 return null;
98             }
99             JsonObject asJsonObject = jsonElement.getAsJsonObject();
100             Set<Entry<String, JsonElement>> entrySet = asJsonObject.entrySet();
101
102             Map<String, Object> toscaMap = new HashMap<>();
103             final boolean isScalarF = isScalar;
104             final ToscaValueConverter innerConverterFinal = innerConverter;
105             entrySet.forEach(e -> {
106                 convertEntry(innerType, dataTypes, allPropertiesRecursive, toscaMap, isScalarF, innerConverterFinal, e);
107             });
108             return toscaMap;
109         } catch (JsonParseException e) {
110             log.debug("Failed to parse json : {}", value, e);
111             BeEcompErrorManager.getInstance().logBeInvalidJsonInput("List Converter");
112             return null;
113         }
114     }
115
116     private void convertEntry(String innerType, Map<String, DataTypeDefinition> dataTypes, List<PropertyDefinition> allPropertiesRecursive, Map<String, Object> toscaMap, final boolean isScalarF, final ToscaValueConverter innerConverterFinal,
117             Entry<String, JsonElement> e) {
118         log.debug("try convert element {}", e.getValue());
119         boolean scalar = false;
120         String propType = null;
121         ToscaValueConverter innerConverterProp = innerConverterFinal;
122         if ( isScalarF ){
123             scalar = isScalarF;
124             propType = innerType;
125         }else{
126             for ( PropertyDefinition pd : allPropertiesRecursive ){
127                 if ( pd.getName().equals(e.getKey()) ){
128                     propType = pd.getType();
129                     DataTypeDefinition pdDataType = dataTypes.get(propType);
130                     ToscaPropertyType toscaPropType = isScalarType(pdDataType);
131                     if ( toscaPropType == null ){
132                         scalar = false;
133                     }else{
134                         scalar = true;
135                         propType = toscaPropType.getType();
136                         innerConverterProp = toscaPropType.getValueConverter();
137                     }
138                     break;
139                 }
140             }
141         }
142         Object convertedValue = convertDataTypeToToscaObject(propType, dataTypes, innerConverterProp, scalar, e.getValue(), false);
143         toscaMap.put(e.getKey(), convertedValue);
144     }
145
146     public Object convertDataTypeToToscaObject(String innerType, Map<String, DataTypeDefinition> dataTypes, ToscaValueConverter innerConverter, final boolean isScalarF, JsonElement entryValue, boolean preserveEmptyValue) {
147         Object convertedValue = null;
148         if (isScalarF && entryValue.isJsonPrimitive()) {
149             log.debug("try convert scalar value {}", entryValue.getAsString());
150             if (entryValue.getAsString() == null) {
151                 convertedValue = null;
152             } else {
153                 convertedValue = innerConverter.convertToToscaValue(entryValue.getAsString(), innerType, dataTypes);
154             }
155         } else {
156             if ( entryValue.isJsonPrimitive() ){
157                 return handleComplexJsonValue(entryValue);
158             }
159
160             // ticket 228696523 created   / DE272734 / Bug 154492 Fix
161             if(entryValue instanceof JsonArray) {
162                 ArrayList<Object> toscaObjectPresentationArray = new ArrayList<>();
163                 JsonArray jsonArray = entryValue.getAsJsonArray();
164
165                 for (JsonElement jsonElement : jsonArray) {
166                     Object convertedDataTypeToToscaMap = convertDataTypeToToscaMap(innerType, dataTypes, isScalarF, jsonElement, preserveEmptyValue);
167                     toscaObjectPresentationArray.add(convertedDataTypeToToscaMap);
168                 }
169                 convertedValue = toscaObjectPresentationArray;
170             } else {
171                 convertedValue = convertDataTypeToToscaMap(innerType, dataTypes, isScalarF, entryValue, preserveEmptyValue);
172             }
173         }
174         return convertedValue;
175     }
176
177     private Object convertDataTypeToToscaMap(String innerType, Map<String, DataTypeDefinition> dataTypes,
178             final boolean isScalarF, JsonElement entryValue, boolean preserveEmptyValue) {
179         Object convertedValue;
180         if (entryValue.isJsonPrimitive()) {
181             return json2JavaPrimitive(entryValue.getAsJsonPrimitive());
182         }
183         JsonObject asJsonObjectIn = entryValue.getAsJsonObject();
184
185         DataTypePropertyConverter.getInstance().mergeDataTypeDefaultValuesWithPropertyValue(asJsonObjectIn, innerType, dataTypes);
186         Map<String, Object> toscaObjectPresentation = new HashMap<>();
187         Set<Entry<String, JsonElement>> entrySetIn = asJsonObjectIn.entrySet();
188
189         for (Entry<String, JsonElement> entry : entrySetIn) {
190             String propName = entry.getKey();
191
192             JsonElement elementValue = entry.getValue();
193             Object convValue;
194             if (!isScalarF) {
195                 DataTypeDefinition dataTypeDefinition = dataTypes.get(innerType);
196                 Map<String, PropertyDefinition> allProperties = getAllProperties(dataTypeDefinition);
197                 PropertyDefinition propertyDefinition = allProperties.get(propName);
198                 if (propertyDefinition == null) {
199                     log.trace("The property {} was not found under data type . Parse as map", propName);
200                     if (elementValue.isJsonPrimitive()) {
201                         convValue = elementValue.getAsString();
202                     } else {
203                         convValue = handleComplexJsonValue(elementValue);
204                     }
205                 } else {
206                     String type = propertyDefinition.getType();
207                     ToscaPropertyType propertyType = ToscaPropertyType.isValidType(type);
208                     if (propertyType != null) {
209                         if (elementValue.isJsonPrimitive()) {
210                             ToscaValueConverter valueConverter = propertyType.getValueConverter();
211                             convValue = valueConverter.convertToToscaValue(elementValue.getAsString(), type, dataTypes);
212                         } else {
213                             if (ToscaPropertyType.MAP.equals(type) || ToscaPropertyType.LIST.equals(propertyType)) {
214                                 ToscaValueConverter valueConverter = propertyType.getValueConverter();
215                                 String json = gson.toJson(elementValue);
216                                 String innerTypeRecursive = propertyDefinition.getSchema().getProperty().getType();
217                                 convValue = valueConverter.convertToToscaValue(json, innerTypeRecursive, dataTypes);
218                             } else {
219                                 convValue = handleComplexJsonValue(elementValue);
220                             }
221                         }
222                     } else {
223                         convValue = convertToToscaValue(elementValue.toString(), type, dataTypes);
224                     }
225                 }
226             } else {
227                 if (elementValue.isJsonPrimitive()) {
228                     convValue = json2JavaPrimitive(elementValue.getAsJsonPrimitive());
229                 } else {
230                     convValue = handleComplexJsonValue(elementValue);
231                 }
232             }
233             if(preserveEmptyValue || !isEmptyObjectValue(convValue)){
234                 toscaObjectPresentation.put(propName, convValue);
235             }
236         }
237         convertedValue = toscaObjectPresentation;
238         return convertedValue;
239     }
240
241 }