aboutsummaryrefslogtreecommitdiffstats
path: root/catalog-be/src/main/java/org/openecomp/sdc/be/components/impl/InputsBusinessLogic.java
blob: bca901ee8b85cedc3d9bac251201d3f0e5102fd5 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
/*-
 * ============LICENSE_START=======================================================
 * SDC
 * ================================================================================
 * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved.
 * ================================================================================
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 * ============LICENSE_END=========================================================
 * Modifications copyright (c) 2019 Nokia
 * ================================================================================
 */
package org.openecomp.sdc.be.components.impl;

import fj.data.Either;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.Optional;
import java.util.stream.Collectors;
import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.collections4.ListUtils;
import org.apache.commons.collections4.MapUtils;
import org.apache.commons.lang3.BooleanUtils;
import org.apache.commons.lang3.StringUtils;
import org.apache.commons.lang3.builder.ReflectionToStringBuilder;
import org.openecomp.sdc.be.components.impl.exceptions.ByActionStatusComponentException;
import org.openecomp.sdc.be.components.impl.exceptions.ByResponseFormatComponentException;
import org.openecomp.sdc.be.components.impl.exceptions.ComponentException;
import org.openecomp.sdc.be.components.property.PropertyDeclarationOrchestrator;
import org.openecomp.sdc.be.components.validation.ComponentValidations;
import org.openecomp.sdc.be.config.BeEcompErrorManager;
import org.openecomp.sdc.be.dao.api.ActionStatus;
import org.openecomp.sdc.be.dao.janusgraph.JanusGraphOperationStatus;
import org.openecomp.sdc.be.dao.utils.MapUtil;
import org.openecomp.sdc.be.datamodel.utils.PropertyValueConstraintValidationUtil;
import org.openecomp.sdc.be.datatypes.elements.PropertyDataDefinition;
import org.openecomp.sdc.be.datatypes.elements.SchemaDefinition;
import org.openecomp.sdc.be.datatypes.enums.ComponentTypeEnum;
import org.openecomp.sdc.be.datatypes.enums.NodeTypeEnum;
import org.openecomp.sdc.be.datatypes.tosca.ToscaDataDefinition;
import org.openecomp.sdc.be.model.Component;
import org.openecomp.sdc.be.model.ComponentInstInputsMap;
import org.openecomp.sdc.be.model.ComponentInstListInput;
import org.openecomp.sdc.be.model.ComponentInstance;
import org.openecomp.sdc.be.model.ComponentInstanceInput;
import org.openecomp.sdc.be.model.ComponentInstancePropInput;
import org.openecomp.sdc.be.model.ComponentInstanceProperty;
import org.openecomp.sdc.be.model.ComponentParametersView;
import org.openecomp.sdc.be.model.DataTypeDefinition;
import org.openecomp.sdc.be.model.InputDefinition;
import org.openecomp.sdc.be.model.PropertyDefinition;
import org.openecomp.sdc.be.model.jsonjanusgraph.operations.ArtifactsOperations;
import org.openecomp.sdc.be.model.jsonjanusgraph.operations.InterfaceOperation;
import org.openecomp.sdc.be.model.operations.api.IElementOperation;
import org.openecomp.sdc.be.model.operations.api.IGroupInstanceOperation;
import org.openecomp.sdc.be.model.operations.api.IGroupOperation;
import org.openecomp.sdc.be.model.operations.api.IGroupTypeOperation;
import org.openecomp.sdc.be.model.operations.api.StorageOperationStatus;
import org.openecomp.sdc.be.model.operations.impl.DaoStatusConverter;
import org.openecomp.sdc.be.model.operations.impl.InterfaceLifecycleOperation;
import org.openecomp.sdc.be.model.operations.impl.UniqueIdBuilder;
import org.openecomp.sdc.be.model.operations.utils.ComponentValidationUtils;
import org.openecomp.sdc.be.model.tosca.ToscaPropertyType;
import org.openecomp.sdc.be.model.tosca.converters.PropertyValueConverter;
import org.openecomp.sdc.be.resources.data.EntryData;
import org.openecomp.sdc.common.log.elements.LoggerSupportability;
import org.openecomp.sdc.common.log.enums.LoggerSupportabilityActions;
import org.openecomp.sdc.common.log.enums.StatusCode;
import org.openecomp.sdc.common.log.wrappers.Logger;
import org.openecomp.sdc.exception.ResponseFormat;
import org.springframework.beans.factory.annotation.Autowired;

@org.springframework.stereotype.Component("inputsBusinessLogic")
public class InputsBusinessLogic extends BaseBusinessLogic {

    private static final String CREATE_INPUT = "CreateInput";
    private static final String UPDATE_INPUT = "UpdateInput";
    private static final Logger log = Logger.getLogger(InputsBusinessLogic.class);
    private static final String FAILED_TO_FOUND_COMPONENT_ERROR = "Failed to found component {}, error: {}";
    private static final String FAILED_TO_FOUND_INPUT_UNDER_COMPONENT_ERROR = "Failed to found input {} under component {}, error: {}";
    private static final String GOING_TO_EXECUTE_ROLLBACK_ON_CREATE_GROUP = "Going to execute rollback on create group.";
    private static final String GOING_TO_EXECUTE_COMMIT_ON_CREATE_GROUP = "Going to execute commit on create group.";
    private static final String GOING_TO_EXECUTE_ROLLBACK_ON_UPDATE_INPUT = "Going to execute rollback on update input.";
    private static final String GOING_TO_EXECUTE_COMMIT_ON_UPDATE_INPUT = "Going to execute commit on update input.";
    private static final LoggerSupportability loggerSupportability = LoggerSupportability.getLogger(InputsBusinessLogic.class.getName());
    private final PropertyDeclarationOrchestrator propertyDeclarationOrchestrator;
    private final ComponentInstanceBusinessLogic componentInstanceBusinessLogic;
    private final DataTypeBusinessLogic dataTypeBusinessLogic;

