9671eee2179b37db5344a8703b284ee9eca78904
[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.springframework.util.CollectionUtils;
41 import org.yaml.snakeyaml.Yaml;
42
43 public class ToscaFunctionJsonDeserializer extends StdDeserializer<ToscaFunction> {
44
45     private static final Logger LOGGER = LoggerFactory.getLogger(ToscaFunctionJsonDeserializer.class);
46
47     public ToscaFunctionJsonDeserializer() {
48         this(null);
49     }
50
51     public ToscaFunctionJsonDeserializer(Class<?> vc) {
52         super(vc);
53     }
54
55     @Override
56     public ToscaFunction deserialize(final JsonParser jsonParser, final DeserializationContext context) throws IOException {
57         final JsonNode node = jsonParser.getCodec().readTree(jsonParser);
58         return deserializeToscaFunction(node, context);
59     }
60
61     private ToscaFunction deserializeToscaFunction(final JsonNode node, final DeserializationContext context) throws IOException {
62         final String functionType;
63         if (node.get("type") != null) {
64             functionType = node.get("type").asText();
65         } else if (node.get("functionType") != null) {
66             //support for legacy tosca function
67             functionType = node.get("functionType").asText();
68         } else {
69             throw context.instantiationException(ToscaFunction.class, "Attribute type not provided");
70         }
71         final ToscaFunctionType toscaFunctionType = ToscaFunctionType.findType(functionType)
72             .orElseThrow(() -> context.instantiationException(ToscaFunction.class,
73                 String.format("Invalid function type '%s' or attribute type not provided", functionType))
74             );
75         if (toscaFunctionType == ToscaFunctionType.GET_INPUT || toscaFunctionType == ToscaFunctionType.GET_ATTRIBUTE
76             || toscaFunctionType == ToscaFunctionType.GET_PROPERTY) {
77             return deserializeToscaGetFunction(toscaFunctionType, node, context);
78         }
79
80         if (toscaFunctionType == ToscaFunctionType.CONCAT) {
81             return this.deserializeConcatFunction(node, context);
82         }
83
84         if (toscaFunctionType == ToscaFunctionType.YAML) {
85             return this.deserializeYamlFunction(node, context);
86         }
87
88         if (toscaFunctionType == ToscaFunctionType.CUSTOM) {
89             return this.deserializeCustomFunction(node, context);
90         }
91
92         return null;
93     }
94
95     private ToscaFunction deserializeYamlFunction(final JsonNode node, final DeserializationContext context) throws JsonMappingException {
96         var yamlFunction = new CustomYamlFunction();
97         final JsonNode valueJsonNode = node.get("value");
98         if (valueJsonNode == null) {
99             return yamlFunction;
100         }
101         final String valueAsText = valueJsonNode.asText();
102         try {
103             yamlFunction.setYamlValue(new Yaml().load(valueAsText));
104         } catch (final Exception e) {
105             final String errorMsg = String.format("Could not parse YAML expression: '%s'", valueAsText);
106             LOGGER.debug(errorMsg, e);
107             throw context.instantiationException(ToscaFunction.class, errorMsg);
108         }
109         return yamlFunction;
110     }
111
112     private ToscaGetFunctionDataDefinition deserializeToscaGetFunction(final ToscaFunctionType toscaFunctionType, final JsonNode node,
113                                                                        final DeserializationContext context) throws JsonMappingException {
114         final ToscaGetFunctionDataDefinition toscaGetFunction = new ToscaGetFunctionDataDefinition();
115         toscaGetFunction.setFunctionType(ToscaGetFunctionType.fromToscaFunctionType(toscaFunctionType).orElse(null));
116         toscaGetFunction.setSourceName(getAsTextOrElseNull(node, "sourceName"));
117         toscaGetFunction.setSourceUniqueId(getAsTextOrElseNull(node, "sourceUniqueId"));
118         toscaGetFunction.setPropertyName(getAsTextOrElseNull(node, "propertyName"));
119         toscaGetFunction.setPropertyUniqueId(getAsTextOrElseNull(node, "propertyUniqueId"));
120         toscaGetFunction.setToscaIndexList(getNumberAsTextOrElseNull(node, "toscaIndexList", context));
121
122         final String propertySource = getAsTextOrElseNull(node, "propertySource");
123         if (StringUtils.isNotEmpty(propertySource)) {
124             final PropertySource propertySource1 = PropertySource.findType(propertySource).orElseThrow(() ->
125                 context.instantiationException(ToscaGetFunctionDataDefinition.class,
126                     String.format("Invalid propertySource '%s'", propertySource))
127             );
128             toscaGetFunction.setPropertySource(propertySource1);
129         }
130         final JsonNode propertyPathFromSourceNode = node.get("propertyPathFromSource");
131         if (propertyPathFromSourceNode != null) {
132             if (!propertyPathFromSourceNode.isArray()) {
133                 throw context.instantiationException(ToscaGetFunctionDataDefinition.class, "Expecting an array for propertyPathFromSource attribute");
134             }
135             final List<String> pathFromSource = new ArrayList<>();
136             propertyPathFromSourceNode.forEach(jsonNode -> pathFromSource.add(jsonNode.asText()));
137             toscaGetFunction.setPropertyPathFromSource(pathFromSource);
138         }
139
140         return toscaGetFunction;
141     }
142
143     private String getAsTextOrElseNull(final JsonNode node, final String fieldName) {
144         final JsonNode jsonNode = node.get(fieldName);
145         if (jsonNode == null) {
146             return null;
147         }
148         if (!jsonNode.isTextual()) {
149             return null;
150         }
151         return jsonNode.asText();
152     }
153
154     private List<Object> getNumberAsTextOrElseNull(final JsonNode node, final String fieldName, final DeserializationContext context)
155         throws JsonMappingException {
156         List<Object> toscaIndexList = new ArrayList<Object>();
157         final JsonNode jsonNode = node.get(fieldName);
158         if (jsonNode != null) {
159             if (!jsonNode.isArray()) {
160                 throw context.instantiationException(ToscaGetFunctionDataDefinition.class, "Expecting an array for toscaIndexList attribute");
161             }
162
163             jsonNode.forEach(nodeValue -> {
164                 String indexValue = nodeValue.asText();
165                 if (StringUtils.isNumeric(indexValue)) {
166                     toscaIndexList.add(Integer.parseInt(indexValue));
167                 } else {
168                     toscaIndexList.add(indexValue);
169                 }
170             });
171         }
172         return toscaIndexList;
173     }
174
175     private ToscaConcatFunction deserializeConcatFunction(final JsonNode concatFunctionJsonNode,
176                                                           final DeserializationContext context) throws IOException {
177         final var toscaConcatFunction = new ToscaConcatFunction();
178         List<ToscaFunctionParameter> functionParameterList = getParameters(concatFunctionJsonNode, context);
179         toscaConcatFunction.setParameters(functionParameterList);
180         return toscaConcatFunction;
181     }
182
183     private ToscaCustomFunction deserializeCustomFunction(final JsonNode customFunctionJsonNode,
184                                                           final DeserializationContext context) throws IOException {
185         final var toscaCustomFunction = new ToscaCustomFunction();
186         final String name = getAsTextOrElseNull(customFunctionJsonNode, "name");
187         if (name == null) {
188             throw context.instantiationException(List.class, "Expecting a string for the 'name' entry");
189         }
190         toscaCustomFunction.setName(name);
191         toscaCustomFunction.setToscaFunctionType(getCustomFunctionType(name));
192         List<ToscaFunctionParameter> functionParameterList = getParameters(customFunctionJsonNode, context);
193         toscaCustomFunction.setParameters(functionParameterList);
194         if (ToscaFunctionType.GET_INPUT.equals(toscaCustomFunction.getToscaFunctionType())) {
195             validateGetInput(toscaCustomFunction, context);
196         }
197         return toscaCustomFunction;
198     }
199
200     private ToscaFunctionType getCustomFunctionType(String name) {
201         List<Configuration.CustomToscaFunction> customFunctions =
202             ConfigurationManager.getConfigurationManager().getConfiguration().getDefaultCustomToscaFunctions();
203         if (CollectionUtils.isEmpty(customFunctions)) {
204             return ToscaFunctionType.CUSTOM;
205         }
206         Optional<Configuration.CustomToscaFunction> optionalFunc = customFunctions.stream().filter(func -> func.getName().equals(name)).findFirst();
207         if (optionalFunc.isEmpty()) {
208             return ToscaFunctionType.CUSTOM;
209         }
210         String type = optionalFunc.get().getType();
211         return ToscaFunctionType.findType(type).get();
212     }
213
214     private void validateGetInput(ToscaCustomFunction toscaCustomFunction, final DeserializationContext context) throws IOException {
215         List<ToscaFunctionParameter> functionParameterList = toscaCustomFunction.getParameters();
216         if (functionParameterList.size() != 1) {
217             throw context.instantiationException(List.class, "Custom GET_INPUT function must contain one GET_INPUT parameter");
218         }
219         ToscaFunctionParameter parameter = functionParameterList.get(0);
220         if (!ToscaFunctionType.GET_INPUT.equals(parameter.getType())) {
221             throw context.instantiationException(List.class, "Custom GET_INPUT function must contain a GET_INPUT parameter");
222         }
223     }
224
225     private List<ToscaFunctionParameter> getParameters(final JsonNode functionJsonNode, final DeserializationContext context) throws IOException {
226         final List<ToscaFunctionParameter> functionParameterList = new ArrayList<>();
227         final JsonNode parametersNode = functionJsonNode.get("parameters");
228         if (parametersNode == null) {
229             return functionParameterList;
230         }
231         if (!parametersNode.isArray()) {
232             throw context.instantiationException(List.class, "Expecting an array for the 'parameters' entry");
233         }
234
235         for (final JsonNode parameterNode : parametersNode) {
236             final JsonNode typeJsonNode = parameterNode.get("type");
237             if (typeJsonNode == null) {
238                 throw context.instantiationException(ToscaFunction.class, "TOSCA function parameter type attribute not provided");
239             }
240             final String parameterType = typeJsonNode.asText();
241             final ToscaFunctionType toscaFunctionType = ToscaFunctionType.findType(parameterType)
242                 .orElseThrow(() -> context.instantiationException(ToscaFunction.class,
243                     String.format("Invalid TOSCA function parameter type '%s'", parameterType))
244                 );
245             if (toscaFunctionType == ToscaFunctionType.STRING) {
246                 final ToscaStringParameter toscaStringParameter = new ToscaStringParameter();
247                 toscaStringParameter.setValue(parameterNode.get("value").asText());
248                 functionParameterList.add(toscaStringParameter);
249             } else {
250                 final ToscaFunction toscaFunction = this.deserializeToscaFunction(parameterNode, context);
251                 functionParameterList.add((ToscaFunctionParameter) toscaFunction);
252             }
253         }
254         return functionParameterList;
255     }
256
257 }