[SDC] rebase 1710 code
[sdc.git] / catalog-be / src / main / java / org / openecomp / sdc / be / components / impl / InputsBusinessLogic.java
1 /*-
2  * ============LICENSE_START=======================================================
3  * SDC
4  * ================================================================================
5  * Copyright (C) 2017 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
21 package org.openecomp.sdc.be.components.impl;
22
23 import java.util.*;
24 import java.util.Map.Entry;
25 import java.util.function.BiConsumer;
26 import java.util.stream.Collectors;
27
28 import jline.internal.Log;
29 import org.apache.commons.collections.CollectionUtils;
30 import org.apache.commons.collections.MapUtils;
31 import org.json.simple.JSONObject;
32 import org.openecomp.sdc.be.components.validation.ComponentValidations;
33 import org.openecomp.sdc.be.config.BeEcompErrorManager;
34 import org.openecomp.sdc.be.config.BeEcompErrorManager.ErrorSeverity;
35 import org.openecomp.sdc.be.dao.api.ActionStatus;
36 import org.openecomp.sdc.be.dao.titan.TitanOperationStatus;
37 import org.openecomp.sdc.be.datatypes.elements.GetInputValueDataDefinition;
38 import org.openecomp.sdc.be.datatypes.elements.PropertyDataDefinition;
39 import org.openecomp.sdc.be.datatypes.elements.SchemaDefinition;
40 import org.openecomp.sdc.be.datatypes.enums.ComponentTypeEnum;
41 import org.openecomp.sdc.be.datatypes.tosca.ToscaDataDefinition;
42 import org.openecomp.sdc.be.model.ComponentInstInputsMap;
43 import org.openecomp.sdc.be.model.ComponentInstance;
44 import org.openecomp.sdc.be.model.ComponentInstanceInput;
45 import org.openecomp.sdc.be.model.ComponentInstancePropInput;
46 import org.openecomp.sdc.be.model.ComponentInstanceProperty;
47 import org.openecomp.sdc.be.model.ComponentParametersView;
48 import org.openecomp.sdc.be.model.DataTypeDefinition;
49 import org.openecomp.sdc.be.model.IComponentInstanceConnectedElement;
50 import org.openecomp.sdc.be.model.InputDefinition;
51 import org.openecomp.sdc.be.model.PropertyDefinition;
52 import org.openecomp.sdc.be.model.User;
53
54 import org.openecomp.sdc.be.model.operations.api.StorageOperationStatus;
55 import org.openecomp.sdc.be.model.operations.impl.DaoStatusConverter;
56 import org.openecomp.sdc.be.model.operations.impl.UniqueIdBuilder;
57 import org.openecomp.sdc.be.model.tosca.ToscaPropertyType;
58 import org.openecomp.sdc.be.model.tosca.converters.PropertyValueConverter;
59 import org.openecomp.sdc.exception.ResponseFormat;
60 import org.slf4j.Logger;
61 import org.slf4j.LoggerFactory;
62 import org.springframework.stereotype.Component;
63 import org.yaml.snakeyaml.Yaml;
64
65 import com.google.gson.Gson;
66
67 import fj.data.Either;
68
69 @Component("inputsBusinessLogic")
70 public class InputsBusinessLogic extends BaseBusinessLogic {
71
72         private static final String CREATE_INPUT = "CreateInput";
73         private static final String UPDATE_INPUT = "UpdateInput";
74
75         private static Logger log = LoggerFactory.getLogger(InputsBusinessLogic.class.getName());
76
77         private static final String GET_INPUT = "get_input";
78
79         private static final short LOOP_PROTECTION_LEVEL = 10 ;
80
81         private static String ASSOCIATING_INPUT_TO_PROP = "AssociatingInputToComponentInstanceProperty";
82         private Gson gson = new Gson();
83
84
85         /**
86          * associate inputs to a given component with paging
87          *
88          * @param componentId
89          * @param userId
90          * @param fromId
91          * @param amount
92          * @return
93          */
94         public Either<List<InputDefinition>, ResponseFormat> getInputs(String userId, String componentId, String fromName, int amount) {
95
96                 Either<User, ResponseFormat> resp = validateUserExists(userId, "get Inputs", false);
97
98                 if (resp.isRight()) {
99                         return Either.right(resp.right().value());
100                 }
101
102
103                 ComponentParametersView filters = new ComponentParametersView();
104                 filters.disableAll();
105                 filters.setIgnoreInputs(false);
106
107                 Either<org.openecomp.sdc.be.model.Component, StorageOperationStatus> getComponentEither = toscaOperationFacade.getToscaElement(componentId, filters);
108                 if(getComponentEither.isRight()){
109                         ActionStatus actionStatus = componentsUtils.convertFromStorageResponse(getComponentEither.right().value());
110                         log.debug("Failed to found component {}, error: {}", componentId, actionStatus.name());
111                         return Either.right(componentsUtils.getResponseFormat(actionStatus));
112
113                 }
114                 org.openecomp.sdc.be.model.Component component = getComponentEither.left().value();
115                 List<InputDefinition> inputs = component.getInputs();
116
117                 return Either.left(inputs);
118
119         }
120
121         public Either<List<ComponentInstanceInput>, ResponseFormat> getComponentInstanceInputs(String userId, String componentId, String componentInstanceId) {
122
123                 Either<User, ResponseFormat> resp = validateUserExists(userId, "get Inputs", false);
124
125                 if (resp.isRight()) {
126                         return Either.right(resp.right().value());
127                 }
128
129
130                 ComponentParametersView filters = new ComponentParametersView();
131                 filters.disableAll();
132                 filters.setIgnoreInputs(false);
133                 filters.setIgnoreComponentInstances(false);
134                 filters.setIgnoreComponentInstancesInputs(false);
135
136                 Either<org.openecomp.sdc.be.model.Component, StorageOperationStatus> getComponentEither = toscaOperationFacade.getToscaElement(componentId, filters);
137                 if(getComponentEither.isRight()){
138                         ActionStatus actionStatus = componentsUtils.convertFromStorageResponse(getComponentEither.right().value());
139                         log.debug("Failed to found component {}, error: {}", componentId, actionStatus.name());
140                         return Either.right(componentsUtils.getResponseFormat(actionStatus));
141
142                 }
143                 org.openecomp.sdc.be.model.Component component = getComponentEither.left().value();
144
145                 if(!ComponentValidations.validateComponentInstanceExist(component, componentInstanceId)){
146                         ActionStatus actionStatus = ActionStatus.COMPONENT_INSTANCE_NOT_FOUND;
147                         log.debug("Failed to found component instance inputs {}, error: {}", componentInstanceId, actionStatus.name());
148                         return Either.right(componentsUtils.getResponseFormat(actionStatus));
149                 }
150                 Map<String, List<ComponentInstanceInput>> ciInputs = Optional.ofNullable(component.getComponentInstancesInputs()).orElse(Collections.emptyMap());
151                 return Either.left(ciInputs.getOrDefault(componentInstanceId, Collections.emptyList()));
152         }
153
154         /**
155          * associate properties to a given component instance input
156          *
157          * @param instanceId
158          * @param userId
159          * @param inputId
160          * @return
161          */
162
163         public Either<List<ComponentInstanceProperty>, ResponseFormat> getComponentInstancePropertiesByInputId(String userId, String componentId, String instanceId, String inputId) {
164                 Either<User, ResponseFormat> resp = validateUserExists(userId, "get Properties by input", false);
165                 if (resp.isRight()) {
166                         return Either.right(resp.right().value());
167                 }
168                 String parentId = componentId;
169                 org.openecomp.sdc.be.model.Component component = null;
170                 ComponentParametersView filters = new ComponentParametersView();
171                 filters.disableAll();
172                 filters.setIgnoreComponentInstances(false);
173
174                 if(!instanceId.equals(inputId)){
175
176
177                         Either<org.openecomp.sdc.be.model.Component, StorageOperationStatus> getComponentEither = toscaOperationFacade.getToscaElement(parentId, filters);
178
179                         if(getComponentEither.isRight()){
180                                 ActionStatus actionStatus = componentsUtils.convertFromStorageResponse(getComponentEither.right().value());
181                                 log.debug("Failed to found component {}, error: {}", parentId, actionStatus.name());
182                                 return Either.right(componentsUtils.getResponseFormat(actionStatus));
183
184                         }
185                         component = getComponentEither.left().value();
186                         Optional<ComponentInstance> ciOp = component.getComponentInstances().stream().filter(ci ->ci.getUniqueId().equals(instanceId)).findAny();
187                         if(ciOp.isPresent()){
188                                 parentId = ciOp.get().getComponentUid();
189                         }
190
191                 }
192
193                 filters.setIgnoreInputs(false);
194
195                 filters.setIgnoreComponentInstancesProperties(false);
196                 filters.setIgnoreComponentInstancesInputs(false);
197                 filters.setIgnoreProperties(false);
198
199                 Either<org.openecomp.sdc.be.model.Component, StorageOperationStatus> getComponentEither = toscaOperationFacade.getToscaElement(parentId, filters);
200
201                 if(getComponentEither.isRight()){
202                         ActionStatus actionStatus = componentsUtils.convertFromStorageResponse(getComponentEither.right().value());
203                         log.debug("Failed to found component {}, error: {}", parentId, actionStatus.name());
204                         return Either.right(componentsUtils.getResponseFormat(actionStatus));
205
206                 }
207                 component = getComponentEither.left().value();
208
209                 Optional<InputDefinition> op = component.getInputs().stream().filter(in -> in.getUniqueId().equals(inputId)).findFirst();
210                 if(!op.isPresent()){
211                         ActionStatus actionStatus = componentsUtils.convertFromStorageResponse(getComponentEither.right().value());
212                         log.debug("Failed to found input {} under component {}, error: {}", inputId, parentId, actionStatus.name());
213                         return Either.right(componentsUtils.getResponseFormat(actionStatus));
214                 }
215
216                 return Either.left(getComponentInstancePropertiesByInputId(component, inputId));
217
218         }
219
220         public Either<InputDefinition, ResponseFormat> updateInputValue(ComponentTypeEnum componentType, String componentId, InputDefinition input, String userId, boolean shouldLockComp, boolean inTransaction) {
221
222                 Either<InputDefinition, ResponseFormat> result = null;
223                 org.openecomp.sdc.be.model.Component component = null;
224
225
226                 try {
227                         Either<User, ResponseFormat> resp = validateUserExists(userId, "get input", false);
228
229                         if (resp.isRight()) {
230                                 result = Either.right(resp.right().value());
231                                 return result;
232                         }
233
234                         ComponentParametersView componentParametersView = new ComponentParametersView();
235                         componentParametersView.disableAll();
236                         componentParametersView.setIgnoreInputs(false);
237                         componentParametersView.setIgnoreUsers(false);
238
239                         Either<? extends org.openecomp.sdc.be.model.Component, ResponseFormat> validateComponent = validateComponentExists(componentId, componentType, componentParametersView);
240
241                         if (validateComponent.isRight()) {
242                                 result = Either.right(validateComponent.right().value());
243                                 return result;
244                         }
245                         component = validateComponent.left().value();
246
247                         if (shouldLockComp) {
248                                 Either<Boolean, ResponseFormat> lockComponent = lockComponent(component, UPDATE_INPUT);
249                                 if (lockComponent.isRight()) {
250                                         result = Either.right(lockComponent.right().value());
251                                         return result;
252                                 }
253                         }
254
255                         Either<Boolean, ResponseFormat> canWork = validateCanWorkOnComponent(component, userId);
256                         if (canWork.isRight()) {
257                                 result = Either.right(canWork.right().value());
258                                 return result;
259                         }
260
261                         Either<Map<String, DataTypeDefinition>, ResponseFormat> allDataTypes = getAllDataTypes(applicationDataTypeCache);
262                         if (allDataTypes.isRight()) {
263                                 result = Either.right(allDataTypes.right().value());
264                                 return result;
265                         }
266
267                         Map<String, DataTypeDefinition> dataTypes = allDataTypes.left().value();
268
269                         Optional<InputDefinition> op = component.getInputs().stream().filter(in -> in.getUniqueId().equals(input.getUniqueId())).findFirst();
270                         if(!op.isPresent()){
271                                 ActionStatus actionStatus = ActionStatus.COMPONENT_NOT_FOUND;
272                                 log.debug("Failed to found input {} under component {}, error: {}", input.getUniqueId(), componentId, actionStatus.name());
273                                 result = Either.right(componentsUtils.getResponseFormat(actionStatus));
274                                 return result;
275                         }
276                         InputDefinition currentInput = op.get();
277
278                         String innerType = null;
279                         String propertyType = currentInput.getType();
280                         ToscaPropertyType type = ToscaPropertyType.isValidType(propertyType);
281                         log.debug("The type of the property {} is {}", currentInput.getUniqueId(), propertyType);
282
283                         if (type == ToscaPropertyType.LIST || type == ToscaPropertyType.MAP) {
284                                 SchemaDefinition def = currentInput.getSchema();
285                                 if (def == null) {
286                                         log.debug("Schema doesn't exists for property of type {}", type);
287                                         return Either.right(componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(StorageOperationStatus.INVALID_VALUE)));
288                                 }
289                                 PropertyDataDefinition propDef = def.getProperty();
290                                 if (propDef == null) {
291                                         log.debug("Property in Schema Definition inside property of type {} doesn't exist", type);
292                                         return Either.right(componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(StorageOperationStatus.INVALID_VALUE)));
293                                 }
294                                 innerType = propDef.getType();
295                         }
296                         // Specific Update Logic
297
298                         Either<Object, Boolean> isValid = propertyOperation.validateAndUpdatePropertyValue(propertyType, input.getDefaultValue(), true, innerType, allDataTypes.left().value());
299
300                         String newValue = currentInput.getDefaultValue();
301                         if (isValid.isRight()) {
302                                 Boolean res = isValid.right().value();
303                                 if (res == false) {
304                                         return Either.right(componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(DaoStatusConverter.convertTitanStatusToStorageStatus(TitanOperationStatus.ILLEGAL_ARGUMENT))));
305                                 }
306                         } else {
307                                 Object object = isValid.left().value();
308                                 if (object != null) {
309                                         newValue = object.toString();
310                                 }
311                         }
312
313                         currentInput.setDefaultValue(newValue);
314
315                         Either<InputDefinition, StorageOperationStatus> status = toscaOperationFacade.updateInputOfComponent(component, currentInput);
316
317                         if(status.isRight()){
318                                 ActionStatus actionStatus = componentsUtils.convertFromStorageResponseForResourceInstanceProperty(status.right().value());
319                                 result = Either.right(componentsUtils.getResponseFormat(actionStatus, ""));
320                                 return result;
321                         }
322
323
324                         result = Either.left(status.left().value());
325
326                         return result;
327
328
329                 }finally {
330
331                                 if (false == inTransaction) {
332
333                                         if (result == null || result.isRight()) {
334                                                 log.debug("Going to execute rollback on create group.");
335                                                 titanDao.rollback();
336                                         } else {
337                                                 log.debug("Going to execute commit on create group.");
338                                                 titanDao.commit();
339                                         }
340
341                                 }
342                                 // unlock resource
343                                 if (shouldLockComp && component != null) {
344                                         graphLockOperation.unlockComponent(componentId, componentType.getNodeType());
345                                 }
346
347                         }
348
349
350         }
351
352         public Either<List<ComponentInstanceInput>, ResponseFormat> getInputsForComponentInput(String userId, String componentId, String inputId) {
353                 Either<User, ResponseFormat> resp = validateUserExists(userId, "get Properties by input", false);
354                 if (resp.isRight()) {
355                         return Either.right(resp.right().value());
356                 }
357                 String parentId = componentId;
358                 org.openecomp.sdc.be.model.Component component = null;
359                 ComponentParametersView filters = new ComponentParametersView();
360                 filters.disableAll();
361                 filters.setIgnoreComponentInstances(false);
362                 filters.setIgnoreInputs(false);
363                 filters.setIgnoreComponentInstancesInputs(false);
364                 filters.setIgnoreProperties(false);
365
366                 Either<org.openecomp.sdc.be.model.Component, StorageOperationStatus> getComponentEither = toscaOperationFacade.getToscaElement(parentId, filters);
367
368                 if(getComponentEither.isRight()){
369                         ActionStatus actionStatus = componentsUtils.convertFromStorageResponse(getComponentEither.right().value());
370                         log.debug("Failed to found component {}, error: {}", parentId, actionStatus.name());
371                         return Either.right(componentsUtils.getResponseFormat(actionStatus));
372
373                 }
374                 component = getComponentEither.left().value();
375
376                 Optional<InputDefinition> op = component.getInputs().stream().filter(in -> in.getUniqueId().equals(inputId)).findFirst();
377                 if(!op.isPresent()){
378                         ActionStatus actionStatus = componentsUtils.convertFromStorageResponse(getComponentEither.right().value());
379                         log.debug("Failed to found input {} under component {}, error: {}", inputId, parentId, actionStatus.name());
380                         return Either.right(componentsUtils.getResponseFormat(actionStatus));
381                 }
382
383                 return Either.left(getComponentInstanceInputsByInputId(component, inputId));
384
385         }
386
387         public Either<List<InputDefinition>, ResponseFormat> createMultipleInputs(String userId, String componentId, ComponentTypeEnum componentType, ComponentInstInputsMap componentInstInputsMapUi, boolean shouldLockComp, boolean inTransaction) {
388
389                 Either<List<InputDefinition>, ResponseFormat> result = null;
390                 org.openecomp.sdc.be.model.Component component = null;
391
392                 Map<String, List<ComponentInstanceInput>> inputsValueToCreateMap = new HashMap<>();
393                 Map<String, List<ComponentInstanceProperty>> propertiesToCreateMap = new HashMap<>();
394                 Map<String, InputDefinition> inputsToCreate = new HashMap<>();
395
396                 try {
397                         Either<User, ResponseFormat> resp = validateUserExists(userId, "get Properties by input", false);
398
399                         if (resp.isRight()) {
400                                 result = Either.right(resp.right().value());
401                                 return result;
402                         }
403
404                         ComponentParametersView componentParametersView = new ComponentParametersView();
405                         componentParametersView.disableAll();
406                         componentParametersView.setIgnoreInputs(false);
407                         componentParametersView.setIgnoreComponentInstancesInputs(false);
408                         componentParametersView.setIgnoreComponentInstances(false);
409                         componentParametersView.setIgnoreComponentInstancesProperties(false);
410                         componentParametersView.setIgnoreUsers(false);
411
412                         Either<? extends org.openecomp.sdc.be.model.Component, ResponseFormat> validateComponent = validateComponentExists(componentId, componentType, componentParametersView);
413
414                         if (validateComponent.isRight()) {
415                                 result = Either.right(validateComponent.right().value());
416                                 return result;
417                         }
418                         component = validateComponent.left().value();
419
420                         if (shouldLockComp) {
421                                 Either<Boolean, ResponseFormat> lockComponent = lockComponent(component, CREATE_INPUT);
422                                 if (lockComponent.isRight()) {
423                                         result = Either.right(lockComponent.right().value());
424                                         return result;
425                                 }
426                         }
427
428                         Either<Boolean, ResponseFormat> canWork = validateCanWorkOnComponent(component, userId);
429                         if (canWork.isRight()) {
430                                 result = Either.right(canWork.right().value());
431                                 return result;
432                         }
433
434                         Either<Map<String, DataTypeDefinition>, ResponseFormat> allDataTypes = getAllDataTypes(applicationDataTypeCache);
435                         if (allDataTypes.isRight()) {
436                                 result = Either.right(allDataTypes.right().value());
437                                 return result;
438                         }
439
440                         Map<String, DataTypeDefinition> dataTypes = allDataTypes.left().value();
441                         Map<String, org.openecomp.sdc.be.model.Component> origComponentMap = new HashMap<>();
442
443
444                         //////////////////////////////////////////////////////////////////////////////////////////////////////
445
446                         List<InputDefinition> resList = new ArrayList<InputDefinition>();
447                         Map<String, List<ComponentInstancePropInput>> newInputsMap = componentInstInputsMapUi.getComponentInstanceInputsMap();
448                         List<ComponentInstance> ciList = component.getComponentInstances();
449                         if (newInputsMap != null && !newInputsMap.isEmpty()) {
450                                 
451                                 result = createInputsFromProperty(component, origComponentMap, inputsToCreate, propertiesToCreateMap, inputsValueToCreateMap, dataTypes, resList, newInputsMap, true);
452
453                                 if (result.isRight()) {
454                                         log.debug("Failed to create inputs of resource  for id {} error {}", component.getUniqueId(), result.right().value());
455                                         return result;
456                                 }
457                                 resList = result.left().value();
458                                 
459                                 
460
461                         }
462
463                         Map<String, List<ComponentInstancePropInput>> newInputsPropsMap = componentInstInputsMapUi.getComponentInstanceProperties();
464                         if (newInputsPropsMap != null && !newInputsPropsMap.isEmpty()) {
465
466                                 result = createInputsFromProperty(component, origComponentMap, inputsToCreate, propertiesToCreateMap,  inputsValueToCreateMap, dataTypes, resList, newInputsPropsMap, false);
467
468                                 if (result.isRight()) {
469                                         log.debug("Failed to create inputs of resource  for id {} error {}", component.getUniqueId(), result.right().value());
470                                         return result;
471                                 }
472                                 resList = result.left().value();
473
474                         }
475
476
477                         Either<List<InputDefinition>, StorageOperationStatus> assotiateInputsEither = toscaOperationFacade.addInputsToComponent(inputsToCreate, component.getUniqueId());
478                         if(assotiateInputsEither.isRight()){
479                                 log.debug("Failed to create inputs under component {}. Status is {}", component.getUniqueId(), assotiateInputsEither.right().value());
480                                 result = Either.right(componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(assotiateInputsEither.right().value())));
481                                 return result;
482                         }
483
484                         Either<Map<String, List<ComponentInstanceProperty>>, StorageOperationStatus> assotiatePropsEither = toscaOperationFacade.addComponentInstancePropertiesToComponent(component, propertiesToCreateMap, component.getUniqueId());
485                         if(assotiatePropsEither.isRight()){
486                                 log.debug("Failed to add inputs values under component {}. Status is {}", component.getUniqueId(), assotiateInputsEither.right().value());
487                                 result = Either.right(componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(assotiateInputsEither.right().value())));
488                                 return result;
489                         }
490
491                         Either<Map<String, List<ComponentInstanceInput>>, StorageOperationStatus> addciInputsEither = toscaOperationFacade.addComponentInstanceInputsToComponent(component, inputsValueToCreateMap);
492                         if(addciInputsEither.isRight()){
493                                 log.debug("Failed to add inputs values under component {}. Status is {}", component.getUniqueId(), assotiateInputsEither.right().value());
494                                 result = Either.right(componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(assotiateInputsEither.right().value())));
495                                 return result;
496                         }
497
498
499
500
501                         result =  Either.left(resList);
502                         return result;
503                         ///////////////////////////////////////////////////////////////////////////////////////////
504
505                 } finally {
506
507                         if (false == inTransaction) {
508
509                                 if (result == null || result.isRight()) {
510                                         log.debug("Going to execute rollback on create group.");
511                                         titanDao.rollback();
512                                 } else {
513                                         log.debug("Going to execute commit on create group.");
514                                         titanDao.commit();
515                                 }
516
517                         }
518                         // unlock resource
519                         if (shouldLockComp && component != null) {
520                                 graphLockOperation.unlockComponent(componentId, componentType.getNodeType());
521                         }
522
523                 }
524
525         }
526
527         private StorageOperationStatus addInputsToComponent(String componentId, Map<String, InputDefinition> inputsToCreate, Map<String, List<ComponentInstanceInput>> inputsValueToCreateMap,  Map<String, DataTypeDefinition> allDataTypes, List<InputDefinition> resList, int index,
528                         String compInstId, String compInstname, org.openecomp.sdc.be.model.Component origComponent, InputDefinition input) {
529                 
530
531                 Either<List<InputDefinition>, ResponseFormat> result;
532                 String innerType = null;
533                 InputDefinition oldInput = origComponent.getInputs().stream().filter(ciIn -> ciIn.getUniqueId().equals(input.getUniqueId())).findAny().get();
534                 String serviceInputName = compInstname + "_" + input.getName();
535                 input.setName(serviceInputName);
536
537                 JSONObject jobject = new JSONObject();
538                 jobject.put(GET_INPUT, input.getName());
539
540                 ComponentInstanceInput inputValue = new ComponentInstanceInput(oldInput, jobject.toJSONString(), null);
541
542                 Either<String, StorageOperationStatus> validatevalueEiter = validateInputValueBeforeCreate(inputValue, jobject.toJSONString(), false, innerType, allDataTypes);
543                 if (validatevalueEiter.isRight()) {
544
545                         return validatevalueEiter.right().value();
546                 }
547
548                 String uniqueId = UniqueIdBuilder.buildResourceInstanceInputValueUid(compInstId, index++);
549                 inputValue.setUniqueId(uniqueId);
550                 inputValue.setValue(validatevalueEiter.left().value());
551
552
553                 input.setUniqueId(UniqueIdBuilder.buildPropertyUniqueId(componentId, input.getName()));
554                 input.setSchema(oldInput.getSchema());
555                 input.setDefaultValue(oldInput.getDefaultValue());
556                 input.setConstraints(oldInput.getConstraints());
557                 input.setDescription(oldInput.getDescription());
558                 input.setHidden(oldInput.isHidden());
559                 input.setImmutable(oldInput.isImmutable());
560                 input.setDefinition(oldInput.isDefinition());
561                 input.setRequired(oldInput.isRequired());
562                 input.setOwnerId(null);
563                 input.setParentUniqueId(null);
564                 input.setInstanceUniqueId(compInstId);
565                 inputsToCreate.put(input.getName(), input);
566
567
568
569                 List<GetInputValueDataDefinition> getInputValues = new ArrayList<>();
570                 GetInputValueDataDefinition getInputValueDataDefinition = new GetInputValueDataDefinition();
571                 getInputValueDataDefinition.setInputId(input.getUniqueId());
572                 getInputValueDataDefinition.setInputName(input.getName());
573                 getInputValues.add(getInputValueDataDefinition);
574                 inputValue.setGetInputValues(getInputValues);
575
576                 List<ComponentInstanceInput> inputsValueToCreate = null;
577                 
578                 if(inputsValueToCreateMap.containsKey(compInstId)){
579                         inputsValueToCreate = inputsValueToCreateMap.get(compInstId);
580                 }else{
581                         inputsValueToCreate = new ArrayList<>();
582                 }
583                 inputsValueToCreate.add(inputValue);
584                 inputsValueToCreateMap.put(compInstId, inputsValueToCreate);
585         
586                 
587                 inputsValueToCreate.add(inputValue);
588                 List<ComponentInstanceInput> inputsValue = input.getInputs();
589                 if(inputsValue == null)
590                         inputsValue = new ArrayList<>();
591                 inputsValue.add(inputValue);
592                 input.setInputs(inputsValue);   
593
594                 resList.add(input);
595                 return StorageOperationStatus.OK;
596         }
597
598         public Either<List<InputDefinition>, ResponseFormat> createInputs(String componentId, String userId, ComponentTypeEnum componentType, List<InputDefinition> inputsDefinitions, boolean shouldLockComp, boolean inTransaction) {
599
600                 Either<List<InputDefinition>, ResponseFormat> result = null;
601
602                 org.openecomp.sdc.be.model.Component component = null;
603                 try {
604
605                         if (inputsDefinitions != null && false == inputsDefinitions.isEmpty()) {
606
607                                 if (shouldLockComp == true && inTransaction == true) {
608                                         BeEcompErrorManager.getInstance().logInternalFlowError("createGroups", "Cannot lock component since we are inside a transaction", ErrorSeverity.ERROR);
609                                         // Cannot lock component since we are in a middle of another
610                                         // transaction.
611                                         ActionStatus actionStatus = ActionStatus.INVALID_CONTENT;
612                                         result = Either.right(componentsUtils.getResponseFormat(actionStatus));
613                                         return result;
614                                 }
615
616                                 Either<User, ResponseFormat> validateUserExists = validateUserExists(userId, CREATE_INPUT, true);
617                                 if (validateUserExists.isRight()) {
618                                         result = Either.right(validateUserExists.right().value());
619                                         return result;
620                                 }
621
622                                 User user = validateUserExists.left().value();
623
624                                 Either<? extends org.openecomp.sdc.be.model.Component, ResponseFormat> validateComponent = validateComponentExists(componentId, componentType, null);
625                                 if (validateComponent.isRight()) {
626                                         result = Either.right(validateComponent.right().value());
627                                         return result;
628                                 }
629                                 component = validateComponent.left().value();
630
631                                 if (shouldLockComp) {
632                                         Either<Boolean, ResponseFormat> lockComponent = lockComponent(component, CREATE_INPUT);
633                                         if (lockComponent.isRight()) {
634                                                 return Either.right(lockComponent.right().value());
635                                         }
636                                 }
637
638                                 Either<Boolean, ResponseFormat> canWork = validateCanWorkOnComponent(component, userId);
639                                 if (canWork.isRight()) {
640                                         result = Either.right(canWork.right().value());
641                                         return result;
642                                 }
643                                 Map<String, InputDefinition> inputs = inputsDefinitions.stream().collect(Collectors.toMap( o -> o.getName(), o -> o));
644
645                                 result = createInputsInGraph(inputs, component, user, inTransaction);
646                         }
647
648                         return result;
649
650                 } finally {
651
652                         if (false == inTransaction) {
653
654                                 if (result == null || result.isRight()) {
655                                         log.debug("Going to execute rollback on create group.");
656                                         titanDao.rollback();
657                                 } else {
658                                         log.debug("Going to execute commit on create group.");
659                                         titanDao.commit();
660                                 }
661
662                         }
663                         // unlock resource
664                         if (shouldLockComp && component != null) {
665                                 graphLockOperation.unlockComponent(componentId, componentType.getNodeType());
666                         }
667
668                 }
669
670         }
671
672         public Either<List<InputDefinition>, ResponseFormat> createInputsInGraph(Map<String, InputDefinition> inputs, org.openecomp.sdc.be.model.Component component, User user, boolean inTransaction) {
673
674                 List<InputDefinition> resList = inputs.values().stream().collect(Collectors.toList());
675                 Either<List<InputDefinition>, ResponseFormat> result = Either.left(resList);
676                 List<InputDefinition> resourceProperties = component.getInputs();
677
678                 Either<Map<String, DataTypeDefinition>, ResponseFormat> allDataTypes = getAllDataTypes(applicationDataTypeCache);
679                 if (allDataTypes.isRight()) {
680                         return Either.right(allDataTypes.right().value());
681                 }
682
683                 Map<String, DataTypeDefinition> dataTypes = allDataTypes.left().value();
684
685                 for (Map.Entry<String, InputDefinition> inputDefinition : inputs.entrySet()) {
686                         String inputName = inputDefinition.getKey();
687                         inputDefinition.getValue().setName(inputName);
688
689                         Either<InputDefinition, ResponseFormat> preparedInputEither = prepareAndValidateInputBeforeCreate(inputDefinition.getValue(), dataTypes);
690                         if(preparedInputEither.isRight()){
691                                 return Either.right(preparedInputEither.right().value());
692                         }
693
694                 }
695                 if (resourceProperties != null) {
696                         Map<String, InputDefinition> generatedInputs = resourceProperties.stream().collect(Collectors.toMap(i -> i.getName(), i -> i));
697                         Either<Map<String, InputDefinition>, String> mergeEither = ToscaDataDefinition.mergeDataMaps(generatedInputs, inputs);
698                         if(mergeEither.isRight()){
699                                 return Either.right(componentsUtils.getResponseFormat(ActionStatus.PROPERTY_ALREADY_EXIST, mergeEither.right().value()));
700                         }
701                         inputs = mergeEither.left().value();
702                 }
703
704                 Either<List<InputDefinition>, StorageOperationStatus> assotiateInputsEither = toscaOperationFacade.createAndAssociateInputs(inputs, component.getUniqueId());
705                 if(assotiateInputsEither.isRight()){
706                         log.debug("Failed to create inputs under component {}. Status is {}", component.getUniqueId(), assotiateInputsEither.right().value());
707                         return Either.right(componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(assotiateInputsEither.right().value())));
708                 }
709                 result  = Either.left(assotiateInputsEither.left().value());
710
711                 return result;
712         }
713
714
715         /*          Mutates the object
716          *              Tail recurse -> traverse the tosca elements and remove nested empty map properties
717          *              this only handles nested maps, other objects are left untouched (even a Set containing a map) since behaviour is unexpected
718          *
719                          *              @param  toscaElement - expected map of tosca values
720          *          @return mutated @param toscaElement , where empty maps are deleted , return null for empty map.
721                         **/
722         private Object cleanEmptyNestedValuesInMap(Object toscaElement , short loopProtectionLevel ){
723                 //region - Stop if map is empty
724                 if (loopProtectionLevel<=0 || toscaElement==null || !(toscaElement instanceof  Map))
725                         return toscaElement;
726                 //endregion
727                 //region - Remove empty map entries & return null iff empty map
728                 if ( MapUtils.isNotEmpty( (Map)toscaElement ) ) {
729                         Object ret;
730                         Set<Object> keysToRemove = new HashSet<>();                                                                                                                             // use different set to avoid ConcurrentModificationException
731                         for( Object key : ((Map)toscaElement).keySet() ) {
732                                 Object value = ((Map) toscaElement).get(key);
733                                 ret = cleanEmptyNestedValuesInMap(value , --loopProtectionLevel );
734                                 if ( ret == null )
735                                         keysToRemove.add(key);
736                         }
737                         Collection set = ((Map) toscaElement).keySet();
738                         if (CollectionUtils.isNotEmpty(set))
739                                 set.removeAll(keysToRemove);
740
741                         if ( isEmptyNestedMap(toscaElement) )                                                                                                                                           // similar to < if ( MapUtils.isEmpty( (Map)toscaElement ) ) > ,but adds nested map check
742                                 return null;
743                 }
744                 //endregion
745                 else
746                         return null;
747                 return toscaElement;
748         }
749
750         //@returns true iff map nested maps are all empty
751         //ignores other collection objects
752         private boolean isEmptyNestedMap(Object element){
753                 boolean isEmpty = true;
754                 if (element != null){
755                         if ( element instanceof Map ){
756                                 if (MapUtils.isEmpty((Map)element))
757                                         isEmpty = true;
758                                 else
759                                 {
760                                         for( Object key : ((Map)(element)).keySet() ){
761                                                 Object value =  ((Map)(element)).get(key);
762                                                 isEmpty &= isEmptyNestedMap( value );
763                                         }
764                                 }
765                         } else {
766                                 isEmpty = false;
767                         }
768                 }
769                 return isEmpty;
770         }
771
772         public Either cleanNestedMap( Map mappedToscaTemplate , boolean deepClone  ){
773                 if (MapUtils.isNotEmpty( mappedToscaTemplate ) ){
774                         if (deepClone){
775                                 if (!(mappedToscaTemplate instanceof HashMap))
776                                         return Either.right("expecting mappedToscaTemplate as HashMap ,recieved "+ mappedToscaTemplate.getClass().getSimpleName() );
777                                 else
778                                         mappedToscaTemplate = (HashMap)((HashMap) mappedToscaTemplate).clone();
779                         }
780                         return Either.left( (Map) cleanEmptyNestedValuesInMap( mappedToscaTemplate , InputsBusinessLogic.LOOP_PROTECTION_LEVEL ) );
781                 }
782                 else {
783                         log.debug("mappedToscaTemplate is empty ");
784                         return Either.right("mappedToscaTemplate is empty ");
785                 }
786         }
787
788
789
790         /**
791          * Delete input from service
792          *
793          * @param componentType
794          * @param inputId
795          * @param component
796          * @param user
797          *
798          * @return
799          */
800         public Either<InputDefinition, ResponseFormat> deleteInput(String componentType, String componentId, String userId, String inputId) {
801
802                 Either<InputDefinition, ResponseFormat> deleteEither = null;
803                 if (log.isDebugEnabled())
804                         log.debug("Going to delete input id: {}", inputId);
805
806                 // Validate user (exists)
807                 Either<User, ResponseFormat> userEither = validateUserExists(userId, "Delete input", true);
808                 if (userEither.isRight()) {
809                         deleteEither =  Either.right(userEither.right().value());
810                         return deleteEither;
811                 }
812
813                 // Get component using componentType, componentId
814
815                 ComponentParametersView componentParametersView = new ComponentParametersView();
816                 componentParametersView.disableAll();
817                 componentParametersView.setIgnoreInputs(false);
818                 componentParametersView.setIgnoreComponentInstances(false);
819                 componentParametersView.setIgnoreComponentInstancesInputs(false);
820                 componentParametersView.setIgnoreComponentInstancesProperties(false);
821                 componentParametersView.setIgnoreUsers(false);
822
823                 Either<org.openecomp.sdc.be.model.Component, StorageOperationStatus> componentEither = toscaOperationFacade.getToscaElement(componentId, componentParametersView);
824                 if (componentEither.isRight()) {
825                         deleteEither =  Either.right(componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(componentEither.right().value())));
826                         return deleteEither;
827                 }
828                 org.openecomp.sdc.be.model.Component component = componentEither.left().value();
829
830                 // Validate inputId is child of the component
831                 Optional<InputDefinition> optionalInput = component.getInputs().stream().
832                 // filter by ID
833                                 filter(input -> input.getUniqueId().equals(inputId)).
834                                 // Get the input
835                                 findAny();
836                 if (!optionalInput.isPresent()) {
837                         return Either.right(componentsUtils.getResponseFormat(ActionStatus.INPUT_IS_NOT_CHILD_OF_COMPONENT, inputId, componentId));
838                 }
839
840                 InputDefinition inputForDelete = optionalInput.get();
841
842                 // Lock component
843                 Either<Boolean, ResponseFormat> lockResultEither = lockComponent(componentId, component, "deleteInput");
844                 if (lockResultEither.isRight()) {
845                         ResponseFormat responseFormat = lockResultEither.right().value();
846                         deleteEither =  Either.right(responseFormat);
847                         return deleteEither;
848                 }
849
850                 // Delete input operations
851                 try {
852                         StorageOperationStatus status = toscaOperationFacade.deleteInputOfResource(component, inputForDelete.getName());
853                         if(status != StorageOperationStatus.OK){
854                                 log.debug("Component id: {} delete input id: {} failed", componentId, inputId);
855                                 deleteEither =  Either.right(componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(status), component.getName()));
856                                 return deleteEither;
857                         }
858
859                         List<ComponentInstanceInput> inputsValue= getComponentInstanceInputsByInputId(component, inputId);
860                         
861                         if(inputsValue != null && !inputsValue.isEmpty()){
862                                 for(ComponentInstanceInput inputValue: inputsValue){
863                                         String compInstId = inputValue.getComponentInstanceId();
864                                         prepareValueBeforeDelete(compInstId, inputForDelete, inputValue, inputValue.getPath());
865                                         
866                                         status = toscaOperationFacade.updateComponentInstanceInput(component, compInstId, inputValue);
867                                         if(status != StorageOperationStatus.OK){
868                                                 log.debug("Component id: {} update component instance property {} id: {} failed", componentId, inputValue.getUniqueId(), inputId);
869                                                 deleteEither = Either.right(componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(status), component.getName()));
870                                                 return deleteEither;
871                                         }
872
873                                 }
874                                 
875                                 
876                         }
877
878                         // US848813 delete service input that relates to VL / CP property
879
880                         List<ComponentInstanceProperty> propertiesValue = getComponentInstancePropertiesByInputId(component, inputId);
881                                 if(propertiesValue != null && !propertiesValue.isEmpty()){
882                                         //propertyList = propertyValueStatus.left().value();
883                                         for(ComponentInstanceProperty propertyValue: propertiesValue){
884
885                                                 String compInstId = propertyValue.getComponentInstanceId();
886                                                 prepareValueBeforeDelete(compInstId, inputForDelete, propertyValue, propertyValue.getPath());
887                                                 
888                                                 status = toscaOperationFacade.updateComponentInstanceProperty(component, compInstId, propertyValue);
889                                                 if(status != StorageOperationStatus.OK){
890                                                         log.debug("Component id: {} update component instance property {} id: {} failed", componentId, propertyValue.getUniqueId(), inputId);
891                                                         deleteEither = Either.right(componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(status), component.getName()));
892                                                         return deleteEither;
893                                                 }
894
895                                         }
896                                 }
897
898
899                                 deleteEither = Either.left(inputForDelete);
900                         return deleteEither;
901                 } finally {
902                         if (deleteEither == null || deleteEither.isRight()) {
903                                 log.debug("Component id: {} delete input id: {} failed", componentId, inputId);
904                                 titanDao.rollback();
905                         } else {
906                                 log.debug("Component id: {} delete input id: {} success", componentId, inputId);
907                                 titanDao.commit();
908                         }
909                         unlockComponent(deleteEither, component);
910                 }
911         }
912
913         private Either<InputDefinition, ResponseFormat>  prepareValueBeforeDelete(String compInstId, InputDefinition inputForDelete, PropertyDefinition inputValue, List<String> pathOfComponentInstances) {
914                 Either<InputDefinition, ResponseFormat> deleteEither = Either.left(inputForDelete);
915                 String value = inputValue.getValue();
916                 Map<String, Object> mappedToscaTemplate = (Map<String, Object>) new Yaml().load(value);
917
918                 resetInputName(mappedToscaTemplate, inputForDelete.getName());
919
920                 value = "";
921                 if(!mappedToscaTemplate.isEmpty()){
922                         Either result = cleanNestedMap(mappedToscaTemplate , true);
923                         Map modifiedMappedToscaTemplate = mappedToscaTemplate;
924                         if (result.isLeft())
925                                 modifiedMappedToscaTemplate = (Map)result.left().value();
926                         else
927                                 Log.warn("Map cleanup failed -> " +result.right().value().toString());  //continue, don't break operation
928                         value = gson.toJson(modifiedMappedToscaTemplate);
929                 }
930                 inputValue.setValue(value);
931                 
932                 
933                 List<GetInputValueDataDefinition> getInputsValues = inputValue.getGetInputValues();
934                 if(getInputsValues != null && !getInputsValues.isEmpty()){
935                         Optional<GetInputValueDataDefinition> op = getInputsValues.stream().filter(gi -> gi.getInputId().equals(inputForDelete.getUniqueId())).findAny();
936                         if(op.isPresent()){
937                                 getInputsValues.remove(op.get());
938                         }
939                 }
940                 inputValue.setGetInputValues(getInputsValues);
941
942                 Either<String, TitanOperationStatus> findDefaultValue = propertyOperation.findDefaultValueFromSecondPosition(pathOfComponentInstances, inputValue.getUniqueId(), inputValue.getDefaultValue());
943                 if (findDefaultValue.isRight()) {
944                         deleteEither = Either.right(componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(DaoStatusConverter.convertTitanStatusToStorageStatus(findDefaultValue.right().value()))));
945                         return deleteEither;
946
947                 }
948                 String defaultValue = findDefaultValue.left().value();
949                 inputValue.setDefaultValue(defaultValue);
950                 log.debug("The returned default value in ResourceInstanceProperty is {}", defaultValue);
951                 return deleteEither;
952         }
953
954         private Either<InputDefinition, ResponseFormat> prepareAndValidateInputBeforeCreate(InputDefinition newInputDefinition, Map<String, DataTypeDefinition> dataTypes) {
955
956
957                 // validate input default values
958                 Either<Boolean, ResponseFormat> defaultValuesValidation = validatePropertyDefaultValue(newInputDefinition, dataTypes);
959                 if (defaultValuesValidation.isRight()) {
960                         return Either.right(defaultValuesValidation.right().value());
961                 }
962                 // convert property
963                 ToscaPropertyType type = getType(newInputDefinition.getType());
964                 if (type != null) {
965                         PropertyValueConverter converter = type.getConverter();
966                         // get inner type
967                         String innerType = null;
968                         if (newInputDefinition != null) {
969                                 SchemaDefinition schema = newInputDefinition.getSchema();
970                                 if (schema != null) {
971                                         PropertyDataDefinition prop = schema.getProperty();
972                                         if (prop != null) {
973                                                 innerType = prop.getType();
974                                         }
975                                 }
976                                 String convertedValue = null;
977                                 if (newInputDefinition.getDefaultValue() != null) {
978                                         convertedValue = converter.convert(newInputDefinition.getDefaultValue(), innerType, dataTypes);
979                                         newInputDefinition.setDefaultValue(convertedValue);
980                                 }
981                         }
982                 }
983                 return Either.left(newInputDefinition);
984         }
985
986         public boolean isInputExist(List<InputDefinition> inputs, String resourceUid, String inputName) {
987
988                 if (inputs == null) {
989                         return false;
990                 }
991
992                 for (InputDefinition propertyDefinition : inputs) {
993                         String parentUniqueId = propertyDefinition.getParentUniqueId();
994                         String name = propertyDefinition.getName();
995
996                         if (parentUniqueId.equals(resourceUid) && name.equals(inputName)) {
997                                 return true;
998                         }
999                 }
1000
1001                 return false;
1002
1003         }
1004
1005
1006         public Either<InputDefinition, ResponseFormat> getInputsAndPropertiesForComponentInput(String userId, String componentId, String inputId, boolean inTransaction) {
1007                 Either<InputDefinition, ResponseFormat> result = null;
1008                 try {
1009
1010                         Either<User, ResponseFormat> resp = validateUserExists(userId, "get Properties by input", false);
1011                         if (resp.isRight()) {
1012                                 return Either.right(resp.right().value());
1013                         }
1014                         Either<List<ComponentInstanceProperty>, StorageOperationStatus> propertiesEitherRes = null;
1015
1016                         ComponentParametersView filters = new ComponentParametersView();
1017                         filters.disableAll();
1018                         filters.setIgnoreComponentInstances(false);
1019                         filters.setIgnoreInputs(false);
1020                         filters.setIgnoreComponentInstancesInputs(false);
1021                         filters.setIgnoreComponentInstancesProperties(false);
1022                         filters.setIgnoreProperties(false);
1023                         Either<org.openecomp.sdc.be.model.Component, StorageOperationStatus> getComponentEither = toscaOperationFacade.getToscaElement(componentId, filters);
1024                         if(getComponentEither.isRight()){
1025                                 ActionStatus actionStatus = componentsUtils.convertFromStorageResponse(getComponentEither.right().value());
1026                                 log.debug("Failed to found component {}, error: {}", componentId, actionStatus.name());
1027                                 return Either.right(componentsUtils.getResponseFormat(actionStatus));
1028
1029                         }
1030                         org.openecomp.sdc.be.model.Component component = getComponentEither.left().value();
1031                         Optional<InputDefinition> op = component.getInputs().stream().filter(in -> in.getUniqueId().equals(inputId)).findFirst();
1032                         if(!op.isPresent()){
1033                                 ActionStatus actionStatus = componentsUtils.convertFromStorageResponse(getComponentEither.right().value());
1034                                 log.debug("Failed to found input {} under component {}, error: {}", inputId, componentId, actionStatus.name());
1035                                 return Either.right(componentsUtils.getResponseFormat(actionStatus));
1036                         }
1037
1038                         InputDefinition resObj = op.get();
1039
1040                         List<ComponentInstanceInput> inputCIInput = getComponentInstanceInputsByInputId(component, inputId) ;
1041
1042                         resObj.setInputs(inputCIInput);
1043
1044
1045                         List<ComponentInstanceProperty> inputProps = getComponentInstancePropertiesByInputId(component, inputId) ;
1046
1047                         resObj.setProperties(inputProps);
1048
1049
1050                         result = Either.left(resObj);
1051
1052                         return result;
1053
1054                 } finally {
1055
1056                         if (false == inTransaction) {
1057
1058                                 if (result == null || result.isRight()) {
1059                                         log.debug("Going to execute rollback on create group.");
1060                                         titanDao.rollback();
1061                                 } else {
1062                                         log.debug("Going to execute commit on create group.");
1063                                         titanDao.commit();
1064                                 }
1065
1066                         }
1067
1068                 }
1069
1070         }
1071
1072         private List<ComponentInstanceProperty> getComponentInstancePropertiesByInputId(org.openecomp.sdc.be.model.Component component, String inputId){
1073                 List<ComponentInstanceProperty> resList = new ArrayList<>();
1074                 Map<String, List<ComponentInstanceProperty>> ciPropertiesMap = component.getComponentInstancesProperties();
1075                 if(ciPropertiesMap != null && !ciPropertiesMap.isEmpty()){
1076                         ciPropertiesMap.forEach(new BiConsumer<String, List<ComponentInstanceProperty>>() {
1077                                 @Override
1078                                 public void accept(String s, List<ComponentInstanceProperty> ciPropList) {
1079                                         String ciName = "";
1080                                         Optional<ComponentInstance> ciOp = component.getComponentInstances().stream().filter(ci ->ci.getUniqueId().equals(s)).findAny();
1081                                         if(ciOp.isPresent())
1082                                                 ciName = ciOp.get().getName();
1083                                         if (ciPropList != null && !ciPropList.isEmpty()) {
1084                                                 for(ComponentInstanceProperty prop: ciPropList){
1085                                                         List<GetInputValueDataDefinition> inputsValues = prop.getGetInputValues();
1086                                                         if(inputsValues != null && !inputsValues.isEmpty()){
1087                                                                 for(GetInputValueDataDefinition inputData: inputsValues){
1088                                                                         if(inputData.getInputId().equals(inputId) || (inputData.getGetInputIndex() != null && inputData.getGetInputIndex().getInputId().equals(inputId))){
1089                                                                                 prop.setComponentInstanceId(s);
1090                                                                                 prop.setComponentInstanceName(ciName);
1091                                                                                 resList.add(prop);
1092                                                                                 break;
1093                                                                         }
1094                                                                 }
1095                                                         }
1096
1097                                                 }
1098                                         }
1099                                 }
1100                         });
1101                 }
1102                 return resList;
1103
1104         }
1105
1106         private List<ComponentInstanceInput> getComponentInstanceInputsByInputId(org.openecomp.sdc.be.model.Component component, String inputId){
1107                 List<ComponentInstanceInput> resList = new ArrayList<>();
1108                 Map<String, List<ComponentInstanceInput>> ciInputsMap = component.getComponentInstancesInputs();
1109                 if(ciInputsMap != null && !ciInputsMap.isEmpty()){
1110                         ciInputsMap.forEach(new BiConsumer<String, List<ComponentInstanceInput>>() {
1111                                 @Override
1112                                 public void accept(String s, List<ComponentInstanceInput> ciPropList) {
1113                                         String ciName = "";
1114                                         Optional<ComponentInstance> ciOp = component.getComponentInstances().stream().filter(ci ->ci.getUniqueId().equals(s)).findAny();
1115                                         if(ciOp.isPresent())
1116                                                 ciName = ciOp.get().getName();
1117                                         if (ciPropList != null && !ciPropList.isEmpty()) {
1118                                                 for(ComponentInstanceInput prop: ciPropList){
1119                                                         List<GetInputValueDataDefinition> inputsValues = prop.getGetInputValues();
1120                                                         if(inputsValues != null && !inputsValues.isEmpty()){
1121                                                                 for(GetInputValueDataDefinition inputData: inputsValues){
1122                                                                         if(inputData.getInputId().equals(inputId) || (inputData.getGetInputIndex() != null && inputData.getGetInputIndex().getInputId().equals(inputId))){
1123                                                                                 prop.setComponentInstanceId(s);
1124                                                                                 prop.setComponentInstanceName(ciName);
1125                                                                                 resList.add(prop);
1126                                                                                 break;
1127                                                                         }
1128                                                                 }
1129                                                         }
1130
1131                                                 }
1132                                         }
1133                                 }
1134                         });
1135                 }
1136                 return resList;
1137
1138         }
1139
1140         private Either<org.openecomp.sdc.be.model.Component, StorageOperationStatus> getOriginComponent(ComponentInstance ci, Map<String, org.openecomp.sdc.be.model.Component> origComponentMap){
1141                 Either<org.openecomp.sdc.be.model.Component, StorageOperationStatus> result = null;
1142                 String compInstname = ci.getNormalizedName();
1143
1144                 ComponentParametersView componentParametersView = new ComponentParametersView();
1145                 componentParametersView.disableAll();
1146                 componentParametersView.setIgnoreInputs(false);
1147                 org.openecomp.sdc.be.model.Component origComponent = null;
1148                 if(!origComponentMap.containsKey(ci.getComponentUid())){
1149                         Either<org.openecomp.sdc.be.model.Component, StorageOperationStatus> componentFound  = toscaOperationFacade.getToscaElement(ci.getComponentUid(), componentParametersView);
1150
1151                         if (componentFound.isRight()) {
1152                                 result = Either.right(componentFound.right().value());
1153                                 return result;
1154                         }
1155                         origComponent =  componentFound.left().value();
1156                         origComponentMap.put(origComponent.getUniqueId(), origComponent);
1157                 }else{
1158                         origComponent = origComponentMap.get(ci.getComponentUid());
1159                 }
1160                 result = Either.left(origComponent);
1161                 return result;
1162         }
1163
1164
1165
1166         private Either<List<InputDefinition>, ResponseFormat> createInputsFromProperty(org.openecomp.sdc.be.model.Component component, Map<String, org.openecomp.sdc.be.model.Component> origComponentMap,  Map<String, InputDefinition> inputsToCreate, Map<String, List<ComponentInstanceProperty>> propertiesToCreateMap, Map<String, List<ComponentInstanceInput>> inputsValueToCreateMap, Map<String, DataTypeDefinition> dataTypes,  List<InputDefinition> resList, Map<String, List<ComponentInstancePropInput>> newInputsPropsMap, boolean isInputValue) {
1167                 List<ComponentInstance> ciList = component.getComponentInstances();
1168                 String componentId = component.getUniqueId();
1169                 for (Entry<String, List<ComponentInstancePropInput>> entry : newInputsPropsMap.entrySet()) {
1170                         String compInstId = entry.getKey();
1171                         List<ComponentInstanceProperty> propertiesToCreate = null;
1172                         if(propertiesToCreateMap.containsKey(compInstId)){
1173                                 propertiesToCreate = propertiesToCreateMap.get(compInstId);
1174                         }else{
1175                                 propertiesToCreate = new ArrayList<>();
1176                         }
1177                         
1178                         List<ComponentInstanceInput> inputsValueToCreate = null;
1179                         if(propertiesToCreateMap.containsKey(compInstId)){
1180                                 inputsValueToCreate = inputsValueToCreateMap.get(compInstId);
1181                         }else{
1182                                 inputsValueToCreate = new ArrayList<>();
1183                         }
1184                         
1185                         List<ComponentInstancePropInput> properties = entry.getValue();
1186
1187                         Optional<ComponentInstance> op = ciList.stream().filter(ci -> ci.getUniqueId().equals(compInstId)).findAny();
1188                         if(!op.isPresent()){
1189                                 ActionStatus actionStatus = ActionStatus.INVALID_CONTENT;
1190                                 log.debug("Failed to find component instance {} under component {}", compInstId, componentId);
1191                                 return Either.right(componentsUtils.getResponseFormat(actionStatus));
1192
1193                         }
1194                         ComponentInstance ci = op.get();
1195                         String compInstname = ci.getNormalizedName();
1196                         Either<org.openecomp.sdc.be.model.Component, StorageOperationStatus> origComponentEither = getOriginComponent(ci, origComponentMap);
1197                         if(origComponentEither.isRight()){
1198                                 ActionStatus actionStatus = componentsUtils.convertFromStorageResponse(origComponentEither.right().value());
1199                                 log.debug("Failed to create inputs value under component {}, error: {}", componentId, actionStatus.name());
1200                                 return Either.right(componentsUtils.getResponseFormat(actionStatus));
1201
1202                         }
1203                         org.openecomp.sdc.be.model.Component origComponent = origComponentEither.left().value();
1204
1205
1206                         //String originType = (String) titanGenericDao.getProperty(originVertex, GraphPropertiesDictionary.LABEL.getProperty());
1207
1208                         String inputName = compInstname;
1209
1210                         if (properties != null && !properties.isEmpty()) {
1211                                 for (ComponentInstancePropInput propInput : properties) {
1212                                         propInput.setOwnerId(null);
1213                                         propInput.setParentUniqueId(null);
1214
1215                                         Either<InputDefinition, StorageOperationStatus> createInputRes = createInputForComponentInstance(component, origComponent,ci, inputsToCreate, propertiesToCreate, inputsValueToCreate, dataTypes, inputName, propInput, isInputValue);
1216
1217                                         if (createInputRes.isRight()) {
1218                                                 log.debug("Failed to create input  of resource instance for id {} error {}", compInstId, createInputRes.right().value());
1219                                                 return Either.right(componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(createInputRes.right().value())));
1220
1221                                         }
1222
1223                                         resList.add(createInputRes.left().value());
1224
1225                                 }
1226                                 if(! isInputValue){
1227                                         propertiesToCreateMap.put(compInstId, propertiesToCreate);
1228                                 }                                       
1229                                 else{
1230                                         inputsValueToCreateMap.put(compInstId, inputsValueToCreate);
1231                                 }
1232                         }
1233
1234                 }
1235                 return Either.left(resList);
1236         }
1237
1238         private Either<InputDefinition, StorageOperationStatus> createInputForComponentInstance(org.openecomp.sdc.be.model.Component component,org.openecomp.sdc.be.model.Component orignComponent, ComponentInstance ci, Map<String, InputDefinition> inputsToCreate, List<ComponentInstanceProperty> propertiesToCreate, List<ComponentInstanceInput> inputsValueToCreate, Map<String, DataTypeDefinition> dataTypes, String inputName, ComponentInstancePropInput propInput, boolean isInputValue) {
1239                 String propertiesName = propInput.getPropertiesName() ;
1240                 PropertyDefinition selectedProp = propInput.getInput();
1241                 String[] parsedPropNames = propInput.getParsedPropNames();
1242
1243                 if(parsedPropNames != null){
1244                         for(String str: parsedPropNames){
1245                                 inputName += "_"  + str;
1246                         }
1247                 } else {
1248                         inputName += "_"  + propInput.getName();
1249                 }
1250
1251                 InputDefinition input = null;
1252                 PropertyDefinition prop = propInput;
1253
1254                 if(CollectionUtils.isNotEmpty(propertiesToCreate) && !isInputValue){
1255                         Optional<ComponentInstanceProperty> propOpt = propertiesToCreate.stream().filter(p -> p.getName().equals(propInput.getName())).findFirst();
1256                         if(propOpt.isPresent()){
1257                                 prop = propOpt.get();
1258                         }
1259                 }else{
1260                         if(CollectionUtils.isNotEmpty(inputsValueToCreate) && isInputValue){
1261                                 Optional<ComponentInstanceInput> propOpt = inputsValueToCreate.stream().filter(p -> p.getName().equals(propInput.getName())).findFirst();
1262                                 if(propOpt.isPresent()){
1263                                         prop = propOpt.get();
1264                                 }
1265                         }
1266                 }
1267                 
1268                 boolean complexProperty = false;
1269                 if(propertiesName != null && !propertiesName.isEmpty() && selectedProp != null){
1270                         complexProperty = true;
1271                         input = new InputDefinition(selectedProp);
1272                 }else{
1273                         input = new InputDefinition(prop);
1274                         input.setName(inputName + "_" + prop.getName());
1275
1276                 }
1277                 input.setName(inputName);
1278                 input.setUniqueId(UniqueIdBuilder.buildPropertyUniqueId(component.getUniqueId(), input.getName()));
1279                 input.setInputPath(propertiesName);
1280                 input.setInstanceUniqueId(ci.getUniqueId());
1281                 input.setPropertyId(propInput.getUniqueId());
1282
1283                 JSONObject jobject = new JSONObject();
1284
1285
1286                 if(prop.getValue() == null || prop.getValue().isEmpty()){
1287                         if(complexProperty){
1288
1289                                 jobject = createJSONValueForProperty(parsedPropNames.length -1, parsedPropNames, jobject, inputName);
1290                                 prop.setValue(jobject.toJSONString());
1291
1292                         }else{
1293
1294                                 jobject.put(GET_INPUT, input.getName());
1295                                 prop.setValue(jobject.toJSONString());
1296
1297                         }
1298
1299                 }else{
1300
1301                         String value = prop.getValue();
1302                         Object objValue =  new Yaml().load(value);
1303                         if( objValue instanceof Map || objValue  instanceof List ){
1304                                 if(!complexProperty){
1305                                         jobject.put(GET_INPUT, input.getName());
1306                                         prop.setValue(jobject.toJSONString());
1307                                         
1308
1309                                 }else{
1310                                         Map<String, Object> mappedToscaTemplate = (Map<String, Object>) objValue;
1311                                         createInputValue(mappedToscaTemplate, 1, parsedPropNames, inputName);
1312
1313                                         String json = gson.toJson(mappedToscaTemplate);
1314                                         prop.setValue(json);
1315                                         
1316                                 }
1317
1318                         }else{
1319                                 jobject.put(GET_INPUT, input.getName());
1320                                 prop.setValue(jobject.toJSONString());
1321                                 
1322                         }
1323
1324                 }
1325                 
1326                 ((IComponentInstanceConnectedElement)prop).setComponentInstanceId(ci.getUniqueId());
1327                 ((IComponentInstanceConnectedElement)prop).setComponentInstanceName(ci.getName());
1328
1329                 if(CollectionUtils.isEmpty(prop.getGetInputValues())){
1330                         prop.setGetInputValues(new ArrayList<>());
1331                 }
1332                 List<GetInputValueDataDefinition> getInputValues = prop.getGetInputValues();
1333
1334                 GetInputValueDataDefinition getInputValueDataDefinition = new GetInputValueDataDefinition();
1335                 getInputValueDataDefinition.setInputId(input.getUniqueId());
1336                 getInputValueDataDefinition.setInputName(input.getName());
1337                 getInputValues.add(getInputValueDataDefinition);
1338
1339                 if(!isInputValue){
1340                         if(!propertiesToCreate.contains(prop)){
1341                                 propertiesToCreate.add((ComponentInstanceProperty)prop);
1342                         }
1343         
1344                         inputsToCreate.put(input.getName(), input);
1345                         List<ComponentInstanceProperty> propertiesList = input.getProperties();
1346                         if(propertiesList == null)
1347                          propertiesList = new ArrayList<>(); // adding the property with the new value for UI
1348                         propertiesList.add((ComponentInstanceProperty)prop);
1349                         input.setProperties(propertiesList);
1350                 }else{
1351                         ComponentInstanceInput inputValue = new ComponentInstanceInput(prop);
1352                         if(!inputsValueToCreate.contains(inputValue)){
1353                                 inputsValueToCreate.add(inputValue);;
1354                         }
1355         
1356                         inputsToCreate.put(input.getName(), input);
1357                         List<ComponentInstanceInput> inputsValueList = input.getInputs();
1358                         if(inputsValueList == null)
1359                                 inputsValueList = new ArrayList<>(); // adding the property with the new value for UI
1360                         inputsValueList.add(inputValue);
1361                         input.setInputs(inputsValueList);
1362                 }
1363
1364                 return Either.left(input);
1365
1366         }
1367
1368         private  JSONObject createJSONValueForProperty (int i, String [] parsedPropNames, JSONObject ooj, String inputName){
1369
1370                 while(i >= 1){
1371                         if( i == parsedPropNames.length -1){
1372                                 JSONObject jobProp = new JSONObject();
1373                                 jobProp.put(GET_INPUT, inputName);
1374                                 ooj.put(parsedPropNames[i], jobProp);
1375                                 i--;
1376                                 return createJSONValueForProperty (i, parsedPropNames, ooj, inputName);
1377                         }else{
1378                                 JSONObject res = new JSONObject();
1379                                 res.put(parsedPropNames[i], ooj);
1380                                 i --;
1381                                 res =  createJSONValueForProperty (i, parsedPropNames, res, inputName);
1382                                 return res;
1383                         }
1384                 }
1385
1386                 return ooj;
1387         }
1388
1389         public void resetInputName(Map<String, Object> lhm1, String inputName){
1390             for (Map.Entry<String, Object> entry : lhm1.entrySet()) {
1391                 String key = entry.getKey();
1392                 Object value = entry.getValue();
1393                 if (value instanceof String && ((String) value).equalsIgnoreCase(inputName) && key.equals(GET_INPUT)) {
1394                         value = "";
1395                         lhm1.remove(key);
1396                 } else if (value instanceof Map) {
1397                     Map<String, Object> subMap = (Map<String, Object>)value;
1398                     resetInputName(subMap, inputName);
1399                 } else {
1400                      continue;
1401                 }
1402
1403             }
1404         }
1405
1406         private  Map<String, Object> createInputValue(Map<String, Object> lhm1, int index, String[] inputNames, String inputName){
1407                 while(index < inputNames.length){
1408                         if(lhm1.containsKey(inputNames[index])){
1409                                 Object value = lhm1.get(inputNames[index]);
1410                                 if (value instanceof Map){
1411                                         if(index == inputNames.length -1){
1412                                                 ((Map) value).put(GET_INPUT, inputName);
1413                                                 return ((Map) value);
1414
1415                                         }else{
1416                                                 index++;
1417                                                 return  createInputValue((Map)value, index, inputNames, inputName);
1418                                         }
1419                                 }else{
1420                                         Map<String, Object> jobProp = new HashMap<>();
1421                                         if(index == inputNames.length -1){
1422                                                 jobProp.put(GET_INPUT, inputName);
1423                                                 lhm1.put(inputNames[index], jobProp);
1424                                                 return lhm1;
1425                                         }else{
1426                                                 lhm1.put(inputNames[index], jobProp);
1427                                                 index++;
1428                                                 return  createInputValue(jobProp, index, inputNames, inputName);
1429                                         }
1430                                 }
1431                         }else{
1432                                 Map<String, Object> jobProp = new HashMap<>();
1433                                 lhm1.put(inputNames[index], jobProp);
1434                                 if(index == inputNames.length -1){
1435                                         jobProp.put(GET_INPUT, inputName);
1436                                         return jobProp;
1437                                 }else{
1438                                         index++;
1439                                         return  createInputValue(jobProp, index, inputNames, inputName);
1440                                 }
1441                         }
1442                 }
1443                 return lhm1;
1444         }
1445
1446
1447
1448
1449 }