    @Autowired
    public InputsBusinessLogic(IElementOperation elementDao, IGroupOperation groupOperation, IGroupInstanceOperation groupInstanceOperation,
                               IGroupTypeOperation groupTypeOperation, InterfaceOperation interfaceOperation,
                               InterfaceLifecycleOperation interfaceLifecycleTypeOperation,
                               PropertyDeclarationOrchestrator propertyDeclarationOrchestrator,
                               ComponentInstanceBusinessLogic componentInstanceBusinessLogic, DataTypeBusinessLogic dataTypeBusinessLogic,
                               ArtifactsOperations artifactToscaOperation) {
        super(elementDao, groupOperation, groupInstanceOperation, groupTypeOperation, interfaceOperation, interfaceLifecycleTypeOperation,
            artifactToscaOperation);
        this.propertyDeclarationOrchestrator = propertyDeclarationOrchestrator;
        this.componentInstanceBusinessLogic = componentInstanceBusinessLogic;
        this.dataTypeBusinessLogic = dataTypeBusinessLogic;
    }

    /**
     * associate inputs to a given component with paging
     *
     * @param userId
     * @param componentId
     * @return
     */
    public Either<List<InputDefinition>, ResponseFormat> getInputs(String userId, String componentId) {
        validateUserExists(userId);
        ComponentParametersView filters = new ComponentParametersView();
        filters.disableAll();
        filters.setIgnoreInputs(false);
        Either<Component, StorageOperationStatus> getComponentEither = toscaOperationFacade
            .getToscaElement(componentId, filters);
        if (getComponentEither.isRight()) {
            ActionStatus actionStatus = componentsUtils.convertFromStorageResponse(getComponentEither.right().value());
            log.debug(FAILED_TO_FOUND_COMPONENT_ERROR, componentId, actionStatus);
            return Either.right(componentsUtils.getResponseFormat(actionStatus));
        }
        Component component = getComponentEither.left().value();
        List<InputDefinition> inputs = component.getInputs();
        return Either.left(inputs);
    }

    public Either<List<ComponentInstanceInput>, ResponseFormat> getComponentInstanceInputs(String userId, String componentId,
                                                                                           String componentInstanceId) {
        validateUserExists(userId);
        ComponentParametersView filters = new ComponentParametersView();
        filters.disableAll();
        filters.setIgnoreInputs(false);
        filters.setIgnoreComponentInstances(false);
        filters.setIgnoreComponentInstancesInputs(false);
        Either<Component, StorageOperationStatus> getComponentEither = toscaOperationFacade
            .getToscaElement(componentId, filters);
        if (getComponentEither.isRight()) {
            ActionStatus actionStatus = componentsUtils.convertFromStorageResponse(getComponentEither.right().value());
            log.debug(FAILED_TO_FOUND_COMPONENT_ERROR, componentId, actionStatus);
            return Either.right(componentsUtils.getResponseFormat(actionStatus));
        }
        Component component = getComponentEither.left().value();
        if (!ComponentValidations.validateComponentInstanceExist(component, componentInstanceId)) {
            ActionStatus actionStatus = ActionStatus.COMPONENT_INSTANCE_NOT_FOUND;
            log.debug("Failed to found component instance inputs {}, error: {}", componentInstanceId, actionStatus);
            loggerSupportability.log(LoggerSupportabilityActions.CREATE_INPUTS, component.getComponentMetadataForSupportLog(), StatusCode.ERROR,
                "Failed to found component instance inputs componentInstanceId: {}", componentInstanceId);
            return Either.right(componentsUtils.getResponseFormat(actionStatus));
        }
        Map<String, List<ComponentInstanceInput>> ciInputs = Optional.ofNullable(component.getComponentInstancesInputs())
            .orElse(Collections.emptyMap());
        // Set Constraints on Input
        MapUtils.emptyIfNull(ciInputs).values()
            .forEach(inputs -> ListUtils.emptyIfNull(inputs).forEach(input -> input.setConstraints(setInputConstraint(input))));
        return Either.left(ciInputs.getOrDefault(componentInstanceId, Collections.emptyList()));
    }

