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