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