    /**
     * associate properties to a given component instance input
     *
     * @param instanceId
     * @param userId
     * @param inputId
     * @return
     */
    public Either<List<ComponentInstanceProperty>, ResponseFormat> getComponentInstancePropertiesByInputId(String userId, String componentId,
                                                                                                           String instanceId, String inputId) {
        validateUserExists(userId);
        String parentId = componentId;
        Component component;
        ComponentParametersView filters = new ComponentParametersView();
        filters.disableAll();
        filters.setIgnoreComponentInstances(false);
        if (!instanceId.equals(inputId)) {
            Either<Component, StorageOperationStatus> getComponentEither = toscaOperationFacade
                .getToscaElement(parentId, filters);
            if (getComponentEither.isRight()) {
                ActionStatus actionStatus = componentsUtils.convertFromStorageResponse(getComponentEither.right().value());
                log.debug(FAILED_TO_FOUND_COMPONENT_ERROR, parentId, actionStatus);
                return Either.right(componentsUtils.getResponseFormat(actionStatus));
            }
            component = getComponentEither.left().value();
            Optional<ComponentInstance> ciOp = component.getComponentInstances().stream().filter(ci -> ci.getUniqueId().equals(instanceId)).findAny();
            if (ciOp.isPresent()) {
                parentId = ciOp.get().getComponentUid();
            }
        }
        filters.setIgnoreInputs(false);
        filters.setIgnoreComponentInstancesProperties(false);
        filters.setIgnoreComponentInstancesInputs(false);
        filters.setIgnoreProperties(false);
        Either<Component, StorageOperationStatus> getComponentEither = toscaOperationFacade
            .getToscaElement(parentId, filters);
        if (getComponentEither.isRight()) {
            ActionStatus actionStatus = componentsUtils.convertFromStorageResponse(getComponentEither.right().value());
            log.debug(FAILED_TO_FOUND_COMPONENT_ERROR, parentId, actionStatus);
            return Either.right(componentsUtils.getResponseFormat(actionStatus));
        }
        component = getComponentEither.left().value();
        Optional<InputDefinition> op = component.getInputs().stream().filter(in -> in.getUniqueId().equals(inputId)).findFirst();
        if (!op.isPresent()) {
            ActionStatus actionStatus = componentsUtils.convertFromStorageResponse(getComponentEither.right().value());
            log.debug(FAILED_TO_FOUND_INPUT_UNDER_COMPONENT_ERROR, inputId, parentId, actionStatus);
            return Either.right(componentsUtils.getResponseFormat(actionStatus));
        }
        return Either.left(componentInstanceBusinessLogic.getComponentInstancePropertiesByInputId(component, inputId));
    }

    private String updateInputObjectValue(InputDefinition currentInput, InputDefinition newInput, Map<String, DataTypeDefinition> dataTypes) {
        String innerType = null;
        String propertyType = currentInput.getType();
        ToscaPropertyType type = ToscaPropertyType.isValidType(propertyType);
        log.debug("The type of the property {} is {}", currentInput.getUniqueId(), propertyType);
        if (type == ToscaPropertyType.LIST || type == ToscaPropertyType.MAP) {
            SchemaDefinition def = currentInput.getSchema();
            if (def == null) {
                log.debug("Schema doesn't exists for property of type {}", type);
                throw new ByActionStatusComponentException(componentsUtils.convertFromStorageResponse(StorageOperationStatus.INVALID_VALUE));
            }
            PropertyDataDefinition propDef = def.getProperty();
            if (propDef == null) {
                log.debug("Property in Schema Definition inside property of type {} doesn't exist", type);
                throw new ByActionStatusComponentException(componentsUtils.convertFromStorageResponse(StorageOperationStatus.INVALID_VALUE));
            }
            innerType = propDef.getType();
        }
        // Specific Update Logic
        Either<Object, Boolean> isValid = propertyOperation
            .validateAndUpdatePropertyValue(propertyType, newInput.getDefaultValue(), true, innerType, dataTypes);
        String newValue = newInput.getDefaultValue();
        if (isValid.isRight()) {
            Boolean res = isValid.right().value();
            if (Boolean.FALSE.equals(res)) {
                throw new ByActionStatusComponentException(componentsUtils.convertFromStorageResponse(
                    DaoStatusConverter.convertJanusGraphStatusToStorageStatus(JanusGraphOperationStatus.ILLEGAL_ARGUMENT)));
            }
        } else {
            Object object = isValid.left().value();
            if (object != null) {
                newValue = object.toString();
            }
        }
        return newValue;
    }

    private InputDefinition getInputFromInputsListById(List<InputDefinition> componentsOldInputs, InputDefinition input) {
        return componentsOldInputs.stream().filter(in -> in.getUniqueId().equals(input.getUniqueId())).findFirst().orElse(null);
    }

    public Either<List<InputDefinition>, ResponseFormat> updateInputsValue(ComponentTypeEnum componentType, String componentId,
                                                                           List<InputDefinition> inputs, String userId, boolean shouldLockComp) {
        List<InputDefinition> returnInputs = new ArrayList<>();
        Either<List<InputDefinition>, ResponseFormat> result = null;
        Component component = null;
        try {
            validateUserExists(userId);
            ComponentParametersView componentParametersView = new ComponentParametersView();
            componentParametersView.disableAll();
            componentParametersView.setIgnoreInputs(false);
            componentParametersView.setIgnoreUsers(false);
            componentParametersView.setIgnoreProperties(false);
            componentParametersView.setIgnoreComponentInstancesProperties(false);
            componentParametersView.setIgnoreComponentInstances(false);
            component = validateComponentExists(componentId, componentType, componentParametersView);
            if (shouldLockComp) {
                try {
                    lockComponent(component, UPDATE_INPUT);
                } catch (ComponentException e) {
                    log.error("Failed to lock component", e);
                    result = Either.right(e.getResponseFormat());
                    return result;
                }
            }
            //Validate value and Constraint of input
            Either<Boolean, ResponseFormat> constraintValidatorResponse = validateInputValueConstraint(inputs, component.getModel());
            if (constraintValidatorResponse.isRight()) {
                log.error("Failed validation value and constraint of property: {}", constraintValidatorResponse.right().value());
                return Either.right(constraintValidatorResponse.right().value());
            }
            validateCanWorkOnComponent(component, userId);
            Map<String, DataTypeDefinition> dataTypes;
            dataTypes = componentsUtils.getAllDataTypes(applicationDataTypeCache, component.getModel());
            List<InputDefinition> componentsOldInputs = Optional.ofNullable(component.getInputs()).orElse(Collections.emptyList());
            for (InputDefinition newInput : inputs) {
                InputDefinition currInput = getInputFromInputsListById(componentsOldInputs, newInput);
                if (currInput == null) {
                    ActionStatus actionStatus = ActionStatus.COMPONENT_NOT_FOUND;
                    log.debug("Failed to found newInput {} under component {}, error: {}", newInput.getUniqueId(), componentId, actionStatus);
                    result = Either.right(componentsUtils.getResponseFormat(actionStatus));
                    return result;
                }
                String updateInputObjectValue = updateInputObjectValue(currInput, newInput, dataTypes);
                currInput.setDefaultValue(updateInputObjectValue);
                currInput.setOwnerId(userId);
                currInput.setMetadata(newInput.getMetadata());
                if (newInput.isRequired() != null) {
                    currInput.setRequired(newInput.isRequired());
                }
                Either<InputDefinition, StorageOperationStatus> status = toscaOperationFacade.updateInputOfComponent(component, currInput);
                if (status.isRight()) {
                    ActionStatus actionStatus = componentsUtils.convertFromStorageResponseForResourceInstanceProperty(status.right().value());
                    result = Either.right(componentsUtils.getResponseFormat(actionStatus, ""));
                    return result;
                } else {
                    returnInputs.add(status.left().value());
                }
            }
            result = Either.left(returnInputs);
        } catch (ComponentException e) {
            log.debug(GOING_TO_EXECUTE_ROLLBACK_ON_UPDATE_INPUT);
            unlockRollbackWithException(component, e);
        } catch (Exception e) {
            log.debug(GOING_TO_EXECUTE_ROLLBACK_ON_UPDATE_INPUT);
            unlockRollbackWithException(component, new ByActionStatusComponentException(ActionStatus.GENERAL_ERROR));
        }
        log.debug(GOING_TO_EXECUTE_COMMIT_ON_UPDATE_INPUT);
        unlockWithCommit(component);
        return result;
    }

