Provide index token to tosca function for nested lists
[sdc.git] / common-be / src / main / java / org / openecomp / sdc / be / datatypes / elements / ToscaFunctionJsonDeserializer.java
1 /*
2  * -
3  *  ============LICENSE_START=======================================================
4  *  Copyright (C) 2022 Nordix Foundation.
5  *  ================================================================================
6  *  Licensed under the Apache License, Version 2.0 (the "License");
7  *  you may not use this file except in compliance with the License.
8  *  You may obtain a copy of the License at
9  *
10  *       http://www.apache.org/licenses/LICENSE-2.0
11  *
12  *  Unless required by applicable law or agreed to in writing, software
13  *  distributed under the License is distributed on an "AS IS" BASIS,
14  *  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
15  *  See the License for the specific language governing permissions and
16  *  limitations under the License.
17  *
18  *  SPDX-License-Identifier: Apache-2.0
19  *  ============LICENSE_END=========================================================
20  */
21
22 package org.openecomp.sdc.be.datatypes.elements;
23
24 import com.fasterxml.jackson.core.JsonParser;
25 import com.fasterxml.jackson.databind.DeserializationContext;
26 import com.fasterxml.jackson.databind.JsonMappingException;
27 import com.fasterxml.jackson.databind.JsonNode;
28 import com.fasterxml.jackson.databind.deser.std.StdDeserializer;
29 import java.io.IOException;
30 import java.util.ArrayList;
31 import java.util.List;
32 import java.util.Optional;
33 import org.apache.commons.lang3.StringUtils;
34 import org.openecomp.sdc.be.config.Configuration;
35 import org.openecomp.sdc.be.config.ConfigurationManager;
36 import org.openecomp.sdc.be.datatypes.enums.PropertySource;
37 import org.openecomp.sdc.be.datatypes.tosca.ToscaGetFunctionType;
38 import org.slf4j.Logger;
39 import org.slf4j.LoggerFactory;
40 import org.yaml.snakeyaml.Yaml;
41
42 public class ToscaFunctionJsonDeserializer extends StdDeserializer<ToscaFunction> {
43
44     private static final Logger LOGGER = LoggerFactory.getLogger(ToscaFunctionJsonDeserializer.class);
45
46     public ToscaFunctionJsonDeserializer() {
47         this(null);
48     }
49
50     public ToscaFunctionJsonDeserializer(Class<?> vc) {
51         super(vc);
52     }
53
54     @Override
55     public ToscaFunction deserialize(final JsonParser jsonParser, final DeserializationContext context) throws IOException {
56         final JsonNode node = jsonParser.getCodec().readTree(jsonParser);
57         return deserializeToscaFunction(node, context);
58     }
59
60     private ToscaFunction deserializeToscaFunction(final JsonNode node, final DeserializationContext context) throws IOException {
61         final String functionType;
62         if (node.get("type") != null) {
63             functionType = node.get("type").asText();
64         } else if (node.get("functionType") != null) {
65             //support for legacy tosca function
66             functionType = node.get("functionType").asText();
67         } else {
68             throw context.instantiationException(ToscaFunction.class, "Attribute type not provided");
69         }
70         final ToscaFunctionType toscaFunctionType = ToscaFunctionType.findType(functionType)
71             .orElseThrow(() -> context.instantiationException(ToscaFunction.class,
72                 String.format("Invalid function type '%s' or attribute type not provided", functionType))
73             );
74         if (toscaFunctionType == ToscaFunctionType.GET_INPUT || toscaFunctionType == ToscaFunctionType.GET_ATTRIBUTE
75             || toscaFunctionType == ToscaFunctionType.GET_PROPERTY) {
76             return deserializeToscaGetFunction(toscaFunctionType, node, context);
77         }
78
79         if (toscaFunctionType == ToscaFunctionType.CONCAT) {
80             return this.deserializeConcatFunction(node, context);
81         }
82
83         if (toscaFunctionType == ToscaFunctionType.YAML) {
84             return this.deserializeYamlFunction(node, context);
85         }
86
87         if (toscaFunctionType == ToscaFunctionType.CUSTOM) {
88             return this.deserializeCustomFunction(node, context);
89         }
90
91         return null;
92     }
93
94     private ToscaFunction deserializeYamlFunction(final JsonNode node, final DeserializationContext context) throws JsonMappingException {
95         var yamlFunction = new CustomYamlFunction();
96         final JsonNode valueJsonNode = node.get("value");
97         if (valueJsonNode == null) {
98             return yamlFunction;
99         }
100         final String valueAsText = valueJsonNode.asText();
101         try {
102             yamlFunction.setYamlValue(new Yaml().load(valueAsText));
103         } catch (final Exception e) {
104             final String errorMsg = String.format("Could not parse YAML expression: '%s'", valueAsText);
105             LOGGER.debug(errorMsg, e);
106             throw context.instantiationException(ToscaFunction.class, errorMsg);
107         }
108         return yamlFunction;
109     }
110
111     private ToscaGetFunctionDataDefinition deserializeToscaGetFunction(final ToscaFunctionType toscaFunctionType, final JsonNode node,
112                                                                        final DeserializationContext context) throws JsonMappingException {
113         final ToscaGetFunctionDataDefinition toscaGetFunction = new ToscaGetFunctionDataDefinition();
114         toscaGetFunction.setFunctionType(ToscaGetFunctionType.fromToscaFunctionType(toscaFunctionType).orElse(null));
115         toscaGetFunction.setSourceName(getAsTextOrElseNull(node, "sourceName"));
116         toscaGetFunction.setSourceUniqueId(getAsTextOrElseNull(node, "sourceUniqueId"));
117         toscaGetFunction.setPropertyName(getAsTextOrElseNull(node, "propertyName"));
118         toscaGetFunction.setPropertyUniqueId(getAsTextOrElseNull(node, "propertyUniqueId"));
119         toscaGetFunction.setToscaIndexList(getNumberAsTextOrElseNull(node, "toscaIndexList", context));
120
121         final String propertySource = getAsTextOrElseNull(node, "propertySource");
122         if (StringUtils.isNotEmpty(propertySource)) {
123             final PropertySource propertySource1 = PropertySource.findType(propertySource).orElseThrow(() ->
124                 context.instantiationException(ToscaGetFunctionDataDefinition.class,
125                     String.format("Invalid propertySource '%s'", propertySource))
126             );
127             toscaGetFunction.setPropertySource(propertySource1);
128         }
129         final JsonNode propertyPathFromSourceNode = node.get("propertyPathFromSource");
130         if (propertyPathFromSourceNode != null) {
131             if (!propertyPathFromSourceNode.isArray()) {
132                 throw context.instantiationException(ToscaGetFunctionDataDefinition.class, "Expecting an array for propertyPathFromSource attribute");
133             }
134             final List<String> pathFromSource = new ArrayList<>();
135             propertyPathFromSourceNode.forEach(jsonNode -> pathFromSource.add(jsonNode.asText()));
136             toscaGetFunction.setPropertyPathFromSource(pathFromSource);
137         }
138
139         return toscaGetFunction;
140     }
141
142     private String getAsTextOrElseNull(final JsonNode node, final String fieldName) {
143         final JsonNode jsonNode = node.get(fieldName);
144         if (jsonNode == null) {
145             return null;
146         }
147         if (!jsonNode.isTextual()) {
148             return null;
149         }
150         return jsonNode.asText();
151     }
152
153     private List<Object> getNumberAsTextOrElseNull(final JsonNode node, final String fieldName, final DeserializationContext context) throws JsonMappingException{
154         List<Object> toscaIndexList = new ArrayList<Object>();
155         final JsonNode jsonNode = node.get(fieldName);
156         if (jsonNode != null) {
157             if (!jsonNode.isArray()) {
158                 throw context.instantiationException(ToscaGetFunctionDataDefinition.class, "Expecting an array for toscaIndexList attribute");
159             }
160             for (int index=0;index<jsonNode.size();index++) {
161                 String textValue = jsonNode.get(index).asText();
162                 if (index%2 == 0) {
163                     if (textValue.equalsIgnoreCase("INDEX")) {
164                         toscaIndexList.add(textValue);
165                     } else {
166                         try {
167                             toscaIndexList.add(Integer.parseInt(textValue));
168                         } catch(Exception e) {
169                             throw context.instantiationException(ToscaGetFunctionDataDefinition.class, "Expecting a valid value for toscaIndex attribute");
170                         }
171                     }
172                 } else {
173                     toscaIndexList.add(textValue);
174                 }
175             }
176         }
177         return toscaIndexList;
178     }
179
180     private ToscaConcatFunction deserializeConcatFunction(final JsonNode concatFunctionJsonNode,
181                                                           final DeserializationContext context) throws IOException {
182         final var toscaConcatFunction = new ToscaConcatFunction();
183         List<ToscaFunctionParameter> functionParameterList = getParameters(concatFunctionJsonNode, context);
184         toscaConcatFunction.setParameters(functionParameterList);
185         return toscaConcatFunction;
186     }
187
188     private ToscaCustomFunction deserializeCustomFunction(final JsonNode customFunctionJsonNode,
189                                                           final DeserializationContext context) throws IOException {
190         final var toscaCustomFunction = new ToscaCustomFunction();
191         final String name = getAsTextOrElseNull(customFunctionJsonNode, "name");
192         if (name == null) {
193             throw context.instantiationException(List.class, "Expecting a string for the 'name' entry");
194         }
195         toscaCustomFunction.setName(name);
196         toscaCustomFunction.setToscaFunctionType(getCustomFunctionType(name));
197         List<ToscaFunctionParameter> functionParameterList = getParameters(customFunctionJsonNode, context);
198         toscaCustomFunction.setParameters(functionParameterList);
199         if (ToscaFunctionType.GET_INPUT.equals(toscaCustomFunction.getToscaFunctionType())) {
200             validateGetInput(toscaCustomFunction, context);
201         }
202         return toscaCustomFunction;
203     }
204
205     private ToscaFunctionType getCustomFunctionType(String name) {
206         List<Configuration.CustomToscaFunction> customFunctions =
207             ConfigurationManager.getConfigurationManager().getConfiguration().getDefaultCustomToscaFunctions();
208         if (customFunctions.isEmpty()) {
209             return ToscaFunctionType.CUSTOM;
210         }
211         Optional<Configuration.CustomToscaFunction> optionalFunc = customFunctions.stream().filter(func -> func.getName().equals(name)).findFirst();
212         if (optionalFunc.isEmpty()) {
213             return ToscaFunctionType.CUSTOM;
214         }
215         String type = optionalFunc.get().getType();
216         return ToscaFunctionType.findType(type).get();
217     }
218
219     private void validateGetInput(ToscaCustomFunction toscaCustomFunction, final DeserializationContext context) throws IOException {
220         List<ToscaFunctionParameter> functionParameterList = toscaCustomFunction.getParameters();
221         if (functionParameterList.size() != 1) {
222             throw context.instantiationException(List.class, "Custom GET_INPUT function must contain one GET_INPUT parameter");
223         }
224         ToscaFunctionParameter parameter = functionParameterList.get(0);
225         if (!ToscaFunctionType.GET_INPUT.equals(parameter.getType())) {
226             throw context.instantiationException(List.class, "Custom GET_INPUT function must contain a GET_INPUT parameter");
227         }
228     }
229
230     private List<ToscaFunctionParameter> getParameters(final JsonNode functionJsonNode, final DeserializationContext context) throws IOException {
231         final List<ToscaFunctionParameter> functionParameterList = new ArrayList<>();
232         final JsonNode parametersNode = functionJsonNode.get("parameters");
233         if (parametersNode == null) {
234             return functionParameterList;
235         }
236         if (!parametersNode.isArray()) {
237             throw context.instantiationException(List.class, "Expecting an array for the 'parameters' entry");
238         }
239
240         for (final JsonNode parameterNode : parametersNode) {
241             final JsonNode typeJsonNode = parameterNode.get("type");
242             if (typeJsonNode == null) {
243                 throw context.instantiationException(ToscaFunction.class, "TOSCA function parameter type attribute not provided");
244             }
245             final String parameterType = typeJsonNode.asText();
246             final ToscaFunctionType toscaFunctionType = ToscaFunctionType.findType(parameterType)
247                 .orElseThrow(() -> context.instantiationException(ToscaFunction.class,
248                     String.format("Invalid TOSCA function parameter type '%s'", parameterType))
249                 );
250             if (toscaFunctionType == ToscaFunctionType.STRING) {
251                 final ToscaStringParameter toscaStringParameter = new ToscaStringParameter();
252                 toscaStringParameter.setValue(parameterNode.get("value").asText());
253                 functionParameterList.add(toscaStringParameter);
254             } else {
255                 final ToscaFunction toscaFunction = this.deserializeToscaFunction(parameterNode, context);
256                 functionParameterList.add((ToscaFunctionParameter) toscaFunction);
257             }
258         }
259         return functionParameterList;
260     }
261
262 }