2 * ============LICENSE_START=======================================================
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
11 * http://www.apache.org/licenses/LICENSE-2.0
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=========================================================
20 package org.openecomp.sdc.be.components.property;
22 import static org.openecomp.sdc.common.api.Constants.GET_INPUT;
23 import static org.openecomp.sdc.common.api.Constants.GET_POLICY;
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;
34 import java.util.Objects;
35 import java.util.Optional;
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;
64 public abstract class DefaultPropertyDeclarator<PROPERTYOWNER extends PropertiesOwner, PROPERTYTYPE extends PropertyDataDefinition> implements
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;
75 public DefaultPropertyDeclarator(ComponentsUtils componentsUtils, PropertyOperation propertyOperation) {
76 this.componentsUtils = componentsUtils;
77 this.propertyOperation = propertyOperation;
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(),
85 return resolvePropertiesOwner(component, propertiesOwnerId)
86 .map(propertyOwner -> declarePropertiesAsInputs(component, propertyOwner, propsToDeclare))
87 .orElse(Either.right(onPropertiesOwnerNotFound(component.getUniqueId(), propertiesOwnerId)));
90 protected abstract PROPERTYTYPE createDeclaredProperty(PropertyDataDefinition prop);
92 protected abstract Either<?, StorageOperationStatus> updatePropertiesValues(Component component, String propertiesOwnerId,
93 List<PROPERTYTYPE> properties);
95 protected abstract Optional<PROPERTYOWNER> resolvePropertiesOwner(Component component, String propertiesOwnerId);
97 protected abstract void addPropertiesListToInput(PROPERTYTYPE declaredProp, InputDefinition input);
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)));
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(),
115 Optional<PROPERTYOWNER> propertyOwner = resolvePropertiesOwner(component, propertiesOwnerId);
116 if (propertyOwner.isPresent()) {
117 return declarePropertiesAsListInput(component, propertyOwner.get(), propsToDeclare, input);
119 return Either.right(onPropertiesOwnerNotFound(component.getUniqueId(), propertiesOwnerId));
123 public StorageOperationStatus unDeclarePropertiesAsPolicies(Component component, PolicyDefinition policy) {
124 return StorageOperationStatus.OK;
127 private Either<List<PolicyDefinition>, StorageOperationStatus> declarePropertiesAsPolicies(Component component, PROPERTYOWNER propertiesOwner,
128 List<ComponentInstancePropInput> propsToDeclare) {
129 PropertiesDeclarationData policyProperties = createPoliciesAndOverridePropertiesValues(propertiesOwner.getUniqueId(), propertiesOwner,
131 return updatePropertiesValues(component, propertiesOwner.getUniqueId(), policyProperties.getPropertiesToUpdate()).left()
132 .map(updatePropsRes -> policyProperties.getPoliciesToCreate());
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;
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());
147 private PropertiesDeclarationData createPoliciesAndOverridePropertiesValues(String componentId, PROPERTYOWNER propertiesOwner,
148 List<ComponentInstancePropInput> propsToDeclare) {
149 List<PROPERTYTYPE> declaredProperties = new ArrayList<>();
150 List<PolicyDefinition> policies = new ArrayList<>();
151 propsToDeclare.forEach(property -> policies.add(declarePropertyPolicy(componentId, declaredProperties, property)));
152 return new PropertiesDeclarationData(null, policies, declaredProperties);
155 private PolicyDefinition declarePropertyPolicy(String componentId, List<PROPERTYTYPE> declaredProperties, ComponentInstancePropInput propInput) {
156 PropertyDataDefinition prop = resolveProperty(declaredProperties, propInput);
157 propInput.setOwnerId(null);
158 propInput.setParentUniqueId(null);
159 PolicyDefinition policyDefinition = new PolicyDefinition(prop);
160 policyDefinition.setUniqueId(UniqueIdBuilder.buildPolicyUniqueId(componentId, prop.getName()));
161 policyDefinition.setInputPath(prop.getName());
162 policyDefinition.setInstanceUniqueId(componentId);
163 policyDefinition.setPropertyId(prop.getUniqueId());
164 changePropertyValueToGetPolicy(prop, policyDefinition);
165 PROPERTYTYPE declaredProperty = createDeclaredProperty(prop);
166 if (!declaredProperties.contains(declaredProperty)) {
167 declaredProperties.add(declaredProperty);
169 return policyDefinition;
172 private void changePropertyValueToGetPolicy(PropertyDataDefinition prop, PolicyDefinition policyDefinition) {
173 JSONObject jsonObject = new JSONObject();
174 String origValue = Objects.isNull(prop.getValue()) ? prop.getDefaultValue() : prop.getValue();
175 jsonObject.put(GET_POLICY, null);
176 prop.setValue(jsonObject.toJSONString());
177 policyDefinition.setValue(jsonObject.toJSONString());
178 if (CollectionUtils.isEmpty(prop.getGetPolicyValues())) {
179 prop.setGetPolicyValues(new ArrayList<>());
181 List<GetPolicyValueDataDefinition> getPolicyValues = prop.getGetPolicyValues();
182 GetPolicyValueDataDefinition getPolicyValueDataDefinition = new GetPolicyValueDataDefinition();
183 getPolicyValueDataDefinition.setPolicyId(policyDefinition.getUniqueId());
184 getPolicyValueDataDefinition.setPropertyName(prop.getName());
185 getPolicyValueDataDefinition.setOrigPropertyValue(origValue);
186 getPolicyValues.add(getPolicyValueDataDefinition);
187 policyDefinition.setGetPolicyValues(getPolicyValues);
190 private Either<InputDefinition, StorageOperationStatus> declarePropertiesAsListInput(Component component, PROPERTYOWNER propertiesOwner,
191 List<ComponentInstancePropInput> propsToDeclare,
192 InputDefinition input) {
193 List<PROPERTYTYPE> declaredProperties = new ArrayList<>();
194 for (ComponentInstancePropInput propInput : propsToDeclare) {
195 if (StringUtils.isNotEmpty(propInput.getPropertiesName()) && propInput.getInput() != null) {
196 // sub-property in complex type is checked on UI. currently not supported.
197 log.debug("skip propInput (propertiesName={}) currently not supported.", propInput.getPropertiesName());
200 PROPERTYTYPE declaredProperty = createDeclaredProperty(propInput);
201 JSONObject jsonObject = new JSONObject();
202 jsonObject.put(GET_INPUT, Arrays.asList(input.getName(), GET_INPUT_INDEX, propInput.getName()));
203 declaredProperty.setValue(jsonObject.toJSONString());
204 GetInputValueDataDefinition getInputValueDataDefinition = new GetInputValueDataDefinition();
205 getInputValueDataDefinition.setInputId(input.getUniqueId());
206 getInputValueDataDefinition.setInputName(input.getName());
207 List<GetInputValueDataDefinition> getInputValues = declaredProperty.getGetInputValues();
208 if (getInputValues == null) {
209 getInputValues = new ArrayList<>();
210 declaredProperty.setGetInputValues(getInputValues);
212 getInputValues.add(getInputValueDataDefinition);
213 if (!declaredProperties.contains(declaredProperty)) {
214 // Add property to the list if not contain in declareProperties.
215 declaredProperties.add(declaredProperty);
218 return updatePropertiesValues(component, propertiesOwner.getUniqueId(), declaredProperties).left().map(x -> input);
221 private PropertiesDeclarationData createInputsAndOverridePropertiesValues(Component component, PROPERTYOWNER propertiesOwner,
222 List<ComponentInstancePropInput> propsToDeclare) {
223 List<PROPERTYTYPE> declaredProperties = new ArrayList<>();
224 List<InputDefinition> createdInputs = propsToDeclare.stream()
225 .map(propInput -> declarePropertyInput(component, propertiesOwner, declaredProperties, propInput)).collect(Collectors.toList());
226 return new PropertiesDeclarationData(createdInputs, null, declaredProperties);
229 private InputDefinition declarePropertyInput(Component component, PROPERTYOWNER propertiesOwner, List<PROPERTYTYPE> declaredProperties,
230 ComponentInstancePropInput propInput) {
231 PropertyDataDefinition prop = resolveProperty(declaredProperties, propInput);
232 InputDefinition inputDefinition = createInput(component, propertiesOwner, propInput, prop);
233 PROPERTYTYPE declaredProperty = createDeclaredProperty(prop);
234 if (!declaredProperties.contains(declaredProperty)) {
235 declaredProperties.add(declaredProperty);
237 addPropertiesListToInput(declaredProperty, inputDefinition);
238 return inputDefinition;
241 private InputDefinition createInput(Component component, PROPERTYOWNER propertiesOwner, ComponentInstancePropInput propInput,
242 PropertyDataDefinition prop) {
243 String generatedInputPrefix = propertiesOwner.getNormalizedName();
244 if (propertiesOwner.getUniqueId().equals(propInput.getParentUniqueId())) {
245 //Creating input from property create on self using add property..Do not add the prefix
246 generatedInputPrefix = null;
248 Optional<CapabilityDefinition> propertyCapability = PropertiesUtils
249 .getPropertyCapabilityOfChildInstance(propInput.getParentUniqueId(), component.getCapabilities());
250 if (propertyCapability.isPresent()) {
251 String capName = propertyCapability.get().getName();
252 if (capName.contains(".")) {
253 capName = capName.replaceAll("\\.", UNDERSCORE);
255 generatedInputPrefix =
256 generatedInputPrefix == null || generatedInputPrefix.isEmpty() ? capName : generatedInputPrefix + UNDERSCORE + capName;
258 String generatedInputName = generateInputName(generatedInputPrefix, propInput);
259 log.debug("createInput: propOwner.uniqueId={}, propInput.parentUniqueId={}", propertiesOwner.getUniqueId(), propInput.getParentUniqueId());
260 return createInputFromProperty(component.getUniqueId(), propertiesOwner, generatedInputName, propInput, prop);
263 private String generateInputName(String inputName, ComponentInstancePropInput propInput) {
264 String declaredInputName;
265 String[] parsedPropNames = propInput.getParsedPropNames();
266 if (parsedPropNames != null) {
267 declaredInputName = handleInputName(inputName, parsedPropNames);
269 String[] propName = {propInput.getName()};
270 declaredInputName = handleInputName(inputName, propName);
272 return declaredInputName;
275 private String handleInputName(String inputName, String[] parsedPropNames) {
276 StringBuilder prefix = new StringBuilder();
278 if (Objects.isNull(inputName)) {
279 prefix.append(parsedPropNames[0]);
282 prefix.append(inputName);
285 while (startingIndex < parsedPropNames.length) {
286 prefix.append(UNDERSCORE);
287 prefix.append(parsedPropNames[startingIndex]);
290 return prefix.toString();
293 private PropertyDataDefinition resolveProperty(List<PROPERTYTYPE> propertiesToCreate, ComponentInstancePropInput propInput) {
294 Optional<PROPERTYTYPE> resolvedProperty = propertiesToCreate.stream().filter(p -> p.getName().equals(propInput.getName())).findFirst();
295 return resolvedProperty.isPresent() ? resolvedProperty.get() : propInput;
298 InputDefinition createInputFromProperty(String componentId, PROPERTYOWNER propertiesOwner, String inputName, ComponentInstancePropInput propInput,
299 PropertyDataDefinition prop) {
300 String propertiesName = propInput.getPropertiesName();
301 PropertyDefinition selectedProp = propInput.getInput();
302 String[] parsedPropNames = propInput.getParsedPropNames();
303 InputDefinition input;
304 boolean complexProperty = false;
305 if (propertiesName != null && !propertiesName.isEmpty() && selectedProp != null) {
306 complexProperty = true;
307 input = new InputDefinition(selectedProp);
308 input.setDefaultValue(selectedProp.getValue());
310 input = new InputDefinition(prop);
311 input.setDefaultValue(prop.getValue());
313 input.setName(inputName);
314 input.setUniqueId(UniqueIdBuilder.buildPropertyUniqueId(componentId, input.getName()));
315 input.setInputPath(propertiesName);
316 input.setInstanceUniqueId(propertiesOwner.getUniqueId());
317 input.setPropertyId(propInput.getUniqueId());
318 if (Objects.isNull(input.getSubPropertyInputPath()) || (Objects.nonNull(propertiesName) && input.getSubPropertyInputPath()
319 .substring(input.getSubPropertyInputPath().lastIndexOf('#')).equals(propertiesName.substring(propertiesName.lastIndexOf('#'))))) {
320 input.setParentPropertyType(propInput.getType());
321 input.setSubPropertyInputPath(propertiesName);
323 changePropertyValueToGetInputValue(inputName, parsedPropNames, input, prop, complexProperty);
324 if (prop instanceof IComponentInstanceConnectedElement) {
325 ((IComponentInstanceConnectedElement) prop).setComponentInstanceId(propertiesOwner.getUniqueId());
326 ((IComponentInstanceConnectedElement) prop).setComponentInstanceName(propertiesOwner.getName());
331 private void changePropertyValueToGetInputValue(String inputName, String[] parsedPropNames, InputDefinition input, PropertyDataDefinition prop,
332 boolean complexProperty) {
333 JSONObject jsonObject = new JSONObject();
334 String value = prop.getValue();
335 if (value == null || value.isEmpty()) {
336 if (complexProperty) {
337 jsonObject = createJSONValueForProperty(parsedPropNames.length - 1, parsedPropNames, jsonObject, inputName);
338 prop.setValue(jsonObject.toJSONString());
340 jsonObject.put(GET_INPUT, input.getName());
341 prop.setValue(jsonObject.toJSONString());
344 Object objValue = new Yaml().load(value);
345 if (objValue instanceof Map || objValue instanceof List) {
346 if (!complexProperty) {
347 jsonObject.put(GET_INPUT, input.getName());
348 prop.setValue(jsonObject.toJSONString());
350 Map<String, Object> mappedToscaTemplate = (Map<String, Object>) objValue;
351 createInputValue(mappedToscaTemplate, 1, parsedPropNames, inputName);
352 String json = gson.toJson(mappedToscaTemplate);
356 jsonObject.put(GET_INPUT, input.getName());
357 prop.setValue(jsonObject.toJSONString());
360 if (CollectionUtils.isEmpty(prop.getGetInputValues())) {
361 prop.setGetInputValues(new ArrayList<>());
363 List<GetInputValueDataDefinition> getInputValues = prop.getGetInputValues();
364 GetInputValueDataDefinition getInputValueDataDefinition = new GetInputValueDataDefinition();
365 getInputValueDataDefinition.setInputId(input.getUniqueId());
366 getInputValueDataDefinition.setInputName(input.getName());
367 getInputValues.add(getInputValueDataDefinition);
370 private JSONObject createJSONValueForProperty(int i, String[] parsedPropNames, JSONObject ooj, String inputName) {
372 if (i == parsedPropNames.length - 1) {
373 JSONObject jobProp = new JSONObject();
374 jobProp.put(GET_INPUT, inputName);
375 ooj.put(parsedPropNames[i], jobProp);
377 return createJSONValueForProperty(i, parsedPropNames, ooj, inputName);
379 JSONObject res = new JSONObject();
380 res.put(parsedPropNames[i], ooj);
382 res = createJSONValueForProperty(i, parsedPropNames, res, inputName);
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);
399 return createInputValue((Map) value, index, inputNames, inputName);
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);
408 lhm1.put(inputNames[index], jobProp);
410 return createInputValue(jobProp, index, inputNames, inputName);
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);
421 return createInputValue(jobProp, index, inputNames, inputName);
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()))));
438 String defaultValue = findDefaultValue.left().value();
439 inputValue.setDefaultValue(defaultValue);
440 log.debug("The returned default value in ResourceInstanceProperty is {}", defaultValue);
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());
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());
457 if (!mappedToscaTemplate.isEmpty()) {
458 Either result = cleanNestedMap(mappedToscaTemplate, true);
459 Map modifiedMappedToscaTemplate = mappedToscaTemplate;
460 if (result.isLeft()) {
461 modifiedMappedToscaTemplate = (Map) result.left().value();
463 log.warn("Map cleanup failed -> " + result.right().value()
464 .toString()); //continue, don't break operation
466 value = gson.toJson(modifiedMappedToscaTemplate);
468 inputValue.setValue(value);
469 List<GetInputValueDataDefinition> getInputsValues = inputValue.getGetInputValues();
470 if (getInputsValues != null && !getInputsValues.isEmpty()) {
471 Optional<GetInputValueDataDefinition> op = getInputsValues.stream().filter(gi -> gi.getInputId().equals(inputForDelete.getUniqueId()))
473 op.ifPresent(getInputsValues::remove);
475 inputValue.setGetInputValues(getInputsValues);
479 private void resetInputName(Map<String, Object> lhm1, String inputName) {
480 for (Map.Entry<String, Object> entry : lhm1.entrySet()) {
481 String key = entry.getKey();
482 Object value = entry.getValue();
483 if (value instanceof String && ((String) value).equalsIgnoreCase(inputName) && key.equals(GET_INPUT)) {
485 } else if (value instanceof Map) {
486 Map<String, Object> subMap = (Map<String, Object>) value;
487 resetInputName(subMap, inputName);
488 } else if (value instanceof List && ((List) value).contains(inputName) && key.equals(GET_INPUT)) {
494 private Either cleanNestedMap(Map mappedToscaTemplate, boolean deepClone) {
495 if (MapUtils.isNotEmpty(mappedToscaTemplate)) {
497 if (!(mappedToscaTemplate instanceof HashMap)) {
498 return Either.right("expecting mappedToscaTemplate as HashMap ,recieved " + mappedToscaTemplate.getClass().getSimpleName());
500 mappedToscaTemplate = (HashMap) ((HashMap) mappedToscaTemplate).clone();
503 return Either.left((Map) cleanEmptyNestedValuesInMap(mappedToscaTemplate, LOOP_PROTECTION_LEVEL));
505 log.debug("mappedToscaTemplate is empty ");
506 return Either.right("mappedToscaTemplate is empty ");
510 /* Mutates the object
511 * Tail recurse -> traverse the tosca elements and remove nested empty map properties
512 * this only handles nested maps, other objects are left untouched (even a Set containing a map) since behaviour is unexpected
514 * @param toscaElement - expected map of tosca values
515 * @return mutated @param toscaElement , where empty maps are deleted , return null for empty map.
517 private Object cleanEmptyNestedValuesInMap(Object toscaElement, short loopProtectionLevel) {
518 if (loopProtectionLevel <= 0 || toscaElement == null || !(toscaElement instanceof Map)) {
521 if (MapUtils.isNotEmpty((Map) toscaElement)) {
523 Set<Object> keysToRemove = new HashSet<>(); // use different set to avoid ConcurrentModificationException
524 for (Object key : ((Map) toscaElement).keySet()) {
525 Object value = ((Map) toscaElement).get(key);
526 ret = cleanEmptyNestedValuesInMap(value, --loopProtectionLevel);
528 keysToRemove.add(key);
531 Collection set = ((Map) toscaElement).keySet();
532 if (CollectionUtils.isNotEmpty(set)) {
533 set.removeAll(keysToRemove);
535 if (isEmptyNestedMap(toscaElement)) {
544 //ignores other collection objects
545 private boolean isEmptyNestedMap(Object element) {
546 boolean isEmpty = true;
547 if (element != null) {
548 if (element instanceof Map) {
549 if (MapUtils.isEmpty((Map) element)) {
552 for (Object key : ((Map) (element)).keySet()) {
553 Object value = ((Map) (element)).get(key);
554 isEmpty &= isEmptyNestedMap(value);
563 //@returns true iff map nested maps are all empty
565 private class PropertiesDeclarationData {
567 private List<InputDefinition> inputsToCreate;
568 private List<PolicyDefinition> policiesToCreate;
569 private List<PROPERTYTYPE> propertiesToUpdate;
571 PropertiesDeclarationData(List<InputDefinition> inputsToCreate, List<PolicyDefinition> policiesToCreate,
572 List<PROPERTYTYPE> propertiesToUpdate) {
573 this.inputsToCreate = inputsToCreate;
574 this.policiesToCreate = policiesToCreate;
575 this.propertiesToUpdate = propertiesToUpdate;
578 List<InputDefinition> getInputsToCreate() {
579 return inputsToCreate;
582 public List<PolicyDefinition> getPoliciesToCreate() {
583 return policiesToCreate;
586 List<PROPERTYTYPE> getPropertiesToUpdate() {
587 return propertiesToUpdate;