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