    private Either<Boolean, ResponseFormat> validateInputValueConstraint(List<InputDefinition> inputs, final String model) {
        PropertyValueConstraintValidationUtil propertyValueConstraintValidationUtil = new PropertyValueConstraintValidationUtil();
        List<InputDefinition> inputDefinitions = new ArrayList<>();
        for (InputDefinition inputDefinition : inputs) {
            InputDefinition inputDef = new InputDefinition();
            inputDefinition.setDefaultValue(inputDefinition.getDefaultValue());
            inputDefinition.setInputPath(inputDefinition.getSubPropertyInputPath());
            inputDefinition.setType(inputDefinition.getType());
            if (Objects.nonNull(inputDefinition.getParentPropertyType())) {
                ComponentInstanceProperty propertyDefinition = new ComponentInstanceProperty();
                propertyDefinition.setType(inputDefinition.getParentPropertyType());
                inputDefinition.setProperties(Collections.singletonList(propertyDefinition));
            }
            inputDefinitions.add(inputDef);
        }
        return propertyValueConstraintValidationUtil.validatePropertyConstraints(inputDefinitions, applicationDataTypeCache, model);
    }

    public Either<List<ComponentInstanceInput>, ResponseFormat> getInputsForComponentInput(String userId, String componentId, String inputId) {
        validateUserExists(userId);
        Component component = null;
        ComponentParametersView filters = new ComponentParametersView();
        filters.disableAll();
        filters.setIgnoreComponentInstances(false);
        filters.setIgnoreInputs(false);
        filters.setIgnoreComponentInstancesInputs(false);
        filters.setIgnoreProperties(false);
        Either<Component, StorageOperationStatus> getComponentEither = toscaOperationFacade
            .getToscaElement(componentId, filters);
        if (getComponentEither.isRight()) {
            ActionStatus actionStatus = componentsUtils.convertFromStorageResponse(getComponentEither.right().value());
            log.debug(FAILED_TO_FOUND_COMPONENT_ERROR, componentId, actionStatus);
            return Either.right(componentsUtils.getResponseFormat(actionStatus));
        }
        component = getComponentEither.left().value();
        Optional<InputDefinition> op = component.getInputs().stream().filter(in -> in.getUniqueId().equals(inputId)).findFirst();
        if (!op.isPresent()) {
            ActionStatus actionStatus = componentsUtils.convertFromStorageResponse(getComponentEither.right().value());
            log.debug(FAILED_TO_FOUND_INPUT_UNDER_COMPONENT_ERROR, inputId, componentId, actionStatus);
            return Either.right(componentsUtils.getResponseFormat(actionStatus));
        }
        return Either.left(componentInstanceBusinessLogic.getComponentInstanceInputsByInputId(component, inputId));
    }

    @Override
    public Either<List<InputDefinition>, ResponseFormat> declareProperties(String userId, String componentId, ComponentTypeEnum componentTypeEnum,
                                                                           ComponentInstInputsMap componentInstInputsMap) {
        return createMultipleInputs(userId, componentId, componentTypeEnum, componentInstInputsMap, true, false);
    }

    private Either<List<InputDefinition>, ResponseFormat> createMultipleInputs(String userId, String componentId, ComponentTypeEnum componentType,
                                                                               ComponentInstInputsMap componentInstInputsMapUi,
                                                                               boolean shouldLockComp,
                                                                               boolean inTransaction) {
        Either<List<InputDefinition>, ResponseFormat> result = null;
        Component component = null;
        try {
            validateUserExists(userId);
            component = getAndValidateComponentForCreate(userId, componentId, componentType, shouldLockComp);
            result = propertyDeclarationOrchestrator.declarePropertiesToInputs(component, componentInstInputsMapUi).left()
                .bind(inputsToCreate -> prepareInputsForCreation(userId, componentId, inputsToCreate)).right()
                .map(componentsUtils::getResponseFormat);
            return result;
        } catch (ByResponseFormatComponentException e) {
            log.error("#createMultipleInputs: Exception thrown: ", e);
            result = Either.right(e.getResponseFormat());
            return result;
        } finally {
            if (!inTransaction) {
                if (result == null || result.isRight()) {
                    log.debug(GOING_TO_EXECUTE_ROLLBACK_ON_CREATE_GROUP);
                    janusGraphDao.rollback();
                } else {
                    log.debug(GOING_TO_EXECUTE_COMMIT_ON_CREATE_GROUP);
                    janusGraphDao.commit();
                }
            }
            // unlock resource
            if (shouldLockComp && component != null) {
                graphLockOperation.unlockComponent(componentId, componentType.getNodeType());
            }
        }
    }

