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