Fix 'Wrong Inputs creation on (Add Service)'
[sdc.git] / catalog-be / src / main / java / org / openecomp / sdc / be / components / property / DefaultPropertyDeclarator.java
1 /*-
2  * ============LICENSE_START=======================================================
3  * SDC
4  * ================================================================================
5  * Copyright (C) 2019 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 package org.openecomp.sdc.be.components.property;
21
22 import static org.openecomp.sdc.common.api.Constants.GET_INPUT;
23 import static org.openecomp.sdc.common.api.Constants.GET_POLICY;
24
25 import com.google.gson.Gson;
26 import fj.data.Either;
27 import java.util.ArrayList;
28 import java.util.Arrays;
29 import java.util.Collection;
30 import java.util.HashMap;
31 import java.util.HashSet;
32 import java.util.List;
33 import java.util.Map;
34 import java.util.Objects;
35 import java.util.Optional;
36 import java.util.Set;
37 import java.util.stream.Collectors;
38 import org.apache.commons.collections.CollectionUtils;
39 import org.apache.commons.collections.MapUtils;
40 import org.apache.commons.lang3.StringUtils;
41 import org.json.simple.JSONObject;
42 import org.openecomp.sdc.be.components.utils.PropertiesUtils;
43 import org.openecomp.sdc.be.dao.janusgraph.JanusGraphOperationStatus;
44 import org.openecomp.sdc.be.datatypes.elements.GetInputValueDataDefinition;
45 import org.openecomp.sdc.be.datatypes.elements.GetPolicyValueDataDefinition;
46 import org.openecomp.sdc.be.datatypes.elements.PropertiesOwner;
47 import org.openecomp.sdc.be.datatypes.elements.PropertyDataDefinition;
48 import org.openecomp.sdc.be.impl.ComponentsUtils;
49 import org.openecomp.sdc.be.model.CapabilityDefinition;
50 import org.openecomp.sdc.be.model.Component;
51 import org.openecomp.sdc.be.model.ComponentInstancePropInput;
52 import org.openecomp.sdc.be.model.IComponentInstanceConnectedElement;
53 import org.openecomp.sdc.be.model.InputDefinition;
54 import org.openecomp.sdc.be.model.PolicyDefinition;
55 import org.openecomp.sdc.be.model.PropertyDefinition;
56 import org.openecomp.sdc.be.model.operations.api.StorageOperationStatus;
57 import org.openecomp.sdc.be.model.operations.impl.DaoStatusConverter;
58 import org.openecomp.sdc.be.model.operations.impl.PropertyOperation;
59 import org.openecomp.sdc.be.model.operations.impl.UniqueIdBuilder;
60 import org.openecomp.sdc.common.log.wrappers.Logger;
61 import org.openecomp.sdc.exception.ResponseFormat;
62 import org.yaml.snakeyaml.Yaml;
63
64 public abstract class DefaultPropertyDeclarator<PROPERTYOWNER extends PropertiesOwner, PROPERTYTYPE extends PropertyDataDefinition> implements
65     PropertyDeclarator {
66
67     private static final Logger log = Logger.getLogger(DefaultPropertyDeclarator.class);
68     private static final short LOOP_PROTECTION_LEVEL = 10;
69     private static final String UNDERSCORE = "_";
70     private static final String GET_INPUT_INDEX = "INDEX";
71     private final Gson gson = new Gson();
72     private ComponentsUtils componentsUtils;
73     private PropertyOperation propertyOperation;
74
75     protected DefaultPropertyDeclarator(ComponentsUtils componentsUtils, PropertyOperation propertyOperation) {
76         this.componentsUtils = componentsUtils;
77         this.propertyOperation = propertyOperation;
78     }
79
80     @Override
81     public Either<List<InputDefinition>, StorageOperationStatus> declarePropertiesAsInputs(Component component, String propertiesOwnerId,
82                                                                                            List<ComponentInstancePropInput> propsToDeclare) {
83         log.debug("#declarePropertiesAsInputs - declaring properties as inputs for component {} from properties owner {}", component.getUniqueId(),
84             propertiesOwnerId);
85         return resolvePropertiesOwner(component, propertiesOwnerId)
86             .map(propertyOwner -> declarePropertiesAsInputs(component, propertyOwner, propsToDeclare))
87             .orElse(Either.right(onPropertiesOwnerNotFound(component.getUniqueId(), propertiesOwnerId)));
88     }
89
90     protected abstract PROPERTYTYPE createDeclaredProperty(PropertyDataDefinition prop);
91
92     protected abstract Either<?, StorageOperationStatus> updatePropertiesValues(Component component, String propertiesOwnerId,
93                                                                                 List<PROPERTYTYPE> properties);
94
95     protected abstract Optional<PROPERTYOWNER> resolvePropertiesOwner(Component component, String propertiesOwnerId);
96
97     protected abstract void addPropertiesListToInput(PROPERTYTYPE declaredProp, InputDefinition input);
98
99     @Override
100     public Either<List<PolicyDefinition>, StorageOperationStatus> declarePropertiesAsPolicies(Component component, String propertiesOwnerId,
101                                                                                               List<ComponentInstancePropInput> propsToDeclare) {
102         log.debug("#declarePropertiesAsPolicies - declaring properties as policies for component {} from properties owner {}",
103             component.getUniqueId(), propertiesOwnerId);
104         return resolvePropertiesOwner(component, propertiesOwnerId)
105             .map(propertyOwner -> declarePropertiesAsPolicies(component, propertyOwner, propsToDeclare))
106             .orElse(Either.right(onPropertiesOwnerNotFound(component.getUniqueId(), propertiesOwnerId)));
107     }
108
109     @Override
110     public Either<InputDefinition, StorageOperationStatus> declarePropertiesAsListInput(Component component, String propertiesOwnerId,
111                                                                                         List<ComponentInstancePropInput> propsToDeclare,
112                                                                                         InputDefinition input) {
113         log.debug("#declarePropertiesAsListInput - declaring properties as inputs for component {} from properties owner {}", component.getUniqueId(),
114             propertiesOwnerId);
115         Optional<PROPERTYOWNER> propertyOwner = resolvePropertiesOwner(component, propertiesOwnerId);
116         if (propertyOwner.isPresent()) {
117             return declarePropertiesAsListInput(component, propertyOwner.get(), propsToDeclare, input);
118         } else {
119             return Either.right(onPropertiesOwnerNotFound(component.getUniqueId(), propertiesOwnerId));
120         }
121     }
122
123     public StorageOperationStatus unDeclarePropertiesAsPolicies(Component component, PolicyDefinition policy) {
124         return StorageOperationStatus.OK;
125     }
126
127     private Either<List<PolicyDefinition>, StorageOperationStatus> declarePropertiesAsPolicies(Component component, PROPERTYOWNER propertiesOwner,
128                                                                                                List<ComponentInstancePropInput> propsToDeclare) {
129         PropertiesDeclarationData policyProperties = createPoliciesAndOverridePropertiesValues(propertiesOwner.getUniqueId(),
130             propsToDeclare);
131         return updatePropertiesValues(component, propertiesOwner.getUniqueId(), policyProperties.getPropertiesToUpdate()).left()
132             .map(updatePropsRes -> policyProperties.getPoliciesToCreate());
133     }
134
135     private StorageOperationStatus onPropertiesOwnerNotFound(String componentId, String propertiesOwnerId) {
136         log.debug("#declarePropertiesAsInputs - properties owner {} was not found on component {}", propertiesOwnerId, componentId);
137         return StorageOperationStatus.NOT_FOUND;
138     }
139
140     private Either<List<InputDefinition>, StorageOperationStatus> declarePropertiesAsInputs(Component component, PROPERTYOWNER propertiesOwner,
141                                                                                             List<ComponentInstancePropInput> propsToDeclare) {
142         PropertiesDeclarationData inputsProperties = createInputsAndOverridePropertiesValues(component, propertiesOwner, propsToDeclare);
143         return updatePropertiesValues(component, propertiesOwner.getUniqueId(), inputsProperties.getPropertiesToUpdate()).left()
144             .map(updatePropsRes -> inputsProperties.getInputsToCreate());
145     }
146
147     private PropertiesDeclarationData createPoliciesAndOverridePropertiesValues(String componentId, List<ComponentInstancePropInput> propsToDeclare) {
148         List<PROPERTYTYPE> declaredProperties = new ArrayList<>();
149         List<PolicyDefinition> policies = new ArrayList<>();
150         propsToDeclare.forEach(property -> policies.add(declarePropertyPolicy(componentId, declaredProperties, property)));
151         return new PropertiesDeclarationData(null, policies, declaredProperties);
152     }
153
154     private PolicyDefinition declarePropertyPolicy(String componentId, List<PROPERTYTYPE> declaredProperties, ComponentInstancePropInput propInput) {
155         PropertyDataDefinition prop = resolveProperty(declaredProperties, propInput);
156         propInput.setOwnerId(null);
157         propInput.setParentUniqueId(null);
158         PolicyDefinition policyDefinition = new PolicyDefinition(prop);
159         policyDefinition.setUniqueId(UniqueIdBuilder.buildPolicyUniqueId(componentId, prop.getName()));
160         policyDefinition.setInputPath(prop.getName());
161         policyDefinition.setInstanceUniqueId(componentId);
162         policyDefinition.setPropertyId(prop.getUniqueId());
163         changePropertyValueToGetPolicy(prop, policyDefinition);
164         PROPERTYTYPE declaredProperty = createDeclaredProperty(prop);
165         if (!declaredProperties.contains(declaredProperty)) {
166             declaredProperties.add(declaredProperty);
167         }
168         return policyDefinition;
169     }
170
171     private void changePropertyValueToGetPolicy(PropertyDataDefinition prop, PolicyDefinition policyDefinition) {
172         JSONObject jsonObject = new JSONObject();
173         String origValue = Objects.isNull(prop.getValue()) ? prop.getDefaultValue() : prop.getValue();
174         jsonObject.put(GET_POLICY, null);
175         prop.setValue(jsonObject.toJSONString());
176         policyDefinition.setValue(jsonObject.toJSONString());
177         if (CollectionUtils.isEmpty(prop.getGetPolicyValues())) {
178             prop.setGetPolicyValues(new ArrayList<>());
179         }
180         List<GetPolicyValueDataDefinition> getPolicyValues = prop.getGetPolicyValues();
181         GetPolicyValueDataDefinition getPolicyValueDataDefinition = new GetPolicyValueDataDefinition();
182         getPolicyValueDataDefinition.setPolicyId(policyDefinition.getUniqueId());
183         getPolicyValueDataDefinition.setPropertyName(prop.getName());
184         getPolicyValueDataDefinition.setOrigPropertyValue(origValue);
185         getPolicyValues.add(getPolicyValueDataDefinition);
186         policyDefinition.setGetPolicyValues(getPolicyValues);
187     }
188
189     private Either<InputDefinition, StorageOperationStatus> declarePropertiesAsListInput(Component component, PROPERTYOWNER propertiesOwner,
190                                                                                          List<ComponentInstancePropInput> propsToDeclare,
191                                                                                          InputDefinition input) {
192         List<PROPERTYTYPE> declaredProperties = new ArrayList<>();
193         for (ComponentInstancePropInput propInput : propsToDeclare) {
194             if (StringUtils.isNotEmpty(propInput.getPropertiesName()) && propInput.getInput() != null) {
195                 // sub-property in complex type is checked on UI. currently not supported.
196                 log.debug("skip propInput (propertiesName={}) currently not supported.", propInput.getPropertiesName());
197                 continue;
198             }
199             PROPERTYTYPE declaredProperty = createDeclaredProperty(propInput);
200             JSONObject jsonObject = new JSONObject();
201             jsonObject.put(GET_INPUT, Arrays.asList(input.getName(), GET_INPUT_INDEX, propInput.getName()));
202             declaredProperty.setValue(jsonObject.toJSONString());
203             GetInputValueDataDefinition getInputValueDataDefinition = new GetInputValueDataDefinition();
204             getInputValueDataDefinition.setInputId(input.getUniqueId());
205             getInputValueDataDefinition.setInputName(input.getName());
206             List<GetInputValueDataDefinition> getInputValues = declaredProperty.getGetInputValues();
207             if (getInputValues == null) {
208                 getInputValues = new ArrayList<>();
209                 declaredProperty.setGetInputValues(getInputValues);
210             }
211             getInputValues.add(getInputValueDataDefinition);
212             if (!declaredProperties.contains(declaredProperty)) {
213                 // Add property to the list if not contain in declareProperties.
214                 declaredProperties.add(declaredProperty);
215             }
216         }
217         return updatePropertiesValues(component, propertiesOwner.getUniqueId(), declaredProperties).left().map(x -> input);
218     }
219
220     private PropertiesDeclarationData createInputsAndOverridePropertiesValues(Component component, PROPERTYOWNER propertiesOwner,
221                                                                               List<ComponentInstancePropInput> propsToDeclare) {
222         List<PROPERTYTYPE> declaredProperties = new ArrayList<>();
223         List<InputDefinition> createdInputs = propsToDeclare.stream()
224             .map(propInput -> declarePropertyInput(component, propertiesOwner, declaredProperties, propInput)).collect(Collectors.toList());
225         return new PropertiesDeclarationData(createdInputs, null, declaredProperties);
226     }
227
228     private InputDefinition declarePropertyInput(Component component, PROPERTYOWNER propertiesOwner, List<PROPERTYTYPE> declaredProperties,
229                                                  ComponentInstancePropInput propInput) {
230         PropertyDataDefinition prop = resolveProperty(declaredProperties, propInput);
231         InputDefinition inputDefinition = createInput(component, propertiesOwner, propInput, prop);
232         PROPERTYTYPE declaredProperty = createDeclaredProperty(prop);
233         if (!declaredProperties.contains(declaredProperty)) {
234             declaredProperties.add(declaredProperty);
235         }
236         addPropertiesListToInput(declaredProperty, inputDefinition);
237         return inputDefinition;
238     }
239
240     private InputDefinition createInput(Component component, PROPERTYOWNER propertiesOwner, ComponentInstancePropInput propInput,
241                                         PropertyDataDefinition prop) {
242         String generatedInputPrefix = propertiesOwner.getNormalizedName();
243         if (component.getUniqueId().equals(propInput.getParentUniqueId())) {
244             //Creating input from property create on self using add property..Do not add the prefix
245             generatedInputPrefix = null;
246         }
247         Optional<CapabilityDefinition> propertyCapability = PropertiesUtils
248             .getPropertyCapabilityOfChildInstance(propInput.getParentUniqueId(), component.getCapabilities());
249         if (propertyCapability.isPresent()) {
250             String capName = propertyCapability.get().getName();
251             if (capName.contains(".")) {
252                 capName = capName.replace(".", UNDERSCORE);
253             }
254             generatedInputPrefix =
255                 generatedInputPrefix == null || generatedInputPrefix.isEmpty() ? capName : generatedInputPrefix + UNDERSCORE + capName;
256         }
257         String generatedInputName = generateInputName(generatedInputPrefix, propInput);
258         log.debug("createInput: propOwner.uniqueId={}, propInput.parentUniqueId={}", propertiesOwner.getUniqueId(), propInput.getParentUniqueId());
259         return createInputFromProperty(component.getUniqueId(), propertiesOwner, generatedInputName, propInput, prop);
260     }
261
262     private String generateInputName(String inputName, ComponentInstancePropInput propInput) {
263         String declaredInputName;
264         String[] parsedPropNames = propInput.getParsedPropNames();
265         if (parsedPropNames != null) {
266             declaredInputName = handleInputName(inputName, parsedPropNames);
267         } else {
268             String[] propName = {propInput.getName()};
269             declaredInputName = handleInputName(inputName, propName);
270         }
271         return declaredInputName;
272     }
273
274     private String handleInputName(String inputName, String[] parsedPropNames) {
275         StringBuilder prefix = new StringBuilder();
276         int startingIndex;
277         if (Objects.isNull(inputName)) {
278             prefix.append(parsedPropNames[0]);
279             startingIndex = 1;
280         } else {
281             prefix.append(inputName);
282             startingIndex = 0;
283         }
284         while (startingIndex < parsedPropNames.length) {
285             prefix.append(UNDERSCORE);
286             prefix.append(parsedPropNames[startingIndex]);
287             startingIndex++;
288         }
289         return prefix.toString();
290     }
291
292     private PropertyDataDefinition resolveProperty(List<PROPERTYTYPE> propertiesToCreate, ComponentInstancePropInput propInput) {
293         Optional<PROPERTYTYPE> resolvedProperty = propertiesToCreate.stream().filter(p -> p.getName().equals(propInput.getName())).findFirst();
294         return resolvedProperty.isPresent() ? resolvedProperty.get() : propInput;
295     }
296
297     InputDefinition createInputFromProperty(String componentId, PROPERTYOWNER propertiesOwner, String inputName, ComponentInstancePropInput propInput,
298                                             PropertyDataDefinition prop) {
299         String propertiesName = propInput.getPropertiesName();
300         PropertyDefinition selectedProp = propInput.getInput();
301         String[] parsedPropNames = propInput.getParsedPropNames();
302         InputDefinition input;
303         boolean complexProperty = false;
304         if (propertiesName != null && !propertiesName.isEmpty() && selectedProp != null) {
305             complexProperty = true;
306             input = new InputDefinition(selectedProp);
307             input.setDefaultValue(selectedProp.getValue());
308         } else {
309             input = new InputDefinition(prop);
310             input.setDefaultValue(prop.getValue());
311         }
312         input.setName(inputName);
313         input.setUniqueId(UniqueIdBuilder.buildPropertyUniqueId(componentId, input.getName()));
314         input.setInputPath(propertiesName);
315         input.setInstanceUniqueId(propertiesOwner.getUniqueId());
316         input.setPropertyId(propInput.getUniqueId());
317         if (Objects.isNull(input.getSubPropertyInputPath()) || (StringUtils.isNotEmpty(propertiesName) && input.getSubPropertyInputPath()
318             .substring(input.getSubPropertyInputPath().lastIndexOf('#')).equals(propertiesName.substring(propertiesName.lastIndexOf('#'))))) {
319             input.setParentPropertyType(propInput.getType());
320             input.setSubPropertyInputPath(propertiesName);
321         }
322         changePropertyValueToGetInputValue(parsedPropNames, input, prop, complexProperty);
323         if (prop instanceof IComponentInstanceConnectedElement) {
324             ((IComponentInstanceConnectedElement) prop).setComponentInstanceId(propertiesOwner.getUniqueId());
325             ((IComponentInstanceConnectedElement) prop).setComponentInstanceName(propertiesOwner.getName());
326         }
327         return input;
328     }
329
330     private void changePropertyValueToGetInputValue(String[] parsedPropNames, InputDefinition input, PropertyDataDefinition prop,
331                                                     boolean complexProperty) {
332         JSONObject jsonObject = new JSONObject();
333         final String value = prop.getValue();
334         final String inputName = input.getName();
335         if (value == null || value.isEmpty()) {
336             if (complexProperty) {
337                 jsonObject = createJSONValueForProperty(parsedPropNames.length - 1, parsedPropNames, jsonObject, inputName);
338                 prop.setValue(jsonObject.toJSONString());
339             } else {
340                 jsonObject.put(GET_INPUT, inputName);
341                 prop.setValue(jsonObject.toJSONString());
342             }
343         } else {
344             final Object objValue = new Yaml().load(value);
345             if (objValue instanceof Map || objValue instanceof List) {
346                 if (!complexProperty) {
347                     jsonObject.put(GET_INPUT, inputName);
348                     prop.setValue(jsonObject.toJSONString());
349                 } else {
350                     final Map<String, Object> mappedToscaTemplate = (Map<String, Object>) objValue;
351                     createInputValue(mappedToscaTemplate, 1, parsedPropNames, inputName);
352                     final String json = gson.toJson(mappedToscaTemplate);
353                     prop.setValue(json);
354                 }
355             } else {
356                 jsonObject.put(GET_INPUT, inputName);
357                 prop.setValue(jsonObject.toJSONString());
358             }
359         }
360         if (CollectionUtils.isEmpty(prop.getGetInputValues())) {
361             prop.setGetInputValues(new ArrayList<>());
362         }
363         final List<GetInputValueDataDefinition> getInputValues = prop.getGetInputValues();
364         final GetInputValueDataDefinition getInputValueDataDefinition = new GetInputValueDataDefinition();
365         getInputValueDataDefinition.setInputId(input.getUniqueId());
366         getInputValueDataDefinition.setInputName(inputName);
367         getInputValues.add(getInputValueDataDefinition);
368     }
369
370     private JSONObject createJSONValueForProperty(int i, String[] parsedPropNames, JSONObject ooj, String inputName) {
371         while (i >= 1) {
372             if (i == parsedPropNames.length - 1) {
373                 JSONObject jobProp = new JSONObject();
374                 jobProp.put(GET_INPUT, inputName);
375                 ooj.put(parsedPropNames[i], jobProp);
376                 i--;
377                 return createJSONValueForProperty(i, parsedPropNames, ooj, inputName);
378             } else {
379                 JSONObject res = new JSONObject();
380                 res.put(parsedPropNames[i], ooj);
381                 i--;
382                 res = createJSONValueForProperty(i, parsedPropNames, res, inputName);
383                 return res;
384             }
385         }
386         return ooj;
387     }
388
389     private Map<String, Object> createInputValue(Map<String, Object> lhm1, int index, String[] inputNames, String inputName) {
390         while (index < inputNames.length) {
391             if (lhm1.containsKey(inputNames[index])) {
392                 Object value = lhm1.get(inputNames[index]);
393                 if (value instanceof Map) {
394                     if (index == inputNames.length - 1) {
395                         ((Map) value).put(GET_INPUT, inputName);
396                         return (Map) value;
397                     } else {
398                         index++;
399                         return createInputValue((Map) value, index, inputNames, inputName);
400                     }
401                 } else {
402                     Map<String, Object> jobProp = new HashMap<>();
403                     if (index == inputNames.length - 1) {
404                         jobProp.put(GET_INPUT, inputName);
405                         lhm1.put(inputNames[index], jobProp);
406                         return lhm1;
407                     } else {
408                         lhm1.put(inputNames[index], jobProp);
409                         index++;
410                         return createInputValue(jobProp, index, inputNames, inputName);
411                     }
412                 }
413             } else {
414                 Map<String, Object> jobProp = new HashMap<>();
415                 lhm1.put(inputNames[index], jobProp);
416                 if (index == inputNames.length - 1) {
417                     jobProp.put(GET_INPUT, inputName);
418                     return jobProp;
419                 } else {
420                     index++;
421                     return createInputValue(jobProp, index, inputNames, inputName);
422                 }
423             }
424         }
425         return lhm1;
426     }
427
428     Either<InputDefinition, ResponseFormat> prepareValueBeforeDelete(InputDefinition inputForDelete, PropertyDataDefinition inputValue,
429                                                                      List<String> pathOfComponentInstances) {
430         Either<InputDefinition, ResponseFormat> deleteEither = prepareValueBeforeDelete(inputForDelete, inputValue);
431         Either<String, JanusGraphOperationStatus> findDefaultValue = propertyOperation
432             .findDefaultValueFromSecondPosition(pathOfComponentInstances, inputValue.getUniqueId(), (String) inputValue.getDefaultValue());
433         if (findDefaultValue.isRight()) {
434             deleteEither = Either.right(componentsUtils.getResponseFormat(componentsUtils
435                 .convertFromStorageResponse(DaoStatusConverter.convertJanusGraphStatusToStorageStatus(findDefaultValue.right().value()))));
436             return deleteEither;
437         }
438         String defaultValue = findDefaultValue.left().value();
439         inputValue.setDefaultValue(defaultValue);
440         log.debug("The returned default value in ResourceInstanceProperty is {}", defaultValue);
441         return deleteEither;
442     }
443
444     Either<InputDefinition, ResponseFormat> prepareValueBeforeDeleteOfCapProp(InputDefinition inputForDelete, PropertyDataDefinition inputValue) {
445         Either<InputDefinition, ResponseFormat> deleteEither = prepareValueBeforeDelete(inputForDelete, inputValue);
446         inputValue.setDefaultValue(inputForDelete.getDefaultValue());
447         log.debug("The returned default value in ResourceInstanceProperty is {}", inputForDelete.getDefaultValue());
448         return deleteEither;
449     }
450
451     private Either<InputDefinition, ResponseFormat> prepareValueBeforeDelete(InputDefinition inputForDelete, PropertyDataDefinition inputValue) {
452         Either<InputDefinition, ResponseFormat> deleteEither = Either.left(inputForDelete);
453         String value = inputValue.getValue();
454         Map<String, Object> mappedToscaTemplate = (Map<String, Object>) new Yaml().load(value);
455         resetInputName(mappedToscaTemplate, inputForDelete.getName());
456         value = "";
457         if (!mappedToscaTemplate.isEmpty()) {
458             Either result = cleanNestedMap(mappedToscaTemplate, true);
459             Map modifiedMappedToscaTemplate = mappedToscaTemplate;
460             if (result.isLeft()) {
461                 modifiedMappedToscaTemplate = (Map) result.left().value();
462             } else {
463                 log.warn("Map cleanup failed -> {}", result.right().value());    //continue, don't break operation
464             }
465             value = gson.toJson(modifiedMappedToscaTemplate);
466         }
467         inputValue.setValue(value);
468         List<GetInputValueDataDefinition> getInputsValues = inputValue.getGetInputValues();
469         if (getInputsValues != null && !getInputsValues.isEmpty()) {
470             Optional<GetInputValueDataDefinition> op = getInputsValues.stream().filter(gi -> gi.getInputId().equals(inputForDelete.getUniqueId()))
471                 .findAny();
472             op.ifPresent(getInputsValues::remove);
473         }
474         inputValue.setGetInputValues(getInputsValues);
475         return deleteEither;
476     }
477
478     private void resetInputName(Map<String, Object> lhm1, String inputName) {
479         for (Map.Entry<String, Object> entry : lhm1.entrySet()) {
480             String key = entry.getKey();
481             Object value = entry.getValue();
482             if (value instanceof String && ((String) value).equalsIgnoreCase(inputName) && key.equals(GET_INPUT)) {
483                 lhm1.remove(key);
484             } else if (value instanceof Map) {
485                 Map<String, Object> subMap = (Map<String, Object>) value;
486                 resetInputName(subMap, inputName);
487             } else if (value instanceof List && ((List) value).contains(inputName) && key.equals(GET_INPUT)) {
488                 lhm1.remove(key);
489             }
490         }
491     }
492
493     private Either cleanNestedMap(Map mappedToscaTemplate, boolean deepClone) {
494         if (MapUtils.isNotEmpty(mappedToscaTemplate)) {
495             if (deepClone) {
496                 if (!(mappedToscaTemplate instanceof HashMap)) {
497                     return Either.right("expecting mappedToscaTemplate as HashMap ,recieved " + mappedToscaTemplate.getClass().getSimpleName());
498                 } else {
499                     mappedToscaTemplate = (HashMap) ((HashMap) mappedToscaTemplate).clone();
500                 }
501             }
502             return Either.left((Map) cleanEmptyNestedValuesInMap(mappedToscaTemplate, LOOP_PROTECTION_LEVEL));
503         } else {
504             log.debug("mappedToscaTemplate is empty ");
505             return Either.right("mappedToscaTemplate is empty ");
506         }
507     }
508
509     /*        Mutates the object
510      *        Tail recurse -> traverse the tosca elements and remove nested empty map properties
511      *        this only handles nested maps, other objects are left untouched (even a Set containing a map) since behaviour is unexpected
512      *
513      *        @param  toscaElement - expected map of tosca values
514      *        @return mutated @param toscaElement , where empty maps are deleted , return null for empty map.
515      **/
516     private Object cleanEmptyNestedValuesInMap(Object toscaElement, short loopProtectionLevel) {
517         if (loopProtectionLevel <= 0 || toscaElement == null || !(toscaElement instanceof Map)) {
518             return toscaElement;
519         }
520         if (MapUtils.isNotEmpty((Map) toscaElement)) {
521             Object ret;
522             Set<Object> keysToRemove = new HashSet<>();                                                                 // use different set to avoid ConcurrentModificationException
523             for (Object key : ((Map) toscaElement).keySet()) {
524                 Object value = ((Map) toscaElement).get(key);
525                 ret = cleanEmptyNestedValuesInMap(value, --loopProtectionLevel);
526                 if (ret == null) {
527                     keysToRemove.add(key);
528                 }
529             }
530             Collection set = ((Map) toscaElement).keySet();
531             if (CollectionUtils.isNotEmpty(set)) {
532                 set.removeAll(keysToRemove);
533             }
534             if (isEmptyNestedMap(toscaElement)) {
535                 return null;
536             }
537         } else {
538             return null;
539         }
540         return toscaElement;
541     }
542
543     //ignores other collection objects
544     private boolean isEmptyNestedMap(Object element) {
545         boolean isEmpty = true;
546         if (element != null) {
547             if (element instanceof Map) {
548                 final Map map = (Map) element;
549                 if (MapUtils.isNotEmpty(map)) {
550                     for (final Object key : map.keySet()) {
551                         final Object value = map.get(key);
552                         isEmpty &= isEmptyNestedMap(value);
553                     }
554                 }
555             } else {
556                 isEmpty = false;
557             }
558         }
559         return isEmpty;
560     }
561     //@returns true if map nested maps are all empty
562
563     private class PropertiesDeclarationData {
564
565         private List<InputDefinition> inputsToCreate;
566         private List<PolicyDefinition> policiesToCreate;
567         private List<PROPERTYTYPE> propertiesToUpdate;
568
569         PropertiesDeclarationData(List<InputDefinition> inputsToCreate, List<PolicyDefinition> policiesToCreate,
570                                   List<PROPERTYTYPE> propertiesToUpdate) {
571             this.inputsToCreate = inputsToCreate;
572             this.policiesToCreate = policiesToCreate;
573             this.propertiesToUpdate = propertiesToUpdate;
574         }
575
576         List<InputDefinition> getInputsToCreate() {
577             return inputsToCreate;
578         }
579
580         public List<PolicyDefinition> getPoliciesToCreate() {
581             return policiesToCreate;
582         }
583
584         List<PROPERTYTYPE> getPropertiesToUpdate() {
585             return propertiesToUpdate;
586         }
587     }
588 }