    /**
     * Creates a list input with a data type which has properties specified.
     *
     * @param userId             User ID
     * @param componentId        Component ID
     * @param componentType      Component type
     * @param componentListInput Properties to be declared and input to be created
     * @param shouldLockComp     true if the component should be locked
     * @param inTransaction      true if already in transaction
     */
    public Either<List<InputDefinition>, ResponseFormat> createListInput(String userId, String componentId, ComponentTypeEnum componentType,
                                                                         ComponentInstListInput componentListInput, boolean shouldLockComp,
                                                                         boolean inTransaction) {
        Either<List<InputDefinition>, ResponseFormat> result = null;
        Component component = null;
        log.trace("#createListInput: enter");
        try {
            /* check if user exists */
            validateUserExists(userId);

            component = getAndValidateComponentForCreate(userId, componentId, componentType, shouldLockComp);

            InputDefinition listInput = componentListInput.getListInput();
            DataTypeDefinition dataType =
                prepareDataTypeForListInput(componentListInput.getComponentInstInputsMap(), listInput);
            Map<String, DataTypeDefinition> dataTypesMap = new HashMap<>();
            dataTypesMap.put(dataType.getName(), dataType);
            if (log.isDebugEnabled()) {
                log.debug("#createListInput: dataTypesMap={}", ReflectionToStringBuilder.toString(dataTypesMap));
            }

            Either<List<DataTypeDefinition>, StorageOperationStatus> dataTypeResult =
                toscaOperationFacade.addDataTypesToComponent(dataTypesMap, componentId);
            if (dataTypeResult.isRight()) {
                log.debug("#createListInput: DataType creation failed.");
                throw new ByResponseFormatComponentException(componentsUtils.getResponseFormat(dataTypeResult.right().value()));
            }

            // create list input
            listInput.setUniqueId(UniqueIdBuilder.buildPropertyUniqueId(componentId, listInput.getName()));
            listInput.setInstanceUniqueId(
                propertyDeclarationOrchestrator.getPropOwnerId(componentListInput.getComponentInstInputsMap()));
            listInput.setIsDeclaredListInput(true);
            Map<String, InputDefinition> listInputMap = new HashMap<>();
            listInputMap.put(listInput.getName(), listInput);
            result = createListInputsInGraph(listInputMap, dataTypesMap, component);
            if (result.isRight()) {
                log.debug("#createListInput: createListInputsInGraph failed.");
                throw new ByResponseFormatComponentException(result.right().value());
            }

            // update properties
            result = propertyDeclarationOrchestrator
                .declarePropertiesToListInput(component, componentListInput.getComponentInstInputsMap(), listInput)
                .right().map(err -> componentsUtils.getResponseFormat(err))
                .left().map(Arrays::asList);

            log.trace("#createListInput: leave");

            return result;

        } catch (ByResponseFormatComponentException e) {
            log.error("#createListInput: Exception thrown", e);
            result = Either.right(e.getResponseFormat());
            return result;
        } finally {

            if (!inTransaction) {
                if (result == null || result.isRight()) {
                    log.debug(GOING_TO_EXECUTE_ROLLBACK_ON_CREATE_GROUP);
                    janusGraphDao.rollback();
                } else {
                    log.debug(GOING_TO_EXECUTE_COMMIT_ON_CREATE_GROUP);
                    janusGraphDao.commit();
                }
            }
            // unlock resource
            if (shouldLockComp && component != null) {
                graphLockOperation.unlockComponent(componentId, componentType.getNodeType());
            }
        }
    }

    private ComponentParametersView getBaseComponentParametersView() {
        ComponentParametersView componentParametersView = new ComponentParametersView();
        componentParametersView.disableAll();
        componentParametersView.setIgnoreInputs(false);
        componentParametersView.setIgnoreComponentInstances(false);
        componentParametersView.setIgnoreComponentInstancesInputs(false);
        componentParametersView.setIgnoreComponentInstancesProperties(false);
        componentParametersView.setIgnorePolicies(false);
        componentParametersView.setIgnoreGroups(false);
        componentParametersView.setIgnoreUsers(false);
        return componentParametersView;
    }

    private Component getAndValidateComponentForCreate(
        String userId, String componentId, ComponentTypeEnum componentType, boolean shouldLockComp
    ) {
        ComponentParametersView componentParametersView = getBaseComponentParametersView();
        Component component = validateComponentExists(componentId, componentType, componentParametersView);
        if (shouldLockComp) {
            // lock the component
            lockComponent(component, CREATE_INPUT);
        }
        validateCanWorkOnComponent(component, userId);
        return component;
    }

