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