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