    private DataTypeDefinition prepareDataTypeForListInput(ComponentInstInputsMap inputsMap, InputDefinition input) {
        // Confirm if type is list
        if (StringUtils.isEmpty(input.getType()) || !input.getType().equals(ToscaPropertyType.LIST.getType())) {
            log.debug("#prepareDataTypeForListInput: Type of input is not list.");
            throw new ByResponseFormatComponentException(componentsUtils.getResponseFormat(ActionStatus.INVALID_PROPERTY_TYPE));
        }

        // Confirm schema type is not empty
        String desiredTypeName = input.getSchemaType();
        if (StringUtils.isEmpty(desiredTypeName)) {
            log.debug("#prepareDataTypeForListInput: Schema type of list input is empty.");
            throw new ByResponseFormatComponentException(componentsUtils.getResponseFormat(ActionStatus.INVALID_PROPERTY_INNER_TYPE));
        }

        DataTypeDefinition dataType = new DataTypeDefinition();
        List<ComponentInstancePropInput> propInputs = inputsMap.resolvePropertiesToDeclare().getRight();
        dataType.setName(desiredTypeName);
        dataType.setDerivedFromName(ToscaPropertyType.ROOT.getType());
        // Copy properties from inputsMap
        dataType.setProperties(propInputs.stream().map(PropertyDefinition::new).collect(Collectors.toList()));
        return dataType;
    }

    private Either<List<InputDefinition>, StorageOperationStatus> prepareInputsForCreation(String userId, String cmptId,
                                                                                           List<InputDefinition> inputsToCreate) {
        Map<String, InputDefinition> inputsToPersist = MapUtil.toMap(inputsToCreate, InputDefinition::getName);
        assignOwnerIdToInputs(userId, inputsToPersist);
        inputsToPersist.values()
            .forEach(input -> input.setConstraints(componentInstanceBusinessLogic.setInputConstraint(input)));

        return toscaOperationFacade.addInputsToComponent(inputsToPersist, cmptId)
            .left()
            .map(persistedInputs -> inputsToCreate);
    }

    private void assignOwnerIdToInputs(String userId, Map<String, InputDefinition> inputsToCreate) {
        inputsToCreate.values().forEach(inputDefinition -> inputDefinition.setOwnerId(userId));
    }

