394d6b314bd20b7dc9a4b4f6b9d7184a3b3354ad
[sdc.git] / catalog-be / src / main / java / org / openecomp / sdc / be / components / attribute / DefaultAttributeDeclarator.java
1 /*-
2  * ============LICENSE_START=======================================================
3  * SDC
4  * ================================================================================
5  * Copyright (C) 2021, Nordix Foundation. 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.components.attribute;
21
22 import static org.openecomp.sdc.common.api.Constants.GET_ATTRIBUTE;
23
24 import com.google.gson.Gson;
25 import fj.data.Either;
26 import java.util.ArrayList;
27 import java.util.Arrays;
28 import java.util.HashMap;
29 import java.util.HashSet;
30 import java.util.List;
31 import java.util.Map;
32 import java.util.Objects;
33 import java.util.Optional;
34 import java.util.Set;
35 import java.util.stream.Collectors;
36 import org.apache.commons.collections4.CollectionUtils;
37 import org.apache.commons.collections4.MapUtils;
38 import org.apache.commons.lang3.StringUtils;
39 import org.json.simple.JSONObject;
40 import org.openecomp.sdc.be.datatypes.elements.AttributeDataDefinition;
41 import org.openecomp.sdc.be.datatypes.elements.GetOutputValueDataDefinition;
42 import org.openecomp.sdc.be.datatypes.elements.PropertiesOwner;
43 import org.openecomp.sdc.be.model.AttributeDefinition;
44 import org.openecomp.sdc.be.model.Component;
45 import org.openecomp.sdc.be.model.ComponentInstanceAttribOutput;
46 import org.openecomp.sdc.be.model.IComponentInstanceConnectedElement;
47 import org.openecomp.sdc.be.model.OutputDefinition;
48 import org.openecomp.sdc.be.model.operations.api.StorageOperationStatus;
49 import org.openecomp.sdc.be.model.operations.impl.UniqueIdBuilder;
50 import org.openecomp.sdc.common.log.wrappers.Logger;
51 import org.yaml.snakeyaml.Yaml;
52
53 public abstract class DefaultAttributeDeclarator<PROPERTYOWNER extends PropertiesOwner, ATTRIBUTETYPE extends AttributeDataDefinition> implements
54     AttributeDeclarator {
55
56     private static final Logger log = Logger.getLogger(DefaultAttributeDeclarator.class);
57     private static final String UNDERSCORE = "_";
58     private final Gson gson = new Gson();
59
60     protected DefaultAttributeDeclarator() {
61     }
62
63     @Override
64     public Either<List<OutputDefinition>, StorageOperationStatus> declareAttributesAsOutputs(final Component component,
65                                                                                              final String propertiesOwnerId,
66                                                                                              final List<ComponentInstanceAttribOutput> attribsToDeclare) {
67         log.debug("#declarePropertiesAsInputs - declaring properties as inputs for component {} from properties owner {}", component.getUniqueId(),
68             propertiesOwnerId);
69         return resolvePropertiesOwner(component, propertiesOwnerId)
70             .map(propertyOwner -> declareAttributesAsOutputs(component, propertyOwner, attribsToDeclare))
71             .orElse(Either.right(onPropertiesOwnerNotFound(component.getUniqueId(), propertiesOwnerId)));
72     }
73
74     protected abstract ATTRIBUTETYPE createDeclaredAttribute(final AttributeDataDefinition attributeDataDefinition);
75
76     protected abstract Either<?, StorageOperationStatus> updateAttributesValues(final Component component, final String propertiesOwnerId,
77                                                                                 final List<ATTRIBUTETYPE> attributetypeList);
78
79     protected abstract Optional<PROPERTYOWNER> resolvePropertiesOwner(final Component component, final String propertiesOwnerId);
80
81     private StorageOperationStatus onPropertiesOwnerNotFound(final String componentId, final String propertiesOwnerId) {
82         log.debug("#declarePropertiesAsInputs - properties owner {} was not found on component {}", propertiesOwnerId, componentId);
83         return StorageOperationStatus.NOT_FOUND;
84     }
85
86     private Either<List<OutputDefinition>, StorageOperationStatus> declareAttributesAsOutputs(final Component component,
87                                                                                               final PROPERTYOWNER propertiesOwner,
88                                                                                               final List<ComponentInstanceAttribOutput> attributesToDeclare) {
89         final AttributesDeclarationData attributesDeclarationData = createOutputsAndOverrideAttributesValues(component, propertiesOwner,
90             attributesToDeclare);
91         return updateAttributesValues(component, propertiesOwner.getUniqueId(), attributesDeclarationData.getAttributesToUpdate()).left()
92             .map(updatePropsRes -> attributesDeclarationData.getOutputsToCreate());
93     }
94
95     private AttributesDeclarationData createOutputsAndOverrideAttributesValues(final Component component, final PROPERTYOWNER propertiesOwner,
96                                                                                final List<ComponentInstanceAttribOutput> attributesToDeclare) {
97         final List<ATTRIBUTETYPE> declaredAttributes = new ArrayList<>();
98         final List<OutputDefinition> createdInputs = attributesToDeclare.stream()
99             .map(attributeOutput -> declareAttributeOutput(component, propertiesOwner, declaredAttributes, attributeOutput))
100             .collect(Collectors.toList());
101         return new AttributesDeclarationData(createdInputs, declaredAttributes);
102     }
103
104     private OutputDefinition declareAttributeOutput(final Component component, final PROPERTYOWNER propertiesOwner,
105                                                     final List<ATTRIBUTETYPE> declaredAttributes, final ComponentInstanceAttribOutput attribOutput) {
106         final AttributeDataDefinition attribute = resolveAttribute(declaredAttributes, attribOutput);
107         final OutputDefinition outputDefinition = createOutput(component, propertiesOwner, attribOutput, attribute);
108         final ATTRIBUTETYPE declaredAttribute = createDeclaredAttribute(attribute);
109         if (!declaredAttributes.contains(declaredAttribute)) {
110             declaredAttributes.add(declaredAttribute);
111         }
112         return outputDefinition;
113     }
114
115     private OutputDefinition createOutput(final Component component, final PROPERTYOWNER propertiesOwner,
116                                           final ComponentInstanceAttribOutput attribOutput, final AttributeDataDefinition attributeDataDefinition) {
117         String generatedInputPrefix = propertiesOwner.getNormalizedName();
118         if (propertiesOwner.getUniqueId().equals(attribOutput.getParentUniqueId())) {
119             //Creating input from property create on self using add property..Do not add the prefix
120             generatedInputPrefix = null;
121         }
122         final String generatedOutputName = generateOutputName(generatedInputPrefix, attribOutput);
123         log.debug("createInput: propOwner.uniqueId={}, attribOutput.parentUniqueId={}", propertiesOwner.getUniqueId(),
124             attribOutput.getParentUniqueId());
125         return createOutputFromAttribute(component.getUniqueId(), propertiesOwner, generatedOutputName, attribOutput, attributeDataDefinition);
126     }
127
128     private String generateOutputName(final String outputName, final ComponentInstanceAttribOutput attribOutput) {
129         final String declaredInputName;
130         final String[] parsedPropNames = attribOutput.getParsedAttribNames();
131         if (parsedPropNames != null) {
132             declaredInputName = handleInputName(outputName, parsedPropNames);
133         } else {
134             final String[] propName = {attribOutput.getName()};
135             declaredInputName = handleInputName(outputName, propName);
136         }
137         return declaredInputName;
138     }
139
140     private String handleInputName(final String outputName, final String[] parsedPropNames) {
141         final StringBuilder prefix = new StringBuilder();
142         int startingIndex;
143         if (Objects.isNull(outputName)) {
144             prefix.append(parsedPropNames[0]);
145             startingIndex = 1;
146         } else {
147             prefix.append(outputName);
148             startingIndex = 0;
149         }
150         while (startingIndex < parsedPropNames.length) {
151             prefix.append(UNDERSCORE);
152             prefix.append(parsedPropNames[startingIndex]);
153             startingIndex++;
154         }
155         return prefix.toString();
156     }
157
158     private AttributeDataDefinition resolveAttribute(final List<ATTRIBUTETYPE> attributesToCreate, final ComponentInstanceAttribOutput attribOutput) {
159         final Optional<ATTRIBUTETYPE> resolvedAttribute = attributesToCreate.stream().filter(p -> p.getName().equals(attribOutput.getName()))
160             .findFirst();
161         return resolvedAttribute.isPresent() ? resolvedAttribute.get() : attribOutput;
162     }
163
164     OutputDefinition createOutputFromAttribute(final String componentId, final PROPERTYOWNER propertiesOwner, final String outputName,
165                                                final ComponentInstanceAttribOutput attributeOutput, final AttributeDataDefinition attribute) {
166         final String attributesName = attributeOutput.getAttributesName();
167         final AttributeDefinition selectedAttrib = attributeOutput.getOutput();
168         final String[] parsedAttribNames = attributeOutput.getParsedAttribNames();
169         OutputDefinition outputDefinition;
170         boolean complexProperty = false;
171         if (attributesName != null && !attributesName.isEmpty() && selectedAttrib != null) {
172             complexProperty = true;
173             outputDefinition = new OutputDefinition(selectedAttrib);
174             outputDefinition.setDefaultValue(selectedAttrib.getValue());
175         } else {
176             outputDefinition = new OutputDefinition(attribute);
177             outputDefinition.setDefaultValue(attribute.getValue());
178         }
179         outputDefinition.setName(outputName);
180         outputDefinition.setUniqueId(UniqueIdBuilder.buildPropertyUniqueId(componentId, outputDefinition.getName()));
181         outputDefinition.setOutputPath(attributesName);
182         outputDefinition.setInstanceUniqueId(propertiesOwner.getUniqueId());
183         outputDefinition.setAttributeId(attributeOutput.getUniqueId());
184         outputDefinition.setAttribute(attributeOutput);
185         if (attribute instanceof IComponentInstanceConnectedElement) {
186             ((IComponentInstanceConnectedElement) attribute).setComponentInstanceId(propertiesOwner.getUniqueId());
187             ((IComponentInstanceConnectedElement) attribute).setComponentInstanceName(propertiesOwner.getName());
188         }
189         changeOutputValueToGetAttributeValue(outputName, parsedAttribNames, outputDefinition, attribute, complexProperty);
190         return outputDefinition;
191     }
192
193     private void changeOutputValueToGetAttributeValue(final String outputName, final String[] parsedPropNames, final OutputDefinition output,
194                                                       final AttributeDataDefinition attributeDataDefinition, final boolean complexProperty) {
195         JSONObject jsonObject = new JSONObject();
196         final String value = attributeDataDefinition.getValue();
197         if (StringUtils.isEmpty(value)) {
198             if (complexProperty) {
199                 jsonObject = createJSONValueForProperty(parsedPropNames.length - 1, parsedPropNames, jsonObject, outputName);
200                 attributeDataDefinition.setValue(jsonObject.toJSONString());
201             } else {
202                 jsonObject
203                     .put(GET_ATTRIBUTE, Arrays.asList(output.getAttribute().getComponentInstanceName(), attributeDataDefinition.getName()));
204                 output.setValue(jsonObject.toJSONString());
205             }
206         } else {
207             final Object objValue = new Yaml().load(value);
208             if (objValue instanceof Map || objValue instanceof List) {
209                 if (!complexProperty) {
210                     jsonObject.put(GET_ATTRIBUTE,
211                         Arrays.asList(output.getAttribute().getComponentInstanceName(), attributeDataDefinition.getName()));
212                     output.setValue(jsonObject.toJSONString());
213                 } else {
214                     final Map<String, Object> mappedToscaTemplate = (Map<String, Object>) objValue;
215                     createOutputValue(mappedToscaTemplate, 1, parsedPropNames, outputName);
216                     output.setValue(gson.toJson(mappedToscaTemplate));
217                 }
218             } else {
219                 jsonObject
220                     .put(GET_ATTRIBUTE, Arrays.asList(output.getAttribute().getComponentInstanceName(), attributeDataDefinition.getName()));
221                 output.setValue(jsonObject.toJSONString());
222             }
223         }
224         if (CollectionUtils.isEmpty(attributeDataDefinition.getGetOutputValues())) {
225             attributeDataDefinition.setGetOutputValues(new ArrayList<>());
226         }
227         final List<GetOutputValueDataDefinition> getOutputValues = attributeDataDefinition.getGetOutputValues();
228         final GetOutputValueDataDefinition getOutputValueDataDefinition = new GetOutputValueDataDefinition();
229         getOutputValueDataDefinition.setOutputId(output.getUniqueId());
230         getOutputValueDataDefinition.setOutputName(output.getName());
231         getOutputValues.add(getOutputValueDataDefinition);
232     }
233
234     private JSONObject createJSONValueForProperty(int i, final String[] parsedPropNames, final JSONObject ooj, final String outputName) {
235         while (i >= 1) {
236             if (i == parsedPropNames.length - 1) {
237                 final JSONObject jobProp = new JSONObject();
238                 jobProp.put(GET_ATTRIBUTE, outputName);
239                 ooj.put(parsedPropNames[i], jobProp);
240                 i--;
241                 return createJSONValueForProperty(i, parsedPropNames, ooj, outputName);
242             } else {
243                 final JSONObject res = new JSONObject();
244                 res.put(parsedPropNames[i], ooj);
245                 i--;
246                 return createJSONValueForProperty(i, parsedPropNames, res, outputName);
247             }
248         }
249         return ooj;
250     }
251
252     private Map<String, Object> createOutputValue(final Map<String, Object> lhm1, int index, final String[] outputNames, final String outputName) {
253         while (index < outputNames.length) {
254             if (lhm1.containsKey(outputNames[index])) {
255                 final Object value = lhm1.get(outputNames[index]);
256                 if (value instanceof Map) {
257                     if (index == outputNames.length - 1) {
258                         return (Map<String, Object>) ((Map) value).put(GET_ATTRIBUTE, outputName);
259                     } else {
260                         return createOutputValue((Map) value, ++index, outputNames, outputName);
261                     }
262                 } else {
263                     final Map<String, Object> jobProp = new HashMap<>();
264                     if (index == outputNames.length - 1) {
265                         jobProp.put(GET_ATTRIBUTE, outputName);
266                         lhm1.put(outputNames[index], jobProp);
267                         return lhm1;
268                     } else {
269                         lhm1.put(outputNames[index], jobProp);
270                         return createOutputValue(jobProp, ++index, outputNames, outputName);
271                     }
272                 }
273             } else {
274                 final Map<String, Object> jobProp = new HashMap<>();
275                 lhm1.put(outputNames[index], jobProp);
276                 if (index == outputNames.length - 1) {
277                     jobProp.put(GET_ATTRIBUTE, outputName);
278                     return jobProp;
279                 } else {
280                     return createOutputValue(jobProp, ++index, outputNames, outputName);
281                 }
282             }
283         }
284         return lhm1;
285     }
286
287     private void resetOutputName(final Map<String, Object> lhm1, final String outputName) {
288         for (final Map.Entry<String, Object> entry : lhm1.entrySet()) {
289             final String key = entry.getKey();
290             final Object value = entry.getValue();
291             if (value instanceof String && ((String) value).equalsIgnoreCase(outputName) && GET_ATTRIBUTE.equals(key)) {
292                 lhm1.remove(key);
293             } else if (value instanceof Map) {
294                 final Map<String, Object> subMap = (Map<String, Object>) value;
295                 resetOutputName(subMap, outputName);
296             } else if (value instanceof List && ((List) value).contains(outputName) && GET_ATTRIBUTE.equals(key)) {
297                 lhm1.remove(key);
298             }
299         }
300     }
301
302     /*        Mutates the object
303      *        Tail recurse -> traverse the tosca elements and remove nested empty map properties
304      *        this only handles nested maps, other objects are left untouched (even a Set containing a map) since behaviour is unexpected
305      *
306      *        @param  toscaElement - expected map of tosca values
307      *        @return mutated @param toscaElement , where empty maps are deleted , return null for empty map.
308      **/
309     private Object cleanEmptyNestedValuesInMap(final Object toscaElement, short loopProtectionLevel) {
310         if (loopProtectionLevel <= 0 || !(toscaElement instanceof Map)) {
311             return toscaElement;
312         }
313         Map<Object, Object> toscaMap = (Map<Object, Object>) toscaElement;
314         if (MapUtils.isNotEmpty(toscaMap)) {
315             Object ret;
316             final Set<Object> keysToRemove = new HashSet<>();                                                                 // use different set to avoid ConcurrentModificationException
317             for (final Object key : toscaMap.keySet()) {
318                 final Object value = toscaMap.get(key);
319                 ret = cleanEmptyNestedValuesInMap(value, --loopProtectionLevel);
320                 if (ret == null) {
321                     keysToRemove.add(key);
322                 }
323             }
324             final Set<Object> keySet = toscaMap.keySet();
325             if (CollectionUtils.isNotEmpty(keySet)) {
326                 keySet.removeAll(keysToRemove);
327             }
328             if (isEmptyNestedMap(toscaElement)) {
329                 return null;
330             }
331         } else {
332             return null;
333         }
334         return toscaElement;
335     }
336
337     /**
338      * @param element
339      * @return true if map nested maps are all empty, ignores other collection objects
340      */
341     private boolean isEmptyNestedMap(final Object element) {
342         boolean isEmpty = true;
343         if (element != null) {
344             if (element instanceof Map) {
345                 if (MapUtils.isNotEmpty((Map) element)) {
346                     for (final Object key : ((Map) (element)).keySet()) {
347                         Object value = ((Map) (element)).get(key);
348                         isEmpty &= isEmptyNestedMap(value);
349                     }
350                 }
351             } else {
352                 isEmpty = false;
353             }
354         }
355         return isEmpty;
356     }
357
358     private class AttributesDeclarationData {
359
360         private final List<OutputDefinition> outputsToCreate;
361         private final List<ATTRIBUTETYPE> attributesToUpdate;
362
363         AttributesDeclarationData(final List<OutputDefinition> outputsToCreate, final List<ATTRIBUTETYPE> attributesToUpdate) {
364             this.outputsToCreate = outputsToCreate;
365             this.attributesToUpdate = attributesToUpdate;
366         }
367
368         List<OutputDefinition> getOutputsToCreate() {
369             return outputsToCreate;
370         }
371
372         List<ATTRIBUTETYPE> getAttributesToUpdate() {
373             return attributesToUpdate;
374         }
375     }
376 }