    public Either<List<InputDefinition>, ResponseFormat> createInputsInGraph(Map<String, InputDefinition> inputs,
                                                                             Component component) {

        List<InputDefinition> resourceProperties = component.getInputs();

        final Map<String, DataTypeDefinition> dataTypes = componentsUtils.getAllDataTypes(applicationDataTypeCache, component.getModel());

        for (Map.Entry<String, InputDefinition> inputDefinition : inputs.entrySet()) {
            String inputName = inputDefinition.getKey();
            inputDefinition.getValue().setName(inputName);

            Either<InputDefinition, ResponseFormat> preparedInputEither = prepareAndValidateInputBeforeCreate(inputDefinition.getValue(), dataTypes);
            if (preparedInputEither.isRight()) {
                return Either.right(preparedInputEither.right().value());
            }

        }
        if (resourceProperties != null) {
            Map<String, InputDefinition> generatedInputs = resourceProperties.stream()
                .collect(Collectors.toMap(PropertyDataDefinition::getName, i -> i));
            Either<Map<String, InputDefinition>, String> mergeEither = ToscaDataDefinition.mergeDataMaps(generatedInputs, inputs);
            if (mergeEither.isRight()) {
                return Either.right(componentsUtils.getResponseFormat(ActionStatus.PROPERTY_ALREADY_EXIST, mergeEither.right().value()));
            }
            inputs = mergeEither.left().value();
        }

        Either<List<InputDefinition>, StorageOperationStatus> associateInputsEither = toscaOperationFacade
            .createAndAssociateInputs(inputs, component.getUniqueId());
        if (associateInputsEither.isRight()) {
            log.debug("Failed to create inputs under component {}. Status is {}", component.getUniqueId(), associateInputsEither.right().value());

            return Either.right(componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(associateInputsEither.right().value())));
        }
        return Either.left(associateInputsEither.left().value());
    }

    private Either<List<InputDefinition>, ResponseFormat> createListInputsInGraph(Map<String, InputDefinition> inputs,
                                                                                  Map<String, DataTypeDefinition> privateDataTypes,
                                                                                  Component component) {

        log.trace("#createListInputsInGraph: enter");

        Map<String, DataTypeDefinition> dataTypes = componentsUtils.getAllDataTypes(applicationDataTypeCache, component.getModel());
        dataTypes.putAll(privateDataTypes);

        for (Map.Entry<String, InputDefinition> inputDefinition : inputs.entrySet()) {
            String inputName = inputDefinition.getKey();
            inputDefinition.getValue().setName(inputName);

            Either<InputDefinition, ResponseFormat> preparedInputEither =
                prepareAndValidateInputBeforeCreate(inputDefinition.getValue(), dataTypes);
            if (preparedInputEither.isRight()) {
                return Either.right(preparedInputEither.right().value());
            }
        }

        Either<List<InputDefinition>, StorageOperationStatus> addInputsEither = toscaOperationFacade
            .addInputsToComponent(inputs, component.getUniqueId());
        if (addInputsEither.isRight()) {
            log.debug("#createListInputsInGraph: Failed to create inputs under component {}. Status is {}",
                component.getUniqueId(), addInputsEither.right().value());
            return Either.right(componentsUtils.getResponseFormat(
                componentsUtils.convertFromStorageResponse(addInputsEither.right().value())));
        }
        log.trace("#createListInputsInGraph: leave");
        return Either.left(addInputsEither.left().value());
    }

    /**
     * Delete input from service
     *
     * @param componentId
     * @param userId
     * @param inputId
     * @return
     */
    public InputDefinition deleteInput(String componentId, String userId, String inputId) {
        Either<InputDefinition, ResponseFormat> deleteEither = null;
        if (log.isDebugEnabled()) {
            log.debug("Going to delete input id: {}", inputId);
        }
        validateUserExists(userId);
        ComponentParametersView componentParametersView = getBaseComponentParametersView();
        componentParametersView.setIgnoreInterfaces(false);
        componentParametersView.setIgnoreDataType(false);
        componentParametersView.setIgnoreProperties(false);
        Either<Component, StorageOperationStatus> componentEither = toscaOperationFacade
            .getToscaElement(componentId, componentParametersView);
        if (componentEither.isRight()) {
            throw new ByActionStatusComponentException(componentsUtils.convertFromStorageResponse(componentEither.right().value()));
        }
        Component component = componentEither.left().value();
        // Validate inputId is child of the component
        Optional<InputDefinition> optionalInput = component.getInputs().stream().
            // filter by ID
                filter(input -> input.getUniqueId().equals(inputId)).
            // Get the input
                findAny();
        if (!optionalInput.isPresent()) {
            throw new ByActionStatusComponentException(ActionStatus.INPUT_IS_NOT_CHILD_OF_COMPONENT, inputId, componentId);
        }
        InputDefinition inputForDelete = optionalInput.get();
        // Lock component
        lockComponent(componentId, component, "deleteInput");
        // Delete input operations
        boolean failed = false;
        try {
            StorageOperationStatus status = toscaOperationFacade.deleteInputOfResource(component, inputForDelete.getName());
            if (status != StorageOperationStatus.OK) {
                log.debug("Component id: {} delete input id: {} failed", componentId, inputId);
                throw new ByActionStatusComponentException(componentsUtils.convertFromStorageResponse(status), component.getName());
            }
            if (BooleanUtils.isTrue(inputForDelete.getIsDeclaredListInput())) {
                deleteEither = deleteListInput(componentId, inputId, component, inputForDelete, status);
                if (deleteEither.isRight()) {
                    throw new ByResponseFormatComponentException(deleteEither.right().value());
                }
                return deleteEither.left().value();
            }
            StorageOperationStatus storageOperationStatus = propertyDeclarationOrchestrator.unDeclarePropertiesAsInputs(component, inputForDelete);
            if (storageOperationStatus != StorageOperationStatus.OK) {
                log.debug("Component id: {} update properties declared as input for input id: {} failed", componentId, inputId);
                throw new ByActionStatusComponentException(componentsUtils.convertFromStorageResponse(storageOperationStatus), component.getName());
            }
            return inputForDelete;
        } catch (ComponentException e) {
            failed = true;
            throw e;
        } finally {
            unlockComponent(failed, component);
        }
    }

    private Either<InputDefinition, ResponseFormat> deleteListInput(String componentId, String inputId,
                                                                    Component component, InputDefinition inputForDelete,
                                                                    StorageOperationStatus status) {
        // the input is created by 'Declare List'.
        // need to 1. undeclare properties, 2. delete input, 3. delete private data type
        StorageOperationStatus storageOperationStatus = propertyDeclarationOrchestrator.unDeclarePropertiesAsListInputs(component, inputForDelete);
        if (storageOperationStatus != StorageOperationStatus.OK) {
            log.debug("Component id: {} update properties declared as input for input id: {} failed", componentId, inputId);
            return Either.right(componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(status), component.getName()));
        }
        Either<DataTypeDefinition, StorageOperationStatus> deleteResult = dataTypeBusinessLogic
            .deletePrivateDataType(component, inputForDelete.getSchemaType());
        if (deleteResult.isRight()) {
            log.debug("Component id: {} delete datatype name: {} failed", componentId, inputForDelete.getSchemaType());
            return Either.right(
                componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(deleteResult.right().value()), component.getName()));
        }
        log.trace("deleteInput: deletePrivateDataType (OK)");
        return Either.left(inputForDelete);
    }

    private Either<InputDefinition, ResponseFormat> prepareAndValidateInputBeforeCreate(InputDefinition newInputDefinition,
                                                                                        Map<String, DataTypeDefinition> dataTypes) {
        // validate input default values
        Either<Boolean, ResponseFormat> defaultValuesValidation = validatePropertyDefaultValue(newInputDefinition, dataTypes);
        if (defaultValuesValidation.isRight()) {
            return Either.right(defaultValuesValidation.right().value());
        }
        // convert property
        ToscaPropertyType type = getType(newInputDefinition.getType());
        if (type != null) {
            PropertyValueConverter converter = type.getConverter();
            // get inner type
            SchemaDefinition schema = newInputDefinition.getSchema();
            String innerType = null;
            if (schema != null) {
                PropertyDataDefinition prop = schema.getProperty();
                if (prop != null) {
                    innerType = prop.getType();
                }
            }
            String convertedValue;
            if (newInputDefinition.getDefaultValue() != null) {
                convertedValue = converter.convert(newInputDefinition.getDefaultValue(), innerType, dataTypes);
                newInputDefinition.setDefaultValue(convertedValue);
            }
        }
        return Either.left(newInputDefinition);
    }

    public Either<InputDefinition, ResponseFormat> getInputsAndPropertiesForComponentInput(String userId, String componentId, String inputId,
                                                                                           boolean inTransaction) {
        Either<InputDefinition, ResponseFormat> result = null;
        try {
            validateUserExists(userId);
            ComponentParametersView filters = new ComponentParametersView();
            filters.disableAll();
            filters.setIgnoreComponentInstances(false);
            filters.setIgnoreInputs(false);
            filters.setIgnoreComponentInstancesInputs(false);
            filters.setIgnoreComponentInstancesProperties(false);
            filters.setIgnoreProperties(false);
            Either<Component, StorageOperationStatus> getComponentEither = toscaOperationFacade
                .getToscaElement(componentId, filters);
            if (getComponentEither.isRight()) {
                ActionStatus actionStatus = componentsUtils.convertFromStorageResponse(getComponentEither.right().value());
                log.debug(FAILED_TO_FOUND_COMPONENT_ERROR, componentId, actionStatus);
                return Either.right(componentsUtils.getResponseFormat(actionStatus));
            }
            Component component = getComponentEither.left().value();
            Optional<InputDefinition> op = component.getInputs().stream().filter(in -> in.getUniqueId().equals(inputId)).findFirst();
            if (!op.isPresent()) {
                ActionStatus actionStatus = componentsUtils.convertFromStorageResponse(getComponentEither.right().value());
                log.debug(FAILED_TO_FOUND_INPUT_UNDER_COMPONENT_ERROR, inputId, componentId, actionStatus);
                return Either.right(componentsUtils.getResponseFormat(actionStatus));
            }
            InputDefinition resObj = op.get();
            List<ComponentInstanceInput> inputCIInput = componentInstanceBusinessLogic.getComponentInstanceInputsByInputId(component, inputId);
            resObj.setInputs(inputCIInput);
            List<ComponentInstanceProperty> inputProps = componentInstanceBusinessLogic.getComponentInstancePropertiesByInputId(component, inputId);
            resObj.setProperties(inputProps);
            result = Either.left(resObj);
            return result;
        } finally {
            if (!inTransaction) {
                if (result == null || result.isRight()) {
                    log.debug(GOING_TO_EXECUTE_ROLLBACK_ON_CREATE_GROUP);
                    janusGraphDao.rollback();
                } else {
                    log.debug(GOING_TO_EXECUTE_COMMIT_ON_CREATE_GROUP);
                    janusGraphDao.commit();
                }
            }
        }
    }

    public Either<EntryData<String, InputDefinition>, ResponseFormat> addInputToComponent(String componentId, String inputName,
                                                                                          InputDefinition newInputDefinition, String userId) {
        Either<EntryData<String, InputDefinition>, ResponseFormat> result = null;
        validateUserExists(userId);
        Either<Component, StorageOperationStatus> serviceElement = toscaOperationFacade.getToscaElement(componentId);
        if (serviceElement.isRight()) {
            result = Either.right(componentsUtils.getResponseFormat(ActionStatus.RESOURCE_NOT_FOUND, ""));
            return result;
        }
        Component component = serviceElement.left().value();
        NodeTypeEnum nodeType = component.getComponentType().getNodeType();
        StorageOperationStatus lockResult = graphLockOperation.lockComponent(componentId, nodeType);
        if (!lockResult.equals(StorageOperationStatus.OK)) {
            BeEcompErrorManager.getInstance().logBeFailedLockObjectError(CREATE_INPUT, nodeType.name().toLowerCase(), componentId);
            log.info("Failed to lock component {}. Error - {}", componentId, lockResult);
            result = Either.right(componentsUtils.getResponseFormat(ActionStatus.GENERAL_ERROR));
            return result;
        }
        try {
            if (!ComponentValidationUtils.canWorkOnComponent(component, userId)) {
                result = Either.right(componentsUtils.getResponseFormat(ActionStatus.RESTRICTED_OPERATION));
                return result;
            }
            List<InputDefinition> inputs = component.getInputs();
            if (CollectionUtils.isEmpty(inputs)) {
                inputs = new ArrayList<>();
            }
            if (isInputExistInComponent(inputs, inputName)) {
                result = Either.right(componentsUtils.getResponseFormat(ActionStatus.INPUT_ALREADY_EXIST, inputName));
                return result;
            }
            Map<String, DataTypeDefinition> allDataTypes = componentsUtils.getAllDataTypes(applicationDataTypeCache, component.getModel());
            // validate input default values
            Either<Boolean, ResponseFormat> defaultValuesValidation = validatePropertyDefaultValue(newInputDefinition, allDataTypes);
            if (defaultValuesValidation.isRight()) {
                result = Either.right(defaultValuesValidation.right().value());
                return result;
            }
            // convert Input
            ToscaPropertyType type = getType(newInputDefinition.getType());
            if (type != null) {
                PropertyValueConverter converter = type.getConverter();
                // get inner type
                String innerType = null;
                SchemaDefinition schema = newInputDefinition.getSchema();
                if (schema != null) {
                    PropertyDataDefinition prop = schema.getProperty();
                    if (prop != null) {
                        innerType = prop.getType();
                    }
                }
                if (newInputDefinition.getDefaultValue() != null) {
                    String convertedValue = converter.convert(newInputDefinition.getDefaultValue(), innerType, allDataTypes);
                    newInputDefinition.setDefaultValue(convertedValue);
                }
            }
            newInputDefinition.setMappedToComponentProperty(false);
            Either<InputDefinition, StorageOperationStatus> addInputEither = toscaOperationFacade
                .addInputToComponent(inputName, newInputDefinition, component);
            if (addInputEither.isRight()) {
                log.info("Failed to add new input {}. Error - {}", componentId, addInputEither.right().value());
                result = Either.right(componentsUtils.getResponseFormat(ActionStatus.GENERAL_ERROR));
                return result;
            }
            result = Either.left(new EntryData<>(inputName, newInputDefinition));
            return result;
        } finally {
            commitOrRollback(result);
            // unlock component
            graphLockOperation.unlockComponent(componentId, nodeType);
        }
    }

    private boolean isInputExistInComponent(List<InputDefinition> inputs, String inputName) {
        return CollectionUtils.isNotEmpty(inputs) && inputs.stream().anyMatch(input -> input.getName().equals(inputName));
    }
}