Service Import - Node Template Interface Definitions
[sdc.git] / catalog-model / src / main / java / org / openecomp / sdc / be / model / jsonjanusgraph / operations / ToscaOperationFacade.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 package org.openecomp.sdc.be.model.jsonjanusgraph.operations;
21
22 import com.vdurmont.semver4j.Semver;
23 import com.vdurmont.semver4j.Semver.SemverType;
24 import fj.data.Either;
25 import org.apache.commons.collections.CollectionUtils;
26 import org.apache.commons.collections.MapUtils;
27 import org.apache.commons.lang3.StringUtils;
28 import org.apache.commons.lang3.tuple.ImmutablePair;
29 import org.apache.tinkerpop.gremlin.structure.Direction;
30 import org.apache.tinkerpop.gremlin.structure.Edge;
31 import org.janusgraph.graphdb.query.JanusGraphPredicate;
32 import org.openecomp.sdc.be.config.Configuration;
33 import org.openecomp.sdc.be.config.ConfigurationManager;
34 import org.openecomp.sdc.be.dao.api.exception.JanusGraphException;
35 import org.openecomp.sdc.be.dao.janusgraph.HealingJanusGraphDao;
36 import org.openecomp.sdc.be.dao.janusgraph.JanusGraphOperationStatus;
37 import org.openecomp.sdc.be.dao.jsongraph.GraphVertex;
38 import org.openecomp.sdc.be.dao.jsongraph.types.EdgeLabelEnum;
39 import org.openecomp.sdc.be.dao.jsongraph.types.JsonParseFlagEnum;
40 import org.openecomp.sdc.be.dao.jsongraph.types.VertexTypeEnum;
41 import org.openecomp.sdc.be.datatypes.elements.ArtifactDataDefinition;
42 import org.openecomp.sdc.be.datatypes.elements.AttributeDataDefinition;
43 import org.openecomp.sdc.be.datatypes.elements.CapabilityDataDefinition;
44 import org.openecomp.sdc.be.datatypes.elements.ComponentInstanceDataDefinition;
45 import org.openecomp.sdc.be.datatypes.elements.DataTypeDataDefinition;
46 import org.openecomp.sdc.be.datatypes.elements.GroupDataDefinition;
47 import org.openecomp.sdc.be.datatypes.elements.InputDataDefinition;
48 import org.openecomp.sdc.be.datatypes.elements.InterfaceDataDefinition;
49 import org.openecomp.sdc.be.datatypes.elements.ListCapabilityDataDefinition;
50 import org.openecomp.sdc.be.datatypes.elements.ListRequirementDataDefinition;
51 import org.openecomp.sdc.be.datatypes.elements.MapArtifactDataDefinition;
52 import org.openecomp.sdc.be.datatypes.elements.MapAttributesDataDefinition;
53 import org.openecomp.sdc.be.datatypes.elements.MapCapabilityProperty;
54 import org.openecomp.sdc.be.datatypes.elements.MapInterfaceDataDefinition;
55 import org.openecomp.sdc.be.datatypes.elements.MapListCapabilityDataDefinition;
56 import org.openecomp.sdc.be.datatypes.elements.MapListRequirementDataDefinition;
57 import org.openecomp.sdc.be.datatypes.elements.MapPropertiesDataDefinition;
58 import org.openecomp.sdc.be.datatypes.elements.OperationDataDefinition;
59 import org.openecomp.sdc.be.datatypes.elements.PropertyDataDefinition;
60 import org.openecomp.sdc.be.datatypes.elements.RequirementDataDefinition;
61 import org.openecomp.sdc.be.datatypes.enums.ComponentTypeEnum;
62 import org.openecomp.sdc.be.datatypes.enums.GraphPropertyEnum;
63 import org.openecomp.sdc.be.datatypes.enums.JsonPresentationFields;
64 import org.openecomp.sdc.be.datatypes.enums.NodeTypeEnum;
65 import org.openecomp.sdc.be.datatypes.enums.OriginTypeEnum;
66 import org.openecomp.sdc.be.datatypes.enums.PromoteVersionEnum;
67 import org.openecomp.sdc.be.datatypes.enums.ResourceTypeEnum;
68 import org.openecomp.sdc.be.model.ArtifactDefinition;
69 import org.openecomp.sdc.be.model.AttributeDefinition;
70 import org.openecomp.sdc.be.model.CapabilityDefinition;
71 import org.openecomp.sdc.be.model.CatalogUpdateTimestamp;
72 import org.openecomp.sdc.be.model.Component;
73 import org.openecomp.sdc.be.model.ComponentInstance;
74 import org.openecomp.sdc.be.model.ComponentInstanceAttribute;
75 import org.openecomp.sdc.be.model.ComponentInstanceInput;
76 import org.openecomp.sdc.be.model.ComponentInstanceInterface;
77 import org.openecomp.sdc.be.model.ComponentInstanceOutput;
78 import org.openecomp.sdc.be.model.ComponentInstanceProperty;
79 import org.openecomp.sdc.be.model.ComponentParametersView;
80 import org.openecomp.sdc.be.model.DataTypeDefinition;
81 import org.openecomp.sdc.be.model.DistributionStatusEnum;
82 import org.openecomp.sdc.be.model.GroupDefinition;
83 import org.openecomp.sdc.be.model.GroupInstance;
84 import org.openecomp.sdc.be.model.InputDefinition;
85 import org.openecomp.sdc.be.model.InterfaceDefinition;
86 import org.openecomp.sdc.be.model.LifecycleStateEnum;
87 import org.openecomp.sdc.be.model.OutputDefinition;
88 import org.openecomp.sdc.be.model.PolicyDefinition;
89 import org.openecomp.sdc.be.model.PropertyDefinition;
90 import org.openecomp.sdc.be.model.RelationshipInfo;
91 import org.openecomp.sdc.be.model.RequirementCapabilityRelDef;
92 import org.openecomp.sdc.be.model.RequirementDefinition;
93 import org.openecomp.sdc.be.model.Resource;
94 import org.openecomp.sdc.be.model.Service;
95 import org.openecomp.sdc.be.model.UploadInterfaceInfo;
96 import org.openecomp.sdc.be.model.User;
97 import org.openecomp.sdc.be.model.catalog.CatalogComponent;
98 import org.openecomp.sdc.be.model.jsonjanusgraph.config.ContainerInstanceTypesData;
99 import org.openecomp.sdc.be.model.jsonjanusgraph.datamodel.TopologyTemplate;
100 import org.openecomp.sdc.be.model.jsonjanusgraph.datamodel.ToscaElement;
101 import org.openecomp.sdc.be.model.jsonjanusgraph.operations.exception.ToscaOperationExceptionSupplier;
102 import org.openecomp.sdc.be.model.jsonjanusgraph.utils.ModelConverter;
103 import org.openecomp.sdc.be.model.operations.StorageException;
104 import org.openecomp.sdc.be.model.operations.api.IGraphLockOperation;
105 import org.openecomp.sdc.be.model.operations.api.StorageOperationStatus;
106 import org.openecomp.sdc.be.model.operations.impl.DaoStatusConverter;
107 import org.openecomp.sdc.be.model.operations.impl.UniqueIdBuilder;
108 import org.openecomp.sdc.be.model.utils.GroupUtils;
109 import org.openecomp.sdc.be.resources.data.ComponentMetadataData;
110 import org.openecomp.sdc.common.jsongraph.util.CommonUtility;
111 import org.openecomp.sdc.common.jsongraph.util.CommonUtility.LogLevelEnum;
112 import org.openecomp.sdc.common.log.enums.EcompLoggerErrorCode;
113 import org.openecomp.sdc.common.log.wrappers.Logger;
114 import org.openecomp.sdc.common.util.ValidationUtils;
115 import org.springframework.beans.factory.annotation.Autowired;
116
117 import java.util.ArrayList;
118 import java.util.Arrays;
119 import java.util.Collection;
120 import java.util.Collections;
121 import java.util.Comparator;
122 import java.util.EnumMap;
123 import java.util.HashMap;
124 import java.util.HashSet;
125 import java.util.Iterator;
126 import java.util.LinkedList;
127 import java.util.List;
128 import java.util.Map;
129 import java.util.Map.Entry;
130 import java.util.Objects;
131 import java.util.Optional;
132 import java.util.Set;
133 import java.util.TreeSet;
134 import java.util.function.BiPredicate;
135 import java.util.stream.Collectors;
136
137 import static java.util.Objects.requireNonNull;
138 import static org.apache.commons.collections.CollectionUtils.isEmpty;
139 import static org.apache.commons.collections.CollectionUtils.isNotEmpty;
140 import static org.janusgraph.core.attribute.Text.REGEX;
141
142 @org.springframework.stereotype.Component("tosca-operation-facade")
143 public class ToscaOperationFacade {
144
145     // region - ToscaElement - GetById
146     public static final String PROXY_SUFFIX = "_proxy";
147     // region - Fields
148     private static final String COULDNT_FETCH_A_COMPONENT_WITH_AND_UNIQUE_ID_ERROR = "Couldn't fetch a component with and UniqueId {}, error: {}";
149     private static final String FAILED_TO_FIND_RECENTLY_ADDED_PROPERTY_ON_THE_RESOURCE_STATUS_IS = "Failed to find recently added property {} on the resource {}. Status is {}. ";
150     private static final String FAILED_TO_GET_UPDATED_RESOURCE_STATUS_IS = "Failed to get updated resource {}. Status is {}. ";
151     private static final String FAILED_TO_ADD_THE_PROPERTY_TO_THE_RESOURCE_STATUS_IS = "Failed to add the property {} to the resource {}. Status is {}. ";
152     private static final String SERVICE = "service";
153     private static final String VF = "VF";
154     private static final String NOT_SUPPORTED_COMPONENT_TYPE = "Not supported component type {}";
155     private static final String COMPONENT_CREATED_SUCCESSFULLY = "Component created successfully!!!";
156     private static final String INPUTS_ASSOCIATED_TO_COMPONENT_SUCCESSFULLY = "Inputs associated to component successfully!";
157     private static final String OUTPUTS_ASSOCIATED_TO_COMPONENT_SUCCESSFULLY = "Outputs associated to component successfully!";
158     private static final String COULDNT_FETCH_COMPONENT_WITH_AND_UNIQUE_ID_ERROR = "Couldn't fetch component with and unique id {}, error: {}";
159     private static final Logger log = Logger.getLogger(ToscaOperationFacade.class.getName());
160     @Autowired
161     private IGraphLockOperation graphLockOperation;
162     @Autowired
163     private NodeTypeOperation nodeTypeOperation;
164     @Autowired
165     private TopologyTemplateOperation topologyTemplateOperation;
166     @Autowired
167     private NodeTemplateOperation nodeTemplateOperation;
168     @Autowired
169     private GroupsOperation groupsOperation;
170     @Autowired
171     private HealingJanusGraphDao janusGraphDao;
172     // endregion
173     @Autowired
174     private ContainerInstanceTypesData containerInstanceTypesData;
175
176     private static Optional<CapabilityDefinition> getPropertyCapability(String propertyParentUniqueId, Component containerComponent) {
177         Map<String, List<CapabilityDefinition>> componentCapabilities = containerComponent.getCapabilities();
178         if (MapUtils.isEmpty(componentCapabilities)) {
179             return Optional.empty();
180         }
181         List<CapabilityDefinition> capabilityDefinitionList = componentCapabilities.values().stream().flatMap(Collection::stream)
182             .collect(Collectors.toList());
183         if (CollectionUtils.isEmpty(capabilityDefinitionList)) {
184             return Optional.empty();
185         }
186         return capabilityDefinitionList.stream().filter(capabilityDefinition -> capabilityDefinition.getUniqueId().equals(propertyParentUniqueId))
187             .findAny();
188     }
189
190     public <T extends Component> Either<T, StorageOperationStatus> getToscaFullElement(String componentId) {
191         ComponentParametersView filters = new ComponentParametersView();
192         filters.setIgnoreCapabiltyProperties(false);
193         filters.setIgnoreServicePath(false);
194         return getToscaElement(componentId, filters);
195     }
196
197     public <T extends Component> Either<T, StorageOperationStatus> getToscaElement(String componentId) {
198         return getToscaElement(componentId, JsonParseFlagEnum.ParseAll);
199     }
200
201     public <T extends Component> Either<T, StorageOperationStatus> getToscaElement(String componentId, ComponentParametersView filters) {
202         Either<GraphVertex, JanusGraphOperationStatus> getVertexEither = janusGraphDao.getVertexById(componentId, filters.detectParseFlag());
203         if (getVertexEither.isRight()) {
204             log.debug(COULDNT_FETCH_COMPONENT_WITH_AND_UNIQUE_ID_ERROR, componentId, getVertexEither.right().value());
205             return Either.right(DaoStatusConverter.convertJanusGraphStatusToStorageStatus(getVertexEither.right().value()));
206         }
207         return getToscaElementByOperation(getVertexEither.left().value(), filters);
208     }
209
210     public <T extends Component> Either<T, StorageOperationStatus> getToscaElement(String componentId, JsonParseFlagEnum parseFlag) {
211         Either<GraphVertex, JanusGraphOperationStatus> getVertexEither = janusGraphDao.getVertexById(componentId, parseFlag);
212         if (getVertexEither.isRight()) {
213             log.debug(COULDNT_FETCH_COMPONENT_WITH_AND_UNIQUE_ID_ERROR, componentId, getVertexEither.right().value());
214             return Either.right(DaoStatusConverter.convertJanusGraphStatusToStorageStatus(getVertexEither.right().value()));
215         }
216         return getToscaElementByOperation(getVertexEither.left().value());
217     }
218
219     public <T extends Component> Either<T, StorageOperationStatus> getToscaElement(GraphVertex componentVertex) {
220         return getToscaElementByOperation(componentVertex);
221     }
222
223     public Either<Boolean, StorageOperationStatus> validateComponentExists(String componentId) {
224         Either<GraphVertex, JanusGraphOperationStatus> getVertexEither = janusGraphDao.getVertexById(componentId, JsonParseFlagEnum.NoParse);
225         if (getVertexEither.isRight()) {
226             JanusGraphOperationStatus status = getVertexEither.right().value();
227             if (status == JanusGraphOperationStatus.NOT_FOUND) {
228                 return Either.left(false);
229             } else {
230                 log.debug(COULDNT_FETCH_COMPONENT_WITH_AND_UNIQUE_ID_ERROR, componentId, getVertexEither.right().value());
231                 return Either.right(DaoStatusConverter.convertJanusGraphStatusToStorageStatus(getVertexEither.right().value()));
232             }
233         }
234         return Either.left(true);
235     }
236     // endregion
237
238     public <T extends Component> Either<T, StorageOperationStatus> findLastCertifiedToscaElementByUUID(T component) {
239         Map<GraphPropertyEnum, Object> props = new EnumMap<>(GraphPropertyEnum.class);
240         props.put(GraphPropertyEnum.UUID, component.getUUID());
241         props.put(GraphPropertyEnum.STATE, LifecycleStateEnum.CERTIFIED.name());
242         props.put(GraphPropertyEnum.IS_HIGHEST_VERSION, true);
243         Either<List<GraphVertex>, JanusGraphOperationStatus> getVertexEither = janusGraphDao
244             .getByCriteria(ModelConverter.getVertexType(component), props);
245         if (getVertexEither.isRight()) {
246             log.debug(COULDNT_FETCH_COMPONENT_WITH_AND_UNIQUE_ID_ERROR, component.getUniqueId(), getVertexEither.right().value());
247             return Either.right(DaoStatusConverter.convertJanusGraphStatusToStorageStatus(getVertexEither.right().value()));
248         }
249         return getToscaElementByOperation(getVertexEither.left().value().get(0));
250     }
251
252     // region - ToscaElement - GetByOperation
253     private <T extends Component> Either<T, StorageOperationStatus> getToscaElementByOperation(GraphVertex componentV) {
254         return getToscaElementByOperation(componentV, new ComponentParametersView());
255     }
256
257     private <T extends Component> Either<T, StorageOperationStatus> getToscaElementByOperation(GraphVertex componentV,
258                                                                                                ComponentParametersView filters) {
259         if (componentV == null) {
260             log.debug("Unexpected null value for `componentV`");
261             return Either.right(StorageOperationStatus.GENERAL_ERROR);
262         } else {
263             VertexTypeEnum label = componentV.getLabel();
264             ToscaElementOperation toscaOperation = getToscaElementOperation(componentV);
265             if (toscaOperation != null) {
266                 log.debug("getToscaElementByOperation: toscaOperation={}", toscaOperation.getClass());
267             }
268             Either<ToscaElement, StorageOperationStatus> toscaElement;
269             String componentId = componentV.getUniqueId();
270             if (toscaOperation != null) {
271                 log.debug("Need to fetch tosca element for id {}", componentId);
272                 toscaElement = toscaOperation.getToscaElement(componentV, filters);
273             } else {
274                 log.debug("not supported tosca type {} for id {}", label, componentId);
275                 toscaElement = Either.right(StorageOperationStatus.BAD_REQUEST);
276             }
277             return toscaElement.left().map(ModelConverter::convertFromToscaElement);
278         }
279     }
280
281     // endregion
282     private ToscaElementOperation getToscaElementOperation(GraphVertex componentV) {
283         VertexTypeEnum label = componentV.getLabel();
284         switch (label) {
285             case NODE_TYPE:
286                 return nodeTypeOperation;
287             case TOPOLOGY_TEMPLATE:
288                 return topologyTemplateOperation;
289             default:
290                 return null;
291         }
292     }
293
294     public <T extends Component> Either<T, StorageOperationStatus> createToscaComponent(T resource) {
295         ToscaElement toscaElement = ModelConverter.convertToToscaElement(resource);
296         ToscaElementOperation toscaElementOperation = getToscaElementOperation(resource);
297         Either<ToscaElement, StorageOperationStatus> createToscaElement = toscaElementOperation.createToscaElement(toscaElement);
298         if (createToscaElement.isLeft()) {
299             log.debug(COMPONENT_CREATED_SUCCESSFULLY);
300             T dataModel = ModelConverter.convertFromToscaElement(createToscaElement.left().value());
301             return Either.left(dataModel);
302         }
303         return Either.right(createToscaElement.right().value());
304     }
305
306     // region - ToscaElement Delete
307     public StorageOperationStatus markComponentToDelete(Component componentToDelete) {
308         if (Boolean.TRUE.equals(componentToDelete.getIsDeleted()) && Boolean.FALSE.equals(componentToDelete.isHighestVersion())) {
309             // component already marked for delete
310             return StorageOperationStatus.OK;
311         } else {
312             Either<GraphVertex, JanusGraphOperationStatus> getResponse = janusGraphDao
313                 .getVertexById(componentToDelete.getUniqueId(), JsonParseFlagEnum.ParseAll);
314             if (getResponse.isRight()) {
315                 log.debug(COULDNT_FETCH_COMPONENT_WITH_AND_UNIQUE_ID_ERROR, componentToDelete.getUniqueId(), getResponse.right().value());
316                 return DaoStatusConverter.convertJanusGraphStatusToStorageStatus(getResponse.right().value());
317             }
318             GraphVertex componentV = getResponse.left().value();
319             // same operation for node type and topology template operations
320             Either<GraphVertex, StorageOperationStatus> result = nodeTypeOperation.markComponentToDelete(componentV);
321             if (result.isRight()) {
322                 return result.right().value();
323             }
324             return StorageOperationStatus.OK;
325         }
326     }
327
328     public <T extends Component> Either<T, StorageOperationStatus> deleteToscaComponent(String componentId) {
329         Either<GraphVertex, JanusGraphOperationStatus> getVertexEither = janusGraphDao.getVertexById(componentId, JsonParseFlagEnum.ParseAll);
330         if (getVertexEither.isRight()) {
331             log.debug("Couldn't fetch component vertex with and unique id {}, error: {}", componentId, getVertexEither.right().value());
332             return Either.right(DaoStatusConverter.convertJanusGraphStatusToStorageStatus(getVertexEither.right().value()));
333         }
334         Either<ToscaElement, StorageOperationStatus> deleteElement = deleteToscaElement(getVertexEither.left().value());
335         if (deleteElement.isRight()) {
336             log.debug("Failed to delete component with and unique id {}, error: {}", componentId, deleteElement.right().value());
337             return Either.right(deleteElement.right().value());
338         }
339         T dataModel = ModelConverter.convertFromToscaElement(deleteElement.left().value());
340         return Either.left(dataModel);
341     }
342
343     private Either<ToscaElement, StorageOperationStatus> deleteToscaElement(GraphVertex componentV) {
344         VertexTypeEnum label = componentV.getLabel();
345         Either<ToscaElement, StorageOperationStatus> toscaElement;
346         Object componentId = componentV.getUniqueId();
347         switch (label) {
348             case NODE_TYPE:
349                 log.debug("Need to fetch node type for id {}", componentId);
350                 toscaElement = nodeTypeOperation.deleteToscaElement(componentV);
351                 break;
352             case TOPOLOGY_TEMPLATE:
353                 log.debug("Need to fetch topology template for id {}", componentId);
354                 toscaElement = topologyTemplateOperation.deleteToscaElement(componentV);
355                 break;
356             default:
357                 log.debug("not supported tosca type {} for id {}", label, componentId);
358                 toscaElement = Either.right(StorageOperationStatus.BAD_REQUEST);
359                 break;
360         }
361         return toscaElement;
362     }
363
364     // endregion
365     private ToscaElementOperation getToscaElementOperation(Component component) {
366         return ModelConverter.isAtomicComponent(component) ? nodeTypeOperation : topologyTemplateOperation;
367     }
368
369     public <T extends Component> Either<T, StorageOperationStatus> getLatestByToscaResourceNameAndModel(final String toscaResourceName,
370                                                                                                         final String model) {
371         return getLatestByNameAndModel(toscaResourceName, JsonParseFlagEnum.ParseMetadata, new ComponentParametersView(), model);
372     }
373
374     private <T extends Component> Either<T, StorageOperationStatus> getLatestByNameAndModel(final String nodeName,
375                                                                                             final JsonParseFlagEnum parseFlag,
376                                                                                             final ComponentParametersView filter,
377                                                                                             final String model) {
378         Either<T, StorageOperationStatus> result;
379         final Map<GraphPropertyEnum, Object> propertiesToMatch = new EnumMap<>(GraphPropertyEnum.class);
380         final Map<GraphPropertyEnum, Object> propertiesNotToMatch = new EnumMap<>(GraphPropertyEnum.class);
381         propertiesToMatch.put(GraphPropertyEnum.TOSCA_RESOURCE_NAME, nodeName);
382         propertiesToMatch.put(GraphPropertyEnum.IS_HIGHEST_VERSION, true);
383         propertiesNotToMatch.put(GraphPropertyEnum.IS_DELETED, true);
384         final Either<List<GraphVertex>, JanusGraphOperationStatus> highestResources = janusGraphDao
385             .getByCriteria(null, propertiesToMatch, propertiesNotToMatch, parseFlag, model);
386         if (highestResources.isRight()) {
387             final JanusGraphOperationStatus status = highestResources.right().value();
388             log.debug("failed to find resource with name {}. status={} ", nodeName, status);
389             result = Either.right(DaoStatusConverter.convertJanusGraphStatusToStorageStatus(status));
390             return result;
391         }
392         final List<GraphVertex> resources = highestResources.left().value();
393         double version = 0.0;
394         GraphVertex highestResource = null;
395         for (final GraphVertex vertex : resources) {
396             final Object versionObj = vertex.getMetadataProperty(GraphPropertyEnum.VERSION);
397             double resourceVersion = Double.parseDouble((String) versionObj);
398             if (resourceVersion > version) {
399                 version = resourceVersion;
400                 highestResource = vertex;
401             }
402         }
403         return getToscaElementByOperation(highestResource, filter);
404     }
405
406     public <T extends Component> Either<T, StorageOperationStatus> getLatestByToscaResourceName(String toscaResourceName, String modelName) {
407         return getLatestByName(GraphPropertyEnum.TOSCA_RESOURCE_NAME, toscaResourceName, modelName);
408     }
409
410     public <T extends Component> Either<T, StorageOperationStatus> getFullLatestComponentByToscaResourceName(String toscaResourceName) {
411         ComponentParametersView fetchAllFilter = new ComponentParametersView();
412         fetchAllFilter.setIgnoreServicePath(true);
413         fetchAllFilter.setIgnoreCapabiltyProperties(false);
414         return getLatestByName(GraphPropertyEnum.TOSCA_RESOURCE_NAME, toscaResourceName, JsonParseFlagEnum.ParseAll, fetchAllFilter, null);
415     }
416
417     public <T extends Component> Either<T, StorageOperationStatus> getLatestByName(String resourceName, String modelName) {
418         return getLatestByName(GraphPropertyEnum.NAME, resourceName, modelName);
419     }
420
421     public StorageOperationStatus validateCsarUuidUniqueness(String csarUUID) {
422         Map<GraphPropertyEnum, Object> properties = new EnumMap<>(GraphPropertyEnum.class);
423         properties.put(GraphPropertyEnum.CSAR_UUID, csarUUID);
424         Either<List<GraphVertex>, JanusGraphOperationStatus> resources = janusGraphDao
425             .getByCriteria(null, properties, JsonParseFlagEnum.ParseMetadata);
426         if (resources.isRight()) {
427             if (resources.right().value() == JanusGraphOperationStatus.NOT_FOUND) {
428                 return StorageOperationStatus.OK;
429             } else {
430                 log.debug("failed to get resources from graph with property name: {}", csarUUID);
431                 return DaoStatusConverter.convertJanusGraphStatusToStorageStatus(resources.right().value());
432             }
433         }
434         return StorageOperationStatus.ENTITY_ALREADY_EXISTS;
435     }
436
437     public <T extends Component> Either<Set<T>, StorageOperationStatus> getFollowed(String userId, Set<LifecycleStateEnum> lifecycleStates,
438                                                                                     Set<LifecycleStateEnum> lastStateStates,
439                                                                                     ComponentTypeEnum componentType) {
440         Either<List<ToscaElement>, StorageOperationStatus> followedResources;
441         if (componentType == ComponentTypeEnum.RESOURCE) {
442             followedResources = nodeTypeOperation.getFollowedComponent(userId, lifecycleStates, lastStateStates, componentType);
443         } else {
444             followedResources = topologyTemplateOperation.getFollowedComponent(userId, lifecycleStates, lastStateStates, componentType);
445         }
446         Set<T> components = new HashSet<>();
447         if (followedResources.isRight() && followedResources.right().value() != StorageOperationStatus.NOT_FOUND) {
448             return Either.right(followedResources.right().value());
449         }
450         if (followedResources.isLeft()) {
451             List<ToscaElement> toscaElements = followedResources.left().value();
452             toscaElements.forEach(te -> {
453                 T component = ModelConverter.convertFromToscaElement(te);
454                 components.add(component);
455             });
456         }
457         return Either.left(components);
458     }
459
460     public Either<Resource, StorageOperationStatus> getLatestCertifiedNodeTypeByToscaResourceName(String toscaResourceName) {
461         return getLatestCertifiedByToscaResourceName(toscaResourceName, VertexTypeEnum.NODE_TYPE, JsonParseFlagEnum.ParseMetadata);
462     }
463
464     public Either<Resource, StorageOperationStatus> getByToscaResourceNameMatchingVendorRelease(final String toscaResourceName,
465                                                                                                 final String vendorVersion) {
466         return getByToscaResourceNameMatchingVendorRelease(toscaResourceName, VertexTypeEnum.NODE_TYPE, JsonParseFlagEnum.ParseMetadata,
467             vendorVersion);
468     }
469
470     public Either<Resource, StorageOperationStatus> getByToscaResourceNameMatchingVendorRelease(String toscaResourceName, VertexTypeEnum vertexType,
471                                                                                                 JsonParseFlagEnum parseFlag, String vendorRelease) {
472         Map<GraphPropertyEnum, Object> props = new EnumMap<>(GraphPropertyEnum.class);
473         props.put(GraphPropertyEnum.TOSCA_RESOURCE_NAME, toscaResourceName);
474         props.put(GraphPropertyEnum.STATE, LifecycleStateEnum.CERTIFIED.name());
475         Map<String, Entry<JanusGraphPredicate, Object>> predicateCriteria = getVendorVersionPredicate(vendorRelease);
476         Either<List<GraphVertex>, JanusGraphOperationStatus> getLatestRes = janusGraphDao
477             .getByCriteria(vertexType, props, null, predicateCriteria, parseFlag, null);
478         if (getLatestRes.isRight() || CollectionUtils.isEmpty(getLatestRes.left().value())) {
479             getLatestRes = janusGraphDao.getByCriteria(vertexType, props, parseFlag);
480         }
481         return getLatestRes.right().map(status -> {
482             CommonUtility
483                 .addRecordToLog(log, LogLevelEnum.DEBUG, "Failed to fetch {} with name {}. status={} ", vertexType, toscaResourceName, status);
484             return DaoStatusConverter.convertJanusGraphStatusToStorageStatus(status);
485         }).left().bind(resources -> {
486             double version = 0.0;
487             GraphVertex highestResource = null;
488             for (GraphVertex resource : resources) {
489                 double resourceVersion = Double.parseDouble((String) resource.getJsonMetadataField(JsonPresentationFields.VERSION));
490                 if (resourceVersion > version && isValidForVendorRelease(resource, vendorRelease)) {
491                     version = resourceVersion;
492                     highestResource = resource;
493                 }
494             }
495             if (highestResource != null) {
496                 return getToscaFullElement(highestResource.getUniqueId());
497             } else {
498                 log.debug("The vertex with the highest version could not be found for {}", toscaResourceName);
499                 return Either.right(StorageOperationStatus.GENERAL_ERROR);
500             }
501         });
502     }
503
504     public <T extends Component> Either<T, StorageOperationStatus> getByToscaResourceNameAndVersion(final String toscaResourceName,
505                                                                                                     final String version, final String model) {
506         Either<T, StorageOperationStatus> result;
507
508         Map<GraphPropertyEnum, Object> hasProperties = new EnumMap<>(GraphPropertyEnum.class);
509         Map<GraphPropertyEnum, Object> hasNotProperties = new EnumMap<>(GraphPropertyEnum.class);
510
511         hasProperties.put(GraphPropertyEnum.TOSCA_RESOURCE_NAME, toscaResourceName);
512         hasProperties.put(GraphPropertyEnum.VERSION, version);
513         hasNotProperties.put(GraphPropertyEnum.IS_DELETED, true);
514
515         Either<List<GraphVertex>, JanusGraphOperationStatus> getResourceRes = janusGraphDao
516             .getByCriteria(VertexTypeEnum.NODE_TYPE, hasProperties, hasNotProperties, JsonParseFlagEnum.ParseAll, model);
517         if (getResourceRes.isRight()) {
518             JanusGraphOperationStatus status = getResourceRes.right().value();
519             log.debug("failed to find resource with toscaResourceName {}, version {}. Status is {} ", toscaResourceName, version, status);
520             result = Either.right(DaoStatusConverter.convertJanusGraphStatusToStorageStatus(status));
521             return result;
522         }
523         return getToscaElementByOperation(getResourceRes.left().value().get(0));
524     }
525
526     private Map<String, Entry<JanusGraphPredicate, Object>> getVendorVersionPredicate(final String vendorRelease) {
527         Map<String, Entry<JanusGraphPredicate, Object>> predicateCriteria = new HashMap<>();
528         if (!"1.0".equals(vendorRelease)) {
529             String[] vendorReleaseElements = vendorRelease.split("\\.");
530             if (vendorReleaseElements.length > 0) {
531                 String regex = ".*\"vendorRelease\":\"";
532                 for (int i = 0; i < vendorReleaseElements.length; i++) {
533                     regex += vendorReleaseElements[i];
534                     regex += i < vendorReleaseElements.length - 1 ? "\\." : "\".*";
535                 }
536                 predicateCriteria.put("metadata", new HashMap.SimpleEntry<>(REGEX, regex));
537             }
538         }
539         return predicateCriteria;
540     }
541
542     public boolean isNodeAssociatedToModel(final String model, final Resource resource) {
543         final List<GraphVertex> modelElementVertices = getResourceModelElementVertices(resource);
544         if (model == null) {
545             return modelElementVertices.isEmpty();
546         }
547         return modelElementVertices.stream().anyMatch(graphVertex -> graphVertex.getMetadataProperty(GraphPropertyEnum.NAME).equals(model));
548     }
549
550     public List<GraphVertex> getResourceModelElementVertices(final Resource resource) {
551         final Either<GraphVertex, JanusGraphOperationStatus> vertex =
552             janusGraphDao.getVertexById(resource.getUniqueId(), JsonParseFlagEnum.NoParse);
553         if (vertex.isRight() || Objects.isNull(vertex.left().value())) {
554             return Collections.emptyList();
555         }
556         final Either<List<GraphVertex>, JanusGraphOperationStatus> nodeModelVertices =
557             janusGraphDao.getParentVertices(vertex.left().value(), EdgeLabelEnum.MODEL_ELEMENT, JsonParseFlagEnum.NoParse);
558         if (nodeModelVertices.isRight() || nodeModelVertices.left().value() == null) {
559             return Collections.emptyList();
560         }
561         return nodeModelVertices.left().value();
562     }
563
564     private boolean isValidForVendorRelease(final GraphVertex resource, final String vendorRelease) {
565         if (!vendorRelease.equals("1.0")) {
566             try {
567                 Semver resourceSemVer = new Semver((String) resource.getJsonMetadataField(JsonPresentationFields.VENDOR_RELEASE), SemverType.NPM);
568                 Semver packageSemVer = new Semver(vendorRelease, SemverType.NPM);
569                 return !resourceSemVer.isGreaterThan(packageSemVer);
570             } catch (Exception exception) {
571                 log.debug("Error in comparing vendor release", exception);
572                 return true;
573             }
574         }
575         return true;
576     }
577
578     public Either<Resource, StorageOperationStatus> getLatestCertifiedByToscaResourceName(String toscaResourceName, VertexTypeEnum vertexType,
579                                                                                           JsonParseFlagEnum parseFlag) {
580         Map<GraphPropertyEnum, Object> props = new EnumMap<>(GraphPropertyEnum.class);
581         props.put(GraphPropertyEnum.TOSCA_RESOURCE_NAME, toscaResourceName);
582         props.put(GraphPropertyEnum.IS_HIGHEST_VERSION, true);
583         props.put(GraphPropertyEnum.STATE, LifecycleStateEnum.CERTIFIED.name());
584         Either<List<GraphVertex>, JanusGraphOperationStatus> getLatestRes = janusGraphDao.getByCriteria(vertexType, props, parseFlag);
585         return getLatestRes.right().map(status -> {
586             CommonUtility
587                 .addRecordToLog(log, LogLevelEnum.DEBUG, "Failed to fetch {} with name {}. status={} ", vertexType, toscaResourceName, status);
588             return DaoStatusConverter.convertJanusGraphStatusToStorageStatus(status);
589         }).left().bind(resources -> {
590             double version = 0.0;
591             GraphVertex highestResource = null;
592             for (GraphVertex resource : resources) {
593                 double resourceVersion = Double.parseDouble((String) resource.getJsonMetadataField(JsonPresentationFields.VERSION));
594                 if (resourceVersion > version) {
595                     version = resourceVersion;
596                     highestResource = resource;
597                 }
598             }
599             if (highestResource != null) {
600                 return getToscaFullElement(highestResource.getUniqueId());
601             } else {
602                 log.debug("The vertex with the highest version could not be found for {}", toscaResourceName);
603                 return Either.right(StorageOperationStatus.GENERAL_ERROR);
604             }
605         });
606     }
607
608     public Either<Resource, StorageOperationStatus> getLatestResourceByToscaResourceName(String toscaResourceName) {
609         if (toscaResourceName != null && toscaResourceName.contains("org.openecomp.resource.vf")) {
610             return getLatestResourceByToscaResourceName(toscaResourceName, VertexTypeEnum.TOPOLOGY_TEMPLATE, JsonParseFlagEnum.ParseMetadata);
611         } else {
612             return getLatestResourceByToscaResourceName(toscaResourceName, VertexTypeEnum.NODE_TYPE, JsonParseFlagEnum.ParseMetadata);
613         }
614     }
615
616     public Either<Resource, StorageOperationStatus> getLatestResourceByToscaResourceName(String toscaResourceName, VertexTypeEnum vertexType,
617                                                                                          JsonParseFlagEnum parseFlag) {
618         Either<Resource, StorageOperationStatus> result = null;
619         Map<GraphPropertyEnum, Object> props = new EnumMap<>(GraphPropertyEnum.class);
620         props.put(GraphPropertyEnum.TOSCA_RESOURCE_NAME, toscaResourceName);
621         props.put(GraphPropertyEnum.IS_HIGHEST_VERSION, true);
622         if (!toscaResourceName.contains("org.openecomp.resource.vf")) {
623             props.put(GraphPropertyEnum.STATE, LifecycleStateEnum.CERTIFIED.name());
624         }
625         Either<List<GraphVertex>, JanusGraphOperationStatus> getLatestRes = janusGraphDao.getByCriteria(vertexType, props, parseFlag);
626         if (getLatestRes.isRight()) {
627             JanusGraphOperationStatus status = getLatestRes.right().value();
628             CommonUtility
629                 .addRecordToLog(log, LogLevelEnum.DEBUG, "Failed to fetch {} with name {}. status={} ", vertexType, toscaResourceName, status);
630             result = Either.right(DaoStatusConverter.convertJanusGraphStatusToStorageStatus(status));
631         }
632         if (result == null) {
633             List<GraphVertex> resources = getLatestRes.left().value();
634             double version = 0.0;
635             GraphVertex highestResource = null;
636             for (GraphVertex resource : resources) {
637                 double resourceVersion = Double.parseDouble((String) resource.getJsonMetadataField(JsonPresentationFields.VERSION));
638                 if (resourceVersion > version) {
639                     version = resourceVersion;
640                     highestResource = resource;
641                 }
642             }
643             if (highestResource != null) {
644                 result = getToscaFullElement(highestResource.getUniqueId());
645             } else {
646                 log.debug("The vertex with the highest version could not be found for {}", toscaResourceName);
647                 result = Either.right(StorageOperationStatus.GENERAL_ERROR);
648             }
649         }
650         return result;
651     }
652
653     public Either<Boolean, StorageOperationStatus> validateToscaResourceNameExists(String templateName) {
654         Either<Boolean, StorageOperationStatus> validateUniquenessRes = validateToscaResourceNameUniqueness(templateName);
655         if (validateUniquenessRes.isLeft()) {
656             return Either.left(!validateUniquenessRes.left().value());
657         }
658         return validateUniquenessRes;
659     }
660
661     public Either<RequirementCapabilityRelDef, StorageOperationStatus> dissociateResourceInstances(String componentId,
662                                                                                                    RequirementCapabilityRelDef requirementDef) {
663         return nodeTemplateOperation.dissociateResourceInstances(componentId, requirementDef);
664     }
665
666     /**
667      * Allows to get fulfilled requirement by relation and received predicate
668      */
669     public Either<RequirementDataDefinition, StorageOperationStatus> getFulfilledRequirementByRelation(String componentId, String instanceId,
670                                                                                                        RequirementCapabilityRelDef relation,
671                                                                                                        BiPredicate<RelationshipInfo, RequirementDataDefinition> predicate) {
672         return nodeTemplateOperation.getFulfilledRequirementByRelation(componentId, instanceId, relation, predicate);
673     }
674
675     /**
676      * Allows to get fulfilled capability by relation and received predicate
677      */
678     public Either<CapabilityDataDefinition, StorageOperationStatus> getFulfilledCapabilityByRelation(String componentId, String instanceId,
679                                                                                                      RequirementCapabilityRelDef relation,
680                                                                                                      BiPredicate<RelationshipInfo, CapabilityDataDefinition> predicate) {
681         return nodeTemplateOperation.getFulfilledCapabilityByRelation(componentId, instanceId, relation, predicate);
682     }
683
684     public Either<List<RequirementCapabilityRelDef>, StorageOperationStatus> associateResourceInstances(Component component, String componentId,
685                                                                                                         List<RequirementCapabilityRelDef> relations) {
686         Either<List<RequirementCapabilityRelDef>, StorageOperationStatus> reqAndCapListEither = nodeTemplateOperation
687             .associateResourceInstances(component, componentId, relations);
688         if (component != null) {
689             updateInstancesCapAndReqOnComponentFromDB(component);
690         }
691         return reqAndCapListEither;
692     }
693
694     protected Either<Boolean, StorageOperationStatus> validateToscaResourceNameUniqueness(String name) {
695         Map<GraphPropertyEnum, Object> properties = new EnumMap<>(GraphPropertyEnum.class);
696         properties.put(GraphPropertyEnum.TOSCA_RESOURCE_NAME, name);
697         Either<List<GraphVertex>, JanusGraphOperationStatus> resources = janusGraphDao
698             .getByCriteria(null, properties, JsonParseFlagEnum.ParseMetadata);
699         if (resources.isRight() && resources.right().value() != JanusGraphOperationStatus.NOT_FOUND) {
700             log.debug("failed to get resources from graph with property name: {}", name);
701             return Either.right(DaoStatusConverter.convertJanusGraphStatusToStorageStatus(resources.right().value()));
702         }
703         List<GraphVertex> resourceList = (resources.isLeft() ? resources.left().value() : null);
704         if (isNotEmpty(resourceList)) {
705             if (log.isDebugEnabled()) {
706                 StringBuilder builder = new StringBuilder();
707                 for (GraphVertex resourceData : resourceList) {
708                     builder.append(resourceData.getUniqueId() + "|");
709                 }
710                 log.debug("resources  with property name:{} exists in graph. found {}", name, builder);
711             }
712             return Either.left(false);
713         } else {
714             log.debug("resources  with property name:{} does not exists in graph", name);
715             return Either.left(true);
716         }
717     }
718
719     // region - Component Update
720     public Either<Resource, StorageOperationStatus> overrideComponent(Resource newComponent, Resource oldComponent) {
721         copyArtifactsToNewComponent(newComponent, oldComponent);
722         Either<GraphVertex, JanusGraphOperationStatus> componentVEither = janusGraphDao
723             .getVertexById(oldComponent.getUniqueId(), JsonParseFlagEnum.NoParse);
724         if (componentVEither.isRight()) {
725             log.debug("Failed to fetch component {} error {}", oldComponent.getUniqueId(), componentVEither.right().value());
726             return Either.right(DaoStatusConverter.convertJanusGraphStatusToStorageStatus(componentVEither.right().value()));
727         }
728         GraphVertex componentv = componentVEither.left().value();
729         Either<GraphVertex, JanusGraphOperationStatus> parentVertexEither = janusGraphDao
730             .getParentVertex(componentv, EdgeLabelEnum.VERSION, JsonParseFlagEnum.NoParse);
731         if (parentVertexEither.isRight() && parentVertexEither.right().value() != JanusGraphOperationStatus.NOT_FOUND) {
732             log.debug("Failed to fetch parent version for component {} error {}", oldComponent.getUniqueId(), parentVertexEither.right().value());
733             return Either.right(DaoStatusConverter.convertJanusGraphStatusToStorageStatus(parentVertexEither.right().value()));
734         }
735         Either<ToscaElement, StorageOperationStatus> deleteToscaComponent = deleteToscaElement(componentv);
736         if (deleteToscaComponent.isRight()) {
737             log.debug("Failed to remove old component {} error {}", oldComponent.getUniqueId(), deleteToscaComponent.right().value());
738             return Either.right(deleteToscaComponent.right().value());
739         }
740         Either<Resource, StorageOperationStatus> createToscaComponent = createToscaComponent(newComponent);
741         if (createToscaComponent.isRight()) {
742             log.debug("Failed to create tosca element component {} error {}", newComponent.getUniqueId(), createToscaComponent.right().value());
743             return Either.right(createToscaComponent.right().value());
744         }
745         Resource newElement = createToscaComponent.left().value();
746         Either<GraphVertex, JanusGraphOperationStatus> newVersionEither = janusGraphDao
747             .getVertexById(newElement.getUniqueId(), JsonParseFlagEnum.NoParse);
748         if (newVersionEither.isRight()) {
749             log.debug("Failed to fetch new tosca element component {} error {}", newComponent.getUniqueId(), newVersionEither.right().value());
750             return Either.right(DaoStatusConverter.convertJanusGraphStatusToStorageStatus(newVersionEither.right().value()));
751         }
752         if (parentVertexEither.isLeft()) {
753             GraphVertex previousVersionV = parentVertexEither.left().value();
754             JanusGraphOperationStatus createEdge = janusGraphDao
755                 .createEdge(previousVersionV, newVersionEither.left().value(), EdgeLabelEnum.VERSION, null);
756             if (createEdge != JanusGraphOperationStatus.OK) {
757                 log.debug("Failed to associate to previous version {} new version {} error {}", previousVersionV.getUniqueId(),
758                     newVersionEither.right().value(), createEdge);
759                 return Either.right(DaoStatusConverter.convertJanusGraphStatusToStorageStatus(createEdge));
760             }
761         }
762         return Either.left(newElement);
763     }
764
765     void copyArtifactsToNewComponent(Resource newComponent, Resource oldComponent) {
766         // TODO - check if required
767         Map<String, ArtifactDefinition> toscaArtifacts = oldComponent.getToscaArtifacts();
768         if (toscaArtifacts != null && !toscaArtifacts.isEmpty()) {
769             toscaArtifacts.values().stream().forEach(a -> a.setDuplicated(Boolean.TRUE));
770         }
771         newComponent.setToscaArtifacts(toscaArtifacts);
772         Map<String, ArtifactDefinition> artifacts = oldComponent.getArtifacts();
773         if (artifacts != null && !artifacts.isEmpty()) {
774             artifacts.values().stream().forEach(a -> a.setDuplicated(Boolean.TRUE));
775         }
776         newComponent.setArtifacts(artifacts);
777         Map<String, ArtifactDefinition> depArtifacts = oldComponent.getDeploymentArtifacts();
778         if (depArtifacts != null && !depArtifacts.isEmpty()) {
779             depArtifacts.values().stream().forEach(a -> a.setDuplicated(Boolean.TRUE));
780         }
781         newComponent.setDeploymentArtifacts(depArtifacts);
782         newComponent.setLastUpdateDate(null);
783         newComponent.setHighestVersion(true);
784     }
785
786     public <T extends Component> Either<T, StorageOperationStatus> updateToscaElement(T componentToUpdate) {
787         return updateToscaElement(componentToUpdate, new ComponentParametersView());
788     }
789
790     public <T extends Component> Either<T, StorageOperationStatus> updateToscaElement(T componentToUpdate, ComponentParametersView filterResult) {
791         String componentId = componentToUpdate.getUniqueId();
792         Either<GraphVertex, JanusGraphOperationStatus> getVertexEither = janusGraphDao.getVertexById(componentId, JsonParseFlagEnum.ParseAll);
793         if (getVertexEither.isRight()) {
794             log.debug(COULDNT_FETCH_COMPONENT_WITH_AND_UNIQUE_ID_ERROR, componentId, getVertexEither.right().value());
795             return Either.right(DaoStatusConverter.convertJanusGraphStatusToStorageStatus(getVertexEither.right().value()));
796         }
797         GraphVertex elementV = getVertexEither.left().value();
798         ToscaElementOperation toscaElementOperation = getToscaElementOperation(elementV);
799         ToscaElement toscaElementToUpdate = ModelConverter.convertToToscaElement(componentToUpdate);
800         Either<ToscaElement, StorageOperationStatus> updateToscaElement = null;
801         if (toscaElementOperation != null) {
802             updateToscaElement = toscaElementOperation.updateToscaElement(toscaElementToUpdate, elementV, filterResult);
803         } else {
804             log.debug("Null value returned by `getToscaElementOperation` with value {}", elementV);
805             updateToscaElement = Either.right(StorageOperationStatus.GENERAL_ERROR);
806         }
807         return updateToscaElement.bimap(ModelConverter::convertFromToscaElement, status -> {
808             log.debug("Failed to update tosca element {} error {}", componentId, status);
809             return status;
810         });
811     }
812
813     private <T extends Component> Either<T, StorageOperationStatus> getLatestByName(GraphPropertyEnum property, String nodeName,
814                                                                                     JsonParseFlagEnum parseFlag, String modelName) {
815         return getLatestByName(property, nodeName, parseFlag, new ComponentParametersView(), modelName);
816     }
817
818     private <T extends Component> Either<T, StorageOperationStatus> getLatestByName(GraphPropertyEnum property, String nodeName,
819                                                                                     JsonParseFlagEnum parseFlag, ComponentParametersView filter,
820                                                                                     String model) {
821         Either<T, StorageOperationStatus> result;
822         Map<GraphPropertyEnum, Object> propertiesToMatch = new EnumMap<>(GraphPropertyEnum.class);
823         Map<GraphPropertyEnum, Object> propertiesNotToMatch = new EnumMap<>(GraphPropertyEnum.class);
824         propertiesToMatch.put(property, nodeName);
825         propertiesToMatch.put(GraphPropertyEnum.IS_HIGHEST_VERSION, true);
826         propertiesNotToMatch.put(GraphPropertyEnum.IS_DELETED, true);
827         Either<List<GraphVertex>, JanusGraphOperationStatus> highestResources = janusGraphDao
828             .getByCriteria(null, propertiesToMatch, propertiesNotToMatch, parseFlag, model);
829         if (highestResources.isRight()) {
830             JanusGraphOperationStatus status = highestResources.right().value();
831             log.debug("failed to find resource with name {}. status={} ", nodeName, status);
832             result = Either.right(DaoStatusConverter.convertJanusGraphStatusToStorageStatus(status));
833             return result;
834         }
835         List<GraphVertex> resources = highestResources.left().value();
836         double version = 0.0;
837         GraphVertex highestResource = null;
838         for (GraphVertex vertex : resources) {
839             Object versionObj = vertex.getMetadataProperty(GraphPropertyEnum.VERSION);
840             double resourceVersion = Double.parseDouble((String) versionObj);
841             if (resourceVersion > version) {
842                 version = resourceVersion;
843                 highestResource = vertex;
844             }
845         }
846         return getToscaElementByOperation(highestResource, filter);
847     }
848
849     // region - Component Get By ..
850     private <T extends Component> Either<T, StorageOperationStatus> getLatestByName(GraphPropertyEnum property, String nodeName, String modelName) {
851         return getLatestByName(property, nodeName, JsonParseFlagEnum.ParseMetadata, modelName);
852     }
853
854     public <T extends Component> Either<List<T>, StorageOperationStatus> getBySystemName(ComponentTypeEnum componentType, String systemName) {
855         Either<List<T>, StorageOperationStatus> result = null;
856         Either<T, StorageOperationStatus> getComponentRes;
857         List<T> components = new ArrayList<>();
858         List<GraphVertex> componentVertices;
859         Map<GraphPropertyEnum, Object> propertiesToMatch = new EnumMap<>(GraphPropertyEnum.class);
860         Map<GraphPropertyEnum, Object> propertiesNotToMatch = new EnumMap<>(GraphPropertyEnum.class);
861         propertiesToMatch.put(GraphPropertyEnum.SYSTEM_NAME, systemName);
862         if (componentType != null) {
863             propertiesToMatch.put(GraphPropertyEnum.COMPONENT_TYPE, componentType.name());
864         }
865         propertiesNotToMatch.put(GraphPropertyEnum.IS_DELETED, true);
866         Either<List<GraphVertex>, JanusGraphOperationStatus> getComponentsRes = janusGraphDao
867             .getByCriteria(null, propertiesToMatch, propertiesNotToMatch, JsonParseFlagEnum.ParseAll);
868         if (getComponentsRes.isRight()) {
869             JanusGraphOperationStatus status = getComponentsRes.right().value();
870             log.debug("Failed to fetch the component with system name {}. Status is {} ", systemName, status);
871             result = Either.right(DaoStatusConverter.convertJanusGraphStatusToStorageStatus(status));
872         }
873         if (result == null) {
874             componentVertices = getComponentsRes.left().value();
875             for (GraphVertex componentVertex : componentVertices) {
876                 getComponentRes = getToscaElementByOperation(componentVertex);
877                 if (getComponentRes.isRight()) {
878                     log.debug("Failed to get the component {}. Status is {} ", componentVertex.getJsonMetadataField(JsonPresentationFields.NAME),
879                         getComponentRes.right().value());
880                     result = Either.right(getComponentRes.right().value());
881                     break;
882                 }
883                 T componentBySystemName = getComponentRes.left().value();
884                 log.debug("Found component, id: {}", componentBySystemName.getUniqueId());
885                 components.add(componentBySystemName);
886             }
887         }
888         if (result == null) {
889             result = Either.left(components);
890         }
891         return result;
892     }
893
894     public <T extends Component> Either<T, StorageOperationStatus> getComponentByNameAndVersion(ComponentTypeEnum componentType, String name,
895                                                                                                 String version) {
896         return getComponentByNameAndVersion(componentType, name, version, JsonParseFlagEnum.ParseAll);
897     }
898
899     public <T extends Component> Either<T, StorageOperationStatus> getComponentByNameAndVersion(ComponentTypeEnum componentType, String name,
900                                                                                                 String version, JsonParseFlagEnum parseFlag) {
901         Either<T, StorageOperationStatus> result;
902         Map<GraphPropertyEnum, Object> hasProperties = new EnumMap<>(GraphPropertyEnum.class);
903         Map<GraphPropertyEnum, Object> hasNotProperties = new EnumMap<>(GraphPropertyEnum.class);
904         hasProperties.put(GraphPropertyEnum.NAME, name);
905         hasProperties.put(GraphPropertyEnum.VERSION, version);
906         hasNotProperties.put(GraphPropertyEnum.IS_DELETED, true);
907         if (componentType != null) {
908             hasProperties.put(GraphPropertyEnum.COMPONENT_TYPE, componentType.name());
909         }
910         Either<List<GraphVertex>, JanusGraphOperationStatus> getResourceRes = janusGraphDao
911             .getByCriteria(null, hasProperties, hasNotProperties, parseFlag);
912         if (getResourceRes.isRight()) {
913             JanusGraphOperationStatus status = getResourceRes.right().value();
914             log.debug("failed to find resource with name {}, version {}. Status is {} ", name, version, status);
915             result = Either.right(DaoStatusConverter.convertJanusGraphStatusToStorageStatus(status));
916             return result;
917         }
918         return getToscaElementByOperation(getResourceRes.left().value().get(0));
919     }
920
921     public <T extends Component> Either<T, StorageOperationStatus> getComponentByNameAndVendorRelease(final ComponentTypeEnum componentType,
922                                                                                                       final String name, final String vendorRelease,
923                                                                                                       final JsonParseFlagEnum parseFlag,
924                                                                                                       final String modelName) {
925         Map<GraphPropertyEnum, Object> hasProperties = new EnumMap<>(GraphPropertyEnum.class);
926         Map<GraphPropertyEnum, Object> hasNotProperties = new EnumMap<>(GraphPropertyEnum.class);
927         hasProperties.put(GraphPropertyEnum.NAME, name);
928         hasNotProperties.put(GraphPropertyEnum.IS_DELETED, true);
929         if (componentType != null) {
930             hasProperties.put(GraphPropertyEnum.COMPONENT_TYPE, componentType.name());
931         }
932         Map<String, Entry<JanusGraphPredicate, Object>> predicateCriteria = getVendorVersionPredicate(vendorRelease);
933         Either<List<GraphVertex>, JanusGraphOperationStatus> getResourceRes = janusGraphDao.getByCriteria(null, hasProperties, hasNotProperties,
934             predicateCriteria, parseFlag, modelName);
935         if (getResourceRes.isRight()) {
936             JanusGraphOperationStatus status = getResourceRes.right().value();
937             log.debug("failed to find resource with name {}, version {}. Status is {} ", name, predicateCriteria, status);
938             return Either.right(DaoStatusConverter.convertJanusGraphStatusToStorageStatus(status));
939         }
940         return getToscaElementByOperation(getResourceRes.left().value().get(0));
941     }
942
943     public Either<List<CatalogComponent>, StorageOperationStatus> getCatalogOrArchiveComponents(boolean isCatalog,
944                                                                                                 List<OriginTypeEnum> excludeTypes) {
945         List<ResourceTypeEnum> excludedResourceTypes = Optional.ofNullable(excludeTypes).orElse(Collections.emptyList()).stream()
946             .filter(type -> !type.equals(OriginTypeEnum.SERVICE)).map(type -> ResourceTypeEnum.getTypeByName(type.name()))
947             .collect(Collectors.toList());
948         return topologyTemplateOperation.getElementCatalogData(isCatalog, excludedResourceTypes);
949     }
950
951     // endregion
952     public <T extends Component> Either<List<T>, StorageOperationStatus> getCatalogComponents(ComponentTypeEnum componentType,
953                                                                                               List<OriginTypeEnum> excludeTypes,
954                                                                                               boolean isHighestVersions) {
955         List<T> components = new ArrayList<>();
956         Either<List<ToscaElement>, StorageOperationStatus> catalogDataResult;
957         List<ToscaElement> toscaElements = new ArrayList<>();
958         List<ResourceTypeEnum> excludedResourceTypes = Optional.ofNullable(excludeTypes).orElse(Collections.emptyList()).stream()
959             .filter(type -> !type.equals(OriginTypeEnum.SERVICE)).map(type -> ResourceTypeEnum.getTypeByName(type.name()))
960             .collect(Collectors.toList());
961         switch (componentType) {
962             case RESOURCE:
963                 catalogDataResult = nodeTypeOperation.getElementCatalogData(ComponentTypeEnum.RESOURCE, excludedResourceTypes, isHighestVersions);
964                 if (catalogDataResult.isRight()) {
965                     return Either.right(catalogDataResult.right().value());
966                 }
967                 toscaElements = catalogDataResult.left().value();
968                 break;
969             case SERVICE:
970                 if (excludeTypes != null && excludeTypes.contains(OriginTypeEnum.SERVICE)) {
971                     break;
972                 }
973                 catalogDataResult = topologyTemplateOperation.getElementCatalogData(ComponentTypeEnum.SERVICE, null, isHighestVersions);
974                 if (catalogDataResult.isRight()) {
975                     return Either.right(catalogDataResult.right().value());
976                 }
977                 toscaElements = catalogDataResult.left().value();
978                 break;
979             default:
980                 log.debug(NOT_SUPPORTED_COMPONENT_TYPE, componentType);
981                 return Either.right(StorageOperationStatus.BAD_REQUEST);
982         }
983         toscaElements.forEach(te -> {
984             T component = ModelConverter.convertFromToscaElement(te);
985             components.add(component);
986         });
987         return Either.left(components);
988     }
989
990     public Either<List<String>, StorageOperationStatus> deleteMarkedElements(ComponentTypeEnum componentType) {
991         Either<List<GraphVertex>, StorageOperationStatus> allComponentsMarkedForDeletion;
992         switch (componentType) {
993             case RESOURCE:
994                 allComponentsMarkedForDeletion = nodeTypeOperation.getAllComponentsMarkedForDeletion(componentType);
995                 break;
996             case SERVICE:
997             case PRODUCT:
998                 allComponentsMarkedForDeletion = topologyTemplateOperation.getAllComponentsMarkedForDeletion(componentType);
999                 break;
1000             default:
1001                 log.debug(NOT_SUPPORTED_COMPONENT_TYPE, componentType);
1002                 return Either.right(StorageOperationStatus.BAD_REQUEST);
1003         }
1004         if (allComponentsMarkedForDeletion.isRight()) {
1005             return Either.right(allComponentsMarkedForDeletion.right().value());
1006         }
1007         List<GraphVertex> allMarked = allComponentsMarkedForDeletion.left().value();
1008         return Either.left(checkIfInUseAndDelete(allMarked));
1009     }
1010
1011     public List<String> deleteService(String invariantUUID, final boolean inTransaction) {
1012         return deleteComponent(invariantUUID, NodeTypeEnum.Service, inTransaction);
1013     }
1014
1015     public List<String> deleteComponent(String invariantUUID, NodeTypeEnum componentType, final boolean inTransaction) {
1016         final List<GraphVertex> allServiceVerticesToDelete = findVertexListByInvariantUuid(invariantUUID);
1017         List<String> affectedComponentIds = new ArrayList<>();
1018         try {
1019             checkNotUsed(allServiceVerticesToDelete);
1020             lockAllVerticesByNodeType(allServiceVerticesToDelete, componentType);
1021             for (GraphVertex elementV : allServiceVerticesToDelete) {
1022                 Either<ToscaElement, StorageOperationStatus> deleteToscaElement = deleteToscaElement(elementV);
1023                 if (deleteToscaElement.isRight()) {
1024                     log.debug("Failed to delete element UniqueID {}, Name {}, error {}", elementV.getUniqueId(),
1025                         elementV.getMetadataProperties().get(GraphPropertyEnum.NAME), deleteToscaElement.right().value());
1026                     throwStorageException(deleteToscaElement.right().value());
1027                 }
1028                 affectedComponentIds.add(elementV.getUniqueId());
1029             }
1030             if (!inTransaction) {
1031                 janusGraphDao.commit();
1032             }
1033         } catch (Exception exception) {
1034             if (!inTransaction) {
1035                 janusGraphDao.rollback();
1036             }
1037             throw exception;
1038         } finally {
1039             unlockAllVerticesByNodeType(allServiceVerticesToDelete, componentType);
1040         }
1041         return affectedComponentIds;
1042     }
1043
1044     private void checkNotUsed(List<GraphVertex> vertices) {
1045         boolean isInUse = isAnyComponentInUse(vertices);
1046         if (isInUse) {
1047             Set<GraphVertex> listOfVertices = getComponentsUsingComponents(vertices);
1048             List<String> listOfStringComponents = new ArrayList<>();
1049             for (GraphVertex componentVertex : listOfVertices) {
1050                 listOfStringComponents.add(
1051                     componentVertex.getMetadataJson().get(GraphPropertyEnum.COMPONENT_TYPE.getProperty()) + " "
1052                         + componentVertex.getMetadataJson().get(GraphPropertyEnum.NAME.getProperty())
1053                 );
1054             }
1055             String stringOfComponents = String.join(", ", listOfStringComponents);
1056             throw ToscaOperationExceptionSupplier.componentInUse(stringOfComponents).get();
1057         }
1058     }
1059
1060     public List<GraphVertex> findVertexListByInvariantUuid(final String invariantUuid) {
1061         try {
1062             return janusGraphDao.findAllVertexByInvariantUuid(invariantUuid, Collections.emptyMap());
1063         } catch (final JanusGraphException e) {
1064             log.error(EcompLoggerErrorCode.DATA_ERROR, this.getClass().getName(), e.getMessage());
1065             throw new StorageException(e.getStatus());
1066         }
1067     }
1068
1069     public void commitAndCheck(String componentId) {
1070         JanusGraphOperationStatus status = janusGraphDao.commit();
1071         if (!status.equals(JanusGraphOperationStatus.OK)) {
1072             log.debug("error occurred when trying to DELETE {}. Return code is: {}", componentId, status);
1073             throwStorageException(DaoStatusConverter.convertJanusGraphStatusToStorageStatus(status));
1074         }
1075     }
1076
1077     private Set<GraphVertex> getComponentsUsingComponents(List<GraphVertex> componentVertices) {
1078         Set<GraphVertex> inUseBy = new TreeSet<>(Comparator.comparing(GraphVertex::getUniqueId));
1079         for (final GraphVertex elementV : componentVertices) {
1080             List<GraphVertex> inUseByVertex = isInUse(elementV);
1081             if (!inUseByVertex.isEmpty()) {
1082                 inUseBy.addAll(inUseByVertex);
1083             }
1084         }
1085         return inUseBy;
1086     }
1087
1088     private boolean isAnyComponentInUse(List<GraphVertex> componentVertices) {
1089         boolean isComponentInUse = false;
1090         if (log.isDebugEnabled()) {
1091             for (final GraphVertex graphVertex : componentVertices) {
1092                 if (!isInUse(graphVertex).isEmpty()) {
1093                     isComponentInUse = true;
1094                 }
1095             }
1096         } else {
1097             isComponentInUse = componentVertices.stream().anyMatch(vertex -> !isInUse(vertex).isEmpty());
1098         }
1099         return isComponentInUse;
1100     }
1101
1102     private List<GraphVertex> isInUse(GraphVertex elementV) {
1103         final List<EdgeLabelEnum> forbiddenEdgeLabelEnums = Arrays
1104             .asList(EdgeLabelEnum.INSTANCE_OF, EdgeLabelEnum.PROXY_OF, EdgeLabelEnum.ALLOTTED_OF);
1105         for (EdgeLabelEnum edgeLabelEnum : forbiddenEdgeLabelEnums) {
1106             Either<List<GraphVertex>, JanusGraphOperationStatus> inUseBy =
1107                 janusGraphDao.getParentVertices(elementV, edgeLabelEnum, JsonParseFlagEnum.ParseAll);
1108             if (inUseBy.isLeft()) {
1109                 if (log.isDebugEnabled()) {
1110                     log.debug("Element {} in use.", elementV.getUniqueId());
1111                 }
1112                 return inUseBy.left().value();
1113             }
1114         }
1115         return Collections.emptyList();
1116     }
1117
1118     private List<String> checkIfInUseAndDelete(List<GraphVertex> allMarked) {
1119         List<String> deleted = new ArrayList<>();
1120         for (GraphVertex elementV : allMarked) {
1121             boolean isAllowedToDelete = !isInUse(elementV).isEmpty();
1122             if (isAllowedToDelete) {
1123                 Either<ToscaElement, StorageOperationStatus> deleteToscaElement = deleteToscaElement(elementV);
1124                 if (deleteToscaElement.isRight()) {
1125                     log.debug("Failed to delete marked element UniqueID {}, Name {}, error {}", elementV.getUniqueId(),
1126                         elementV.getMetadataProperties().get(GraphPropertyEnum.NAME), deleteToscaElement.right().value());
1127                     continue;
1128                 }
1129                 deleted.add(elementV.getUniqueId());
1130             }
1131         }
1132         return deleted;
1133     }
1134
1135     private void lockAllVerticesByNodeType(List<GraphVertex> allVerticesToLock, NodeTypeEnum nodeType) {
1136         for (GraphVertex graphVertex : allVerticesToLock) {
1137             StorageOperationStatus storageOperationStatus = graphLockOperation.lockComponent(graphVertex.getUniqueId(), nodeType);
1138             if (!storageOperationStatus.equals(StorageOperationStatus.OK)) {
1139                 throwStorageException(storageOperationStatus);
1140             }
1141         }
1142     }
1143
1144     private void unlockAllVerticesByNodeType(List<GraphVertex> allVerticesToUnlock, NodeTypeEnum nodeType) {
1145         for (GraphVertex graphVertex : allVerticesToUnlock) {
1146             graphLockOperation.unlockComponent(graphVertex.getUniqueId(), nodeType);
1147         }
1148     }
1149
1150     public Either<List<String>, StorageOperationStatus> getAllComponentsMarkedForDeletion(ComponentTypeEnum componentType) {
1151         Either<List<GraphVertex>, StorageOperationStatus> allComponentsMarkedForDeletion;
1152         switch (componentType) {
1153             case RESOURCE:
1154                 allComponentsMarkedForDeletion = nodeTypeOperation.getAllComponentsMarkedForDeletion(componentType);
1155                 break;
1156             case SERVICE:
1157             case PRODUCT:
1158                 allComponentsMarkedForDeletion = topologyTemplateOperation.getAllComponentsMarkedForDeletion(componentType);
1159                 break;
1160             default:
1161                 log.debug(NOT_SUPPORTED_COMPONENT_TYPE, componentType);
1162                 return Either.right(StorageOperationStatus.BAD_REQUEST);
1163         }
1164         if (allComponentsMarkedForDeletion.isRight()) {
1165             return Either.right(allComponentsMarkedForDeletion.right().value());
1166         }
1167         return Either.left(allComponentsMarkedForDeletion.left().value().stream().map(GraphVertex::getUniqueId).collect(Collectors.toList()));
1168     }
1169
1170     // region - Component Update
1171     public Either<ImmutablePair<Component, String>, StorageOperationStatus> addComponentInstanceToTopologyTemplate(Component containerComponent,
1172                                                                                                                    Component origComponent,
1173                                                                                                                    ComponentInstance componentInstance,
1174                                                                                                                    boolean allowDeleted, User user) {
1175         Either<ImmutablePair<Component, String>, StorageOperationStatus> result = null;
1176         Either<ToscaElement, StorageOperationStatus> updateContainerComponentRes = null;
1177         if (StringUtils.isEmpty(componentInstance.getIcon())) {
1178             componentInstance.setIcon(origComponent.getIcon());
1179         }
1180         String nameToFindForCounter;
1181         switch (componentInstance.getOriginType()) {
1182             case ServiceProxy:
1183                 nameToFindForCounter = ValidationUtils.normaliseComponentName(componentInstance.getSourceModelName()) + PROXY_SUFFIX;
1184                 break;
1185             case ServiceSubstitution:
1186                 nameToFindForCounter = ValidationUtils.normaliseComponentName(componentInstance.getSourceModelName());
1187                 break;
1188             default:
1189                 nameToFindForCounter = origComponent.getName();
1190         }
1191         String nextComponentInstanceCounter = getNextComponentInstanceCounter(containerComponent, nameToFindForCounter);
1192         Either<ImmutablePair<TopologyTemplate, String>, StorageOperationStatus> addResult = nodeTemplateOperation
1193             .addComponentInstanceToTopologyTemplate(ModelConverter.convertToToscaElement(containerComponent),
1194                 ModelConverter.convertToToscaElement(origComponent), nextComponentInstanceCounter, componentInstance, allowDeleted, user);
1195         if (addResult.isRight()) {
1196             CommonUtility.addRecordToLog(log, LogLevelEnum.DEBUG, "Failed to add the component instance {} to container component {}. ",
1197                 componentInstance.getName(), containerComponent.getName());
1198             result = Either.right(addResult.right().value());
1199         }
1200         if (result == null) {
1201             updateContainerComponentRes = topologyTemplateOperation.getToscaElement(containerComponent.getUniqueId());
1202             if (updateContainerComponentRes.isRight()) {
1203                 CommonUtility
1204                     .addRecordToLog(log, LogLevelEnum.DEBUG, "Failed to fetch updated topology template {} with updated component instance {}. ",
1205                         containerComponent.getName(), componentInstance.getName());
1206                 result = Either.right(updateContainerComponentRes.right().value());
1207             }
1208         }
1209         if (result == null) {
1210             Component updatedComponent = ModelConverter.convertFromToscaElement(updateContainerComponentRes.left().value());
1211             String createdInstanceId = addResult.left().value().getRight();
1212             CommonUtility
1213                 .addRecordToLog(log, LogLevelEnum.TRACE, "The component instance {} has been added to container component {}. ", createdInstanceId,
1214                     updatedComponent.getName());
1215             result = Either.left(new ImmutablePair<>(updatedComponent, createdInstanceId));
1216         }
1217         return result;
1218     }
1219
1220     public void associateComponentInstancesToComponent(Component containerComponent, Map<ComponentInstance, Resource> resourcesInstancesMap,
1221                                                        boolean allowDeleted, boolean isUpdateCsar) {
1222         CommonUtility.addRecordToLog(log, LogLevelEnum.DEBUG, "Going to add component instances to component {}", containerComponent.getUniqueId());
1223         Either<GraphVertex, JanusGraphOperationStatus> metadataVertex = janusGraphDao
1224             .getVertexById(containerComponent.getUniqueId(), JsonParseFlagEnum.ParseAll);
1225         if (metadataVertex.isRight()) {
1226             JanusGraphOperationStatus status = metadataVertex.right().value();
1227             if (status == JanusGraphOperationStatus.NOT_FOUND) {
1228                 status = JanusGraphOperationStatus.INVALID_ID;
1229             }
1230             throw new StorageException(DaoStatusConverter.convertJanusGraphStatusToStorageStatus(status));
1231         }
1232         Map<String, ComponentInstanceDataDefinition> compnentInstancesMap = nodeTemplateOperation
1233             .associateComponentInstancesToComponent(containerComponent, resourcesInstancesMap, metadataVertex.left().value(), allowDeleted,
1234                 isUpdateCsar);
1235         containerComponent.setComponentInstances(ModelConverter.getComponentInstancesFromMapObject(compnentInstancesMap, containerComponent));
1236     }
1237
1238     public Either<ImmutablePair<Component, String>, StorageOperationStatus> updateComponentInstanceMetadataOfTopologyTemplate(
1239         Component containerComponent, Component origComponent, ComponentInstance componentInstance) {
1240         Either<ImmutablePair<Component, String>, StorageOperationStatus> result = null;
1241         CommonUtility.addRecordToLog(log, LogLevelEnum.TRACE,
1242             "Going to update the metadata of the component instance {} belonging to container component {}. ", componentInstance.getName(),
1243             containerComponent.getName());
1244         componentInstance.setIcon(origComponent.getIcon());
1245         Either<ImmutablePair<TopologyTemplate, String>, StorageOperationStatus> updateResult = nodeTemplateOperation
1246             .updateComponentInstanceMetadataOfTopologyTemplate(ModelConverter.convertToToscaElement(containerComponent),
1247                 ModelConverter.convertToToscaElement(origComponent), componentInstance);
1248         if (updateResult.isRight()) {
1249             CommonUtility.addRecordToLog(log, LogLevelEnum.DEBUG,
1250                 "Failed to update the metadata of the component instance {} belonging to container component {}. ", componentInstance.getName(),
1251                 containerComponent.getName());
1252             result = Either.right(updateResult.right().value());
1253         }
1254         if (result == null) {
1255             Component updatedComponent = ModelConverter.convertFromToscaElement(updateResult.left().value().getLeft());
1256             String createdInstanceId = updateResult.left().value().getRight();
1257             CommonUtility
1258                 .addRecordToLog(log, LogLevelEnum.TRACE, "The metadata of the component instance {} has been updated to container component {}. ",
1259                     createdInstanceId, updatedComponent.getName());
1260             result = Either.left(new ImmutablePair<>(updatedComponent, createdInstanceId));
1261         }
1262         return result;
1263     }
1264
1265     public Either<Component, StorageOperationStatus> updateComponentInstanceMetadataOfTopologyTemplate(Component containerComponent) {
1266         return updateComponentInstanceMetadataOfTopologyTemplate(containerComponent, new ComponentParametersView());
1267     }
1268
1269     public Either<Component, StorageOperationStatus> updateComponentInstanceMetadataOfTopologyTemplate(Component containerComponent,
1270                                                                                                        ComponentParametersView filter) {
1271         Either<Component, StorageOperationStatus> result = null;
1272         CommonUtility.addRecordToLog(log, LogLevelEnum.TRACE, "Going to update the metadata  belonging to container component {}. ",
1273             containerComponent.getName());
1274         Either<TopologyTemplate, StorageOperationStatus> updateResult = nodeTemplateOperation
1275             .updateComponentInstanceMetadataOfTopologyTemplate(ModelConverter.convertToToscaElement(containerComponent), filter);
1276         if (updateResult.isRight()) {
1277             CommonUtility.addRecordToLog(log, LogLevelEnum.DEBUG, "Failed to update the metadata  belonging to container component {}. ",
1278                 containerComponent.getName());
1279             result = Either.right(updateResult.right().value());
1280         }
1281         if (result == null) {
1282             Component updatedComponent = ModelConverter.convertFromToscaElement(updateResult.left().value());
1283             CommonUtility
1284                 .addRecordToLog(log, LogLevelEnum.TRACE, "The metadata has been updated to container component {}. ", updatedComponent.getName());
1285             result = Either.left(updatedComponent);
1286         }
1287         return result;
1288     }
1289
1290     // endregion
1291     public Either<ImmutablePair<Component, String>, StorageOperationStatus> deleteComponentInstanceFromTopologyTemplate(Component containerComponent,
1292                                                                                                                         String resourceInstanceId) {
1293         Either<ImmutablePair<Component, String>, StorageOperationStatus> result = null;
1294         CommonUtility.addRecordToLog(log, LogLevelEnum.TRACE, "Going to delete the component instance {} belonging to container component {}. ",
1295             resourceInstanceId, containerComponent.getName());
1296         Either<ImmutablePair<TopologyTemplate, String>, StorageOperationStatus> updateResult = nodeTemplateOperation
1297             .deleteComponentInstanceFromTopologyTemplate(ModelConverter.convertToToscaElement(containerComponent), resourceInstanceId);
1298         if (updateResult.isRight()) {
1299             CommonUtility.addRecordToLog(log, LogLevelEnum.DEBUG, "Failed to delete the component instance {} belonging to container component {}. ",
1300                 resourceInstanceId, containerComponent.getName());
1301             result = Either.right(updateResult.right().value());
1302         }
1303         if (result == null) {
1304             Component updatedComponent = ModelConverter.convertFromToscaElement(updateResult.left().value().getLeft());
1305             String deletedInstanceId = updateResult.left().value().getRight();
1306             CommonUtility.addRecordToLog(log, LogLevelEnum.TRACE, "The component instance {} has been deleted from container component {}. ",
1307                 deletedInstanceId, updatedComponent.getName());
1308             result = Either.left(new ImmutablePair<>(updatedComponent, deletedInstanceId));
1309         }
1310         return result;
1311     }
1312
1313     private String getNextComponentInstanceCounter(Component containerComponent, String originResourceName) {
1314         Integer nextCounter = 0;
1315         if (CollectionUtils.isNotEmpty(containerComponent.getComponentInstances())) {
1316             String normalizedName = ValidationUtils.normalizeComponentInstanceName(originResourceName);
1317             Integer maxCounter = getMaxCounterFromNamesAndIds(containerComponent, normalizedName);
1318             if (maxCounter != null) {
1319                 nextCounter = maxCounter + 1;
1320             }
1321         }
1322         return nextCounter.toString();
1323     }
1324
1325     /**
1326      * @return max counter of component instance Id's, null if not found
1327      */
1328     private Integer getMaxCounterFromNamesAndIds(Component containerComponent, String normalizedName) {
1329         List<String> countersInNames = containerComponent.getComponentInstances().stream()
1330             .filter(ci -> ci.getNormalizedName() != null && ci.getNormalizedName().startsWith(normalizedName))
1331             .map(ci -> ci.getNormalizedName().split(normalizedName)[1].replaceAll("\\D", "")).collect(Collectors.toList());
1332         List<String> countersInIds = containerComponent.getComponentInstances().stream()
1333             .filter(ci -> ci.getUniqueId() != null && ci.getUniqueId().contains(normalizedName))
1334             .map(ci -> ci.getUniqueId().split(normalizedName)[1].replaceAll("\\D", "")).collect(Collectors.toList());
1335         List<String> namesAndIdsList = new ArrayList<>(countersInNames);
1336         namesAndIdsList.addAll(countersInIds);
1337         return getMaxInteger(namesAndIdsList);
1338     }
1339
1340     private Integer getMaxInteger(List<String> counters) {
1341         Integer maxCounter = 0;
1342         Integer currCounter = null;
1343         for (String counter : counters) {
1344             try {
1345                 currCounter = Integer.parseInt(counter);
1346                 if (maxCounter < currCounter) {
1347                     maxCounter = currCounter;
1348                 }
1349             } catch (NumberFormatException e) {
1350                 continue;
1351             }
1352         }
1353         return currCounter == null ? null : maxCounter;
1354     }
1355
1356     public Either<RequirementCapabilityRelDef, StorageOperationStatus> associateResourceInstances(Component component, String componentId,
1357                                                                                                   RequirementCapabilityRelDef requirementDef) {
1358         return nodeTemplateOperation.associateResourceInstances(component, componentId, requirementDef);
1359     }
1360
1361     public Either<List<InputDefinition>, StorageOperationStatus> createAndAssociateInputs(Map<String, InputDefinition> inputs, String componentId) {
1362         Either<GraphVertex, JanusGraphOperationStatus> getVertexEither = janusGraphDao.getVertexById(componentId, JsonParseFlagEnum.NoParse);
1363         if (getVertexEither.isRight()) {
1364             log.debug(COULDNT_FETCH_COMPONENT_WITH_AND_UNIQUE_ID_ERROR, componentId, getVertexEither.right().value());
1365             return Either.right(DaoStatusConverter.convertJanusGraphStatusToStorageStatus(getVertexEither.right().value()));
1366         }
1367         GraphVertex vertex = getVertexEither.left().value();
1368         Map<String, PropertyDataDefinition> inputsMap = inputs.entrySet().stream()
1369             .collect(Collectors.toMap(Map.Entry::getKey, e -> new PropertyDataDefinition(e.getValue())));
1370         StorageOperationStatus status = topologyTemplateOperation.associateInputsToComponent(vertex, inputsMap, componentId);
1371         if (StorageOperationStatus.OK == status) {
1372             log.debug(INPUTS_ASSOCIATED_TO_COMPONENT_SUCCESSFULLY);
1373             List<InputDefinition> inputsResList = null;
1374             if (inputsMap != null && !inputsMap.isEmpty()) {
1375                 inputsResList = inputsMap.values().stream().map(InputDefinition::new).collect(Collectors.toList());
1376             }
1377             return Either.left(inputsResList);
1378         }
1379         return Either.right(status);
1380     }
1381
1382     public Either<List<OutputDefinition>, StorageOperationStatus> createAndAssociateOutputs(final Map<String, OutputDefinition> outputs,
1383                                                                                             final String componentId) {
1384         final Either<GraphVertex, JanusGraphOperationStatus> getVertexEither = janusGraphDao.getVertexById(componentId, JsonParseFlagEnum.NoParse);
1385         if (getVertexEither.isRight()) {
1386             log.debug(COULDNT_FETCH_COMPONENT_WITH_AND_UNIQUE_ID_ERROR, componentId, getVertexEither.right().value());
1387             return Either.right(DaoStatusConverter.convertJanusGraphStatusToStorageStatus(getVertexEither.right().value()));
1388         }
1389         final GraphVertex vertex = getVertexEither.left().value();
1390         final Map<String, OutputDefinition> outputsMap = outputs.entrySet().stream()
1391             .collect(Collectors.toMap(Map.Entry::getKey, e -> new OutputDefinition(e.getValue())));
1392         final StorageOperationStatus status = topologyTemplateOperation.associateOutputsToComponent(vertex, outputsMap, componentId);
1393         if (StorageOperationStatus.OK == status) {
1394             log.debug(OUTPUTS_ASSOCIATED_TO_COMPONENT_SUCCESSFULLY);
1395             List<OutputDefinition> outputsResList = null;
1396             if (MapUtils.isNotEmpty(outputsMap)) {
1397                 outputsResList = outputsMap.values().stream().map(OutputDefinition::new).collect(Collectors.toList());
1398             }
1399             return Either.left(outputsResList);
1400         }
1401         return Either.right(status);
1402     }
1403
1404     public Either<List<InputDefinition>, StorageOperationStatus> addInputsToComponent(Map<String, InputDefinition> inputs, String componentId) {
1405         Either<GraphVertex, JanusGraphOperationStatus> getVertexEither = janusGraphDao.getVertexById(componentId, JsonParseFlagEnum.NoParse);
1406         if (getVertexEither.isRight()) {
1407             log.debug(COULDNT_FETCH_COMPONENT_WITH_AND_UNIQUE_ID_ERROR, componentId, getVertexEither.right().value());
1408             return Either.right(DaoStatusConverter.convertJanusGraphStatusToStorageStatus(getVertexEither.right().value()));
1409         }
1410         GraphVertex vertex = getVertexEither.left().value();
1411         Map<String, PropertyDefinition> inputsMap = inputs.entrySet().stream()
1412             .collect(Collectors.toMap(Map.Entry::getKey, e -> new PropertyDefinition(e.getValue())));
1413         StorageOperationStatus status = topologyTemplateOperation
1414             .addToscaDataToToscaElement(vertex, EdgeLabelEnum.INPUTS, VertexTypeEnum.INPUTS, inputsMap, JsonPresentationFields.NAME);
1415         if (StorageOperationStatus.OK == status) {
1416             log.debug(COMPONENT_CREATED_SUCCESSFULLY);
1417             List<InputDefinition> inputsResList = null;
1418             if (inputsMap != null && !inputsMap.isEmpty()) {
1419                 inputsResList = inputsMap.values().stream().map(InputDefinition::new).collect(Collectors.toList());
1420             }
1421             return Either.left(inputsResList);
1422         }
1423         return Either.right(status);
1424     }
1425
1426     public Either<List<OutputDefinition>, StorageOperationStatus> addOutputsToComponent(Map<String, OutputDefinition> outputs, String componentId) {
1427         Either<GraphVertex, JanusGraphOperationStatus> getVertexEither = janusGraphDao.getVertexById(componentId, JsonParseFlagEnum.NoParse);
1428         if (getVertexEither.isRight()) {
1429             log.debug(COULDNT_FETCH_COMPONENT_WITH_AND_UNIQUE_ID_ERROR, componentId, getVertexEither.right().value());
1430             return Either.right(DaoStatusConverter.convertJanusGraphStatusToStorageStatus(getVertexEither.right().value()));
1431         }
1432         GraphVertex vertex = getVertexEither.left().value();
1433         Map<String, AttributeDefinition> outputsMap = outputs.entrySet().stream()
1434             .collect(Collectors.toMap(Map.Entry::getKey, e -> new AttributeDefinition(e.getValue())));
1435         StorageOperationStatus status = topologyTemplateOperation
1436             .addToscaDataToToscaElement(vertex, EdgeLabelEnum.OUTPUTS, VertexTypeEnum.OUTPUTS, outputsMap, JsonPresentationFields.NAME);
1437         if (StorageOperationStatus.OK == status) {
1438             log.debug(COMPONENT_CREATED_SUCCESSFULLY);
1439             List<OutputDefinition> outputsResList = null;
1440             if (outputsMap != null && !outputsMap.isEmpty()) {
1441                 outputsResList = outputsMap.values().stream().map(OutputDefinition::new).collect(Collectors.toList());
1442             }
1443             return Either.left(outputsResList);
1444         }
1445         return Either.right(status);
1446     }
1447
1448     /**
1449      * Add data types into a Component.
1450      *
1451      * @param dataTypes   datatypes to be added. the key should be each name of data type.
1452      * @param componentId unique ID of Component.
1453      * @return list of data types.
1454      */
1455     public Either<List<DataTypeDefinition>, StorageOperationStatus> addDataTypesToComponent(Map<String, DataTypeDefinition> dataTypes,
1456                                                                                             String componentId) {
1457         log.trace("#addDataTypesToComponent - enter, componentId={}", componentId);
1458         /* get component vertex */
1459         Either<GraphVertex, JanusGraphOperationStatus> getVertexEither = janusGraphDao
1460             .getVertexById(componentId, JsonParseFlagEnum.NoParse);
1461         if (getVertexEither.isRight()) {
1462             /* not found / error */
1463             log.debug(COULDNT_FETCH_COMPONENT_WITH_AND_UNIQUE_ID_ERROR, componentId, getVertexEither.right().value());
1464             return Either.right(DaoStatusConverter.convertJanusGraphStatusToStorageStatus(getVertexEither.right().value()));
1465         }
1466         GraphVertex vertex = getVertexEither.left().value();
1467         log.trace("#addDataTypesToComponent - get vertex ok");
1468         // convert DataTypeDefinition to DataTypeDataDefinition
1469         Map<String, DataTypeDataDefinition> dataTypeDataMap = dataTypes.entrySet().stream()
1470             .collect(Collectors.toMap(Map.Entry::getKey, e -> convertDataTypeToDataTypeData(e.getValue())));
1471         // add datatype(s) to the Component.
1472
1473         // if child vertex does not exist, it will be created.
1474         StorageOperationStatus status = topologyTemplateOperation
1475             .addToscaDataToToscaElement(vertex, EdgeLabelEnum.DATA_TYPES, VertexTypeEnum.DATA_TYPES, dataTypeDataMap, JsonPresentationFields.NAME);
1476         if (StorageOperationStatus.OK == status) {
1477             log.debug(COMPONENT_CREATED_SUCCESSFULLY);
1478             List<DataTypeDefinition> inputsResList = null;
1479             if (!dataTypes.isEmpty()) {
1480                 inputsResList = new ArrayList<>(dataTypes.values());
1481             }
1482             return Either.left(inputsResList);
1483         }
1484         log.trace("#addDataTypesToComponent - leave");
1485         return Either.right(status);
1486     }
1487
1488     private DataTypeDataDefinition convertDataTypeToDataTypeData(DataTypeDefinition dataType) {
1489         DataTypeDataDefinition dataTypeData = new DataTypeDataDefinition(dataType);
1490         if (CollectionUtils.isNotEmpty(dataType.getProperties())) {
1491             List<PropertyDataDefinition> propertyDataList = dataType.getProperties().stream().map(PropertyDataDefinition::new)
1492                 .collect(Collectors.toList());
1493             dataTypeData.setPropertiesData(propertyDataList);
1494         }
1495         // if "derivedFrom" data_type exists, copy the name to "derivedFromName"
1496         if (dataType.getDerivedFrom() != null && StringUtils.isNotEmpty(dataType.getDerivedFrom().getName())) {
1497             // if names are different, log it
1498             if (!StringUtils.equals(dataTypeData.getDerivedFromName(), dataType.getDerivedFrom().getName())) {
1499                 log.debug("#convertDataTypeToDataTypeData - derivedFromName(={}) overwritten by derivedFrom.name(={})", dataType.getDerivedFromName(),
1500                     dataType.getDerivedFrom().getName());
1501             }
1502             dataTypeData.setDerivedFromName(dataType.getDerivedFrom().getName());
1503         }
1504         // supply "name" field to toscaPresentationValue in each datatype object for DAO operations
1505         dataTypeData.setToscaPresentationValue(JsonPresentationFields.NAME, dataType.getName());
1506         return dataTypeData;
1507     }
1508
1509     public Either<List<InputDefinition>, StorageOperationStatus> getComponentInputs(String componentId) {
1510         Either<GraphVertex, JanusGraphOperationStatus> getVertexEither = janusGraphDao.getVertexById(componentId, JsonParseFlagEnum.NoParse);
1511         if (getVertexEither.isRight()) {
1512             log.debug(COULDNT_FETCH_COMPONENT_WITH_AND_UNIQUE_ID_ERROR, componentId, getVertexEither.right().value());
1513             return Either.right(DaoStatusConverter.convertJanusGraphStatusToStorageStatus(getVertexEither.right().value()));
1514         }
1515         Either<ToscaElement, StorageOperationStatus> toscaElement = topologyTemplateOperation.getToscaElement(componentId);
1516         if (toscaElement.isRight()) {
1517             return Either.right(toscaElement.right().value());
1518         }
1519         TopologyTemplate topologyTemplate = (TopologyTemplate) toscaElement.left().value();
1520         Map<String, PropertyDataDefinition> inputsMap = topologyTemplate.getInputs();
1521         List<InputDefinition> inputs = new ArrayList<>();
1522         if (MapUtils.isNotEmpty(inputsMap)) {
1523             inputs = inputsMap.values().stream().map(p -> new InputDefinition(p)).collect(Collectors.toList());
1524         }
1525         return Either.left(inputs);
1526     }
1527
1528     public Either<List<InputDefinition>, StorageOperationStatus> updateInputsToComponent(List<InputDefinition> inputs, String componentId) {
1529         Either<GraphVertex, JanusGraphOperationStatus> getVertexEither = janusGraphDao.getVertexById(componentId, JsonParseFlagEnum.NoParse);
1530         if (getVertexEither.isRight()) {
1531             log.debug(COULDNT_FETCH_COMPONENT_WITH_AND_UNIQUE_ID_ERROR, componentId, getVertexEither.right().value());
1532             return Either.right(DaoStatusConverter.convertJanusGraphStatusToStorageStatus(getVertexEither.right().value()));
1533         }
1534         GraphVertex vertex = getVertexEither.left().value();
1535         List<PropertyDataDefinition> inputsAsDataDef = inputs.stream().map(PropertyDataDefinition::new).collect(Collectors.toList());
1536         StorageOperationStatus status = topologyTemplateOperation
1537             .updateToscaDataOfToscaElement(vertex, EdgeLabelEnum.INPUTS, VertexTypeEnum.INPUTS, inputsAsDataDef, JsonPresentationFields.NAME);
1538         if (StorageOperationStatus.OK == status) {
1539             log.debug(COMPONENT_CREATED_SUCCESSFULLY);
1540             List<InputDefinition> inputsResList = null;
1541             if (inputsAsDataDef != null && !inputsAsDataDef.isEmpty()) {
1542                 inputsResList = inputsAsDataDef.stream().map(InputDefinition::new).collect(Collectors.toList());
1543             }
1544             return Either.left(inputsResList);
1545         }
1546         return Either.right(status);
1547     }
1548
1549     public Either<List<OutputDefinition>, StorageOperationStatus> updateOutputsToComponent(List<OutputDefinition> outputs, String componentId) {
1550         Either<GraphVertex, JanusGraphOperationStatus> getVertexEither = janusGraphDao.getVertexById(componentId, JsonParseFlagEnum.NoParse);
1551         if (getVertexEither.isRight()) {
1552             log.debug(COULDNT_FETCH_COMPONENT_WITH_AND_UNIQUE_ID_ERROR, componentId, getVertexEither.right().value());
1553             return Either.right(DaoStatusConverter.convertJanusGraphStatusToStorageStatus(getVertexEither.right().value()));
1554         }
1555         GraphVertex vertex = getVertexEither.left().value();
1556         List<AttributeDataDefinition> outputsAsDataDef = outputs.stream().map(AttributeDataDefinition::new).collect(Collectors.toList());
1557         StorageOperationStatus status = topologyTemplateOperation
1558             .updateToscaDataOfToscaElement(vertex, EdgeLabelEnum.OUTPUTS, VertexTypeEnum.OUTPUTS, outputsAsDataDef, JsonPresentationFields.NAME);
1559         if (StorageOperationStatus.OK == status) {
1560             log.debug(COMPONENT_CREATED_SUCCESSFULLY);
1561             List<OutputDefinition> outputsResList = null;
1562             if (!outputsAsDataDef.isEmpty()) {
1563                 outputsResList = outputsAsDataDef.stream().map(OutputDefinition::new).collect(Collectors.toList());
1564             }
1565             return Either.left(outputsResList);
1566         }
1567         return Either.right(status);
1568     }
1569
1570     // region - ComponentInstance
1571     public Either<Map<String, List<ComponentInstanceProperty>>, StorageOperationStatus> associateComponentInstancePropertiesToComponent(
1572         Map<String, List<ComponentInstanceProperty>> instProperties, String componentId) {
1573         Either<GraphVertex, JanusGraphOperationStatus> getVertexEither = janusGraphDao.getVertexById(componentId, JsonParseFlagEnum.NoParse);
1574         if (getVertexEither.isRight()) {
1575             log.debug(COULDNT_FETCH_COMPONENT_WITH_AND_UNIQUE_ID_ERROR, componentId, getVertexEither.right().value());
1576             return Either.right(DaoStatusConverter.convertJanusGraphStatusToStorageStatus(getVertexEither.right().value()));
1577         }
1578         GraphVertex vertex = getVertexEither.left().value();
1579         Map<String, MapPropertiesDataDefinition> instPropsMap = new HashMap<>();
1580         if (instProperties != null) {
1581             MapPropertiesDataDefinition propertiesMap;
1582             for (Entry<String, List<ComponentInstanceProperty>> entry : instProperties.entrySet()) {
1583                 propertiesMap = new MapPropertiesDataDefinition();
1584                 propertiesMap.setMapToscaDataDefinition(
1585                     entry.getValue().stream().map(PropertyDataDefinition::new).collect(Collectors.toMap(PropertyDataDefinition::getName, e -> e)));
1586                 instPropsMap.put(entry.getKey(), propertiesMap);
1587             }
1588         }
1589         StorageOperationStatus status = topologyTemplateOperation.associateInstPropertiesToComponent(vertex, instPropsMap);
1590         if (StorageOperationStatus.OK == status) {
1591             log.debug(COMPONENT_CREATED_SUCCESSFULLY);
1592             return Either.left(instProperties);
1593         }
1594         return Either.right(status);
1595     }
1596
1597     /**
1598      * saves the instInputs as the updated instance inputs of the component container in DB
1599      */
1600     public Either<Map<String, List<ComponentInstanceInput>>, StorageOperationStatus> updateComponentInstanceInputsToComponent(
1601         Map<String, List<ComponentInstanceInput>> instInputs, String componentId) {
1602         if (instInputs == null || instInputs.isEmpty()) {
1603             return Either.left(instInputs);
1604         }
1605         StorageOperationStatus status;
1606         for (Entry<String, List<ComponentInstanceInput>> inputsPerIntance : instInputs.entrySet()) {
1607             List<ComponentInstanceInput> toscaDataListPerInst = inputsPerIntance.getValue();
1608             List<String> pathKeysPerInst = new ArrayList<>();
1609             pathKeysPerInst.add(inputsPerIntance.getKey());
1610             status = topologyTemplateOperation
1611                 .updateToscaDataDeepElementsOfToscaElement(componentId, EdgeLabelEnum.INST_INPUTS, VertexTypeEnum.INST_INPUTS, toscaDataListPerInst,
1612                     pathKeysPerInst, JsonPresentationFields.NAME);
1613             if (status != StorageOperationStatus.OK) {
1614                 log.debug("Failed to update component instance inputs for instance {} in component {} edge type {} error {}",
1615                     inputsPerIntance.getKey(), componentId, EdgeLabelEnum.INST_INPUTS, status);
1616                 return Either.right(status);
1617             }
1618         }
1619         return Either.left(instInputs);
1620     }
1621
1622     /**
1623      * saves the instProps as the updated instance properties of the component container in DB
1624      */
1625     public Either<Map<String, List<ComponentInstanceProperty>>, StorageOperationStatus> updateComponentInstancePropsToComponent(
1626         Map<String, List<ComponentInstanceProperty>> instProps, String componentId) {
1627         if (instProps == null || instProps.isEmpty()) {
1628             return Either.left(instProps);
1629         }
1630         StorageOperationStatus status;
1631         for (Entry<String, List<ComponentInstanceProperty>> propsPerIntance : instProps.entrySet()) {
1632             List<ComponentInstanceProperty> toscaDataListPerInst = propsPerIntance.getValue();
1633             List<String> pathKeysPerInst = new ArrayList<>();
1634             pathKeysPerInst.add(propsPerIntance.getKey());
1635             status = topologyTemplateOperation
1636                 .updateToscaDataDeepElementsOfToscaElement(componentId, EdgeLabelEnum.INST_PROPERTIES, VertexTypeEnum.INST_PROPERTIES,
1637                     toscaDataListPerInst, pathKeysPerInst, JsonPresentationFields.NAME);
1638             if (status != StorageOperationStatus.OK) {
1639                 log.debug("Failed to update component instance inputs for instance {} in component {} edge type {} error {}",
1640                     propsPerIntance.getKey(), componentId, EdgeLabelEnum.INST_PROPERTIES, status);
1641                 return Either.right(status);
1642             }
1643         }
1644         return Either.left(instProps);
1645     }
1646
1647     public Either<Map<String, List<ComponentInstanceInput>>, StorageOperationStatus> associateComponentInstanceInputsToComponent(
1648         Map<String, List<ComponentInstanceInput>> instInputs, String componentId) {
1649         Either<GraphVertex, JanusGraphOperationStatus> getVertexEither = janusGraphDao.getVertexById(componentId, JsonParseFlagEnum.NoParse);
1650         if (getVertexEither.isRight()) {
1651             log.debug(COULDNT_FETCH_COMPONENT_WITH_AND_UNIQUE_ID_ERROR, componentId, getVertexEither.right().value());
1652             return Either.right(DaoStatusConverter.convertJanusGraphStatusToStorageStatus(getVertexEither.right().value()));
1653         }
1654         GraphVertex vertex = getVertexEither.left().value();
1655         Map<String, MapPropertiesDataDefinition> instPropsMap = new HashMap<>();
1656         if (instInputs != null) {
1657             MapPropertiesDataDefinition propertiesMap;
1658             for (Entry<String, List<ComponentInstanceInput>> entry : instInputs.entrySet()) {
1659                 propertiesMap = new MapPropertiesDataDefinition();
1660                 propertiesMap.setMapToscaDataDefinition(
1661                     entry.getValue().stream().map(PropertyDataDefinition::new).collect(Collectors.toMap(PropertyDataDefinition::getName, e -> e)));
1662                 instPropsMap.put(entry.getKey(), propertiesMap);
1663             }
1664         }
1665         StorageOperationStatus status = topologyTemplateOperation.associateInstInputsToComponent(vertex, instPropsMap);
1666         if (StorageOperationStatus.OK == status) {
1667             log.debug(COMPONENT_CREATED_SUCCESSFULLY);
1668             return Either.left(instInputs);
1669         }
1670         return Either.right(status);
1671     }
1672
1673     public Either<Map<String, MapInterfaceDataDefinition>, StorageOperationStatus> associateComponentInstanceInterfacesToComponent(
1674             Map<String, Map<String, InterfaceDefinition>> instInterfaces,
1675             String componentId
1676     ) {
1677         Either<GraphVertex, JanusGraphOperationStatus> getVertexEither = janusGraphDao.getVertexById(
1678                 componentId,
1679                 JsonParseFlagEnum.NoParse
1680         );
1681         if (getVertexEither.isRight()) {
1682             log.debug(
1683                     COULDNT_FETCH_COMPONENT_WITH_AND_UNIQUE_ID_ERROR,
1684                     componentId,
1685                     getVertexEither.right().value()
1686             );
1687             return Either.right(
1688                     DaoStatusConverter.convertJanusGraphStatusToStorageStatus(
1689                             getVertexEither.right().value()
1690                     )
1691             );
1692         }
1693         GraphVertex vertex = getVertexEither.left().value();
1694         Map<String, MapInterfaceDataDefinition> instInterfacesMap = new HashMap<>();
1695         if (instInterfaces != null) {
1696             MapInterfaceDataDefinition interfacesMap = new MapInterfaceDataDefinition();
1697             for (Map.Entry<String, Map<String, InterfaceDefinition>> entryInstances : instInterfaces.entrySet()) {
1698                 Map<String, InterfaceDataDefinition> incomingInterfacesMap = entryInstances.getValue().entrySet().stream()
1699                         .collect(Collectors.toMap(e -> e.getKey(), e -> e.getValue()));
1700                 interfacesMap.setMapToscaDataDefinition(incomingInterfacesMap);
1701                 instInterfacesMap.put(entryInstances.getKey(), interfacesMap);
1702             }
1703         }
1704         StorageOperationStatus status = topologyTemplateOperation.associateInstInterfacesToComponent(
1705                 vertex,
1706                 instInterfacesMap
1707         );
1708         if (StorageOperationStatus.OK == status) {
1709             log.debug(COMPONENT_CREATED_SUCCESSFULLY);
1710             return Either.left(instInterfacesMap);
1711         }
1712         return Either.right(status);
1713     }
1714
1715     public Either<Map<String, List<ComponentInstanceInput>>, StorageOperationStatus> addComponentInstanceInputsToComponent(
1716         Component containerComponent, Map<String, List<ComponentInstanceInput>> instProperties) {
1717         requireNonNull(instProperties);
1718         StorageOperationStatus status;
1719         for (Entry<String, List<ComponentInstanceInput>> entry : instProperties.entrySet()) {
1720             List<ComponentInstanceInput> props = entry.getValue();
1721             String componentInstanceId = entry.getKey();
1722             if (!isEmpty(props)) {
1723                 for (ComponentInstanceInput property : props) {
1724                     List<ComponentInstanceInput> componentInstancesInputs = containerComponent.getComponentInstancesInputs().get(componentInstanceId);
1725                     Optional<ComponentInstanceInput> instanceProperty = componentInstancesInputs.stream()
1726                         .filter(p -> p.getName().equals(property.getName())).findAny();
1727                     if (instanceProperty.isPresent()) {
1728                         status = updateComponentInstanceInput(containerComponent, componentInstanceId, property);
1729                     } else {
1730                         status = addComponentInstanceInput(containerComponent, componentInstanceId, property);
1731                     }
1732                     if (status != StorageOperationStatus.OK) {
1733                         log.debug("Failed to update instance input {} for instance {} error {} ", property, componentInstanceId, status);
1734                         return Either.right(status);
1735                     } else {
1736                         log.trace("instance input {} for instance {} updated", property, componentInstanceId);
1737                     }
1738                 }
1739             }
1740         }
1741         return Either.left(instProperties);
1742     }
1743
1744     public Either<Map<String, List<ComponentInstanceOutput>>, StorageOperationStatus> addComponentInstanceOutputsToComponent(
1745         Component containerComponent, Map<String, List<ComponentInstanceOutput>> instOutputs) {
1746         requireNonNull(instOutputs);
1747         StorageOperationStatus status;
1748         for (final Entry<String, List<ComponentInstanceOutput>> entry : instOutputs.entrySet()) {
1749             final List<ComponentInstanceOutput> outputs = entry.getValue();
1750             final String componentInstanceId = entry.getKey();
1751             if (!isEmpty(outputs)) {
1752                 for (final ComponentInstanceOutput output : outputs) {
1753                     final List<ComponentInstanceOutput> componentInstanceOutputs = containerComponent.getComponentInstancesOutputs()
1754                         .get(componentInstanceId);
1755                     final Optional<ComponentInstanceOutput> componentInstanceOutput = componentInstanceOutputs.stream()
1756                         .filter(p -> p.getName().equals(output.getName())).findAny();
1757                     if (componentInstanceOutput.isPresent()) {
1758                         status = updateComponentInstanceOutput(containerComponent, componentInstanceId, output);
1759                     } else {
1760                         status = addComponentInstanceOutput(containerComponent, componentInstanceId, output);
1761                     }
1762                     if (status != StorageOperationStatus.OK) {
1763                         log.debug("Failed to update instance output {} for instance {} error {} ", output, componentInstanceId, status);
1764                         return Either.right(status);
1765                     } else {
1766                         log.trace("instance output {} for instance {} updated", output, componentInstanceId);
1767                     }
1768                 }
1769             }
1770         }
1771         return Either.left(instOutputs);
1772     }
1773
1774     public Either<Map<String, List<ComponentInstanceProperty>>, StorageOperationStatus> addComponentInstancePropertiesToComponent(
1775         Component containerComponent, Map<String, List<ComponentInstanceProperty>> instProperties) {
1776         requireNonNull(instProperties);
1777         for (Entry<String, List<ComponentInstanceProperty>> entry : instProperties.entrySet()) {
1778             List<ComponentInstanceProperty> props = entry.getValue();
1779             String componentInstanceId = entry.getKey();
1780             List<ComponentInstanceProperty> originalComponentInstProps = containerComponent.getComponentInstancesProperties()
1781                 .get(componentInstanceId);
1782             Map<String, List<CapabilityDefinition>> containerComponentCapabilities = containerComponent.getCapabilities();
1783             if (isEmpty(props)) {
1784                 continue;
1785             }
1786             for (ComponentInstanceProperty property : props) {
1787                 StorageOperationStatus status = null;
1788                 String propertyParentUniqueId = property.getParentUniqueId();
1789                 Optional<CapabilityDefinition> capPropDefinition = getPropertyCapability(propertyParentUniqueId, containerComponent);
1790                 if (capPropDefinition.isPresent() && MapUtils.isNotEmpty(containerComponentCapabilities)) {
1791                     status = populateAndUpdateInstanceCapProperty(containerComponent, componentInstanceId, containerComponentCapabilities, property,
1792                         capPropDefinition.get());
1793                 }
1794                 if (status == null) {
1795                     status = updateOrAddComponentInstanceProperty(containerComponent, componentInstanceId, originalComponentInstProps, property);
1796                 }
1797                 if (status != StorageOperationStatus.OK) {
1798                     return Either.right(status);
1799                 }
1800             }
1801         }
1802         return Either.left(instProperties);
1803     }
1804
1805     public Either<Map<String, List<ComponentInstanceAttribute>>, StorageOperationStatus> addComponentInstanceAttributesToComponent(
1806         final Component containerComponent, final Map<String, List<ComponentInstanceAttribute>> instProperties) {
1807         requireNonNull(instProperties);
1808         for (final Entry<String, List<ComponentInstanceAttribute>> entry : instProperties.entrySet()) {
1809             final List<ComponentInstanceAttribute> props = entry.getValue();
1810             if (isEmpty(props)) {
1811                 continue;
1812             }
1813             final String componentInstanceId = entry.getKey();
1814             final List<ComponentInstanceAttribute> originalComponentInstProps = containerComponent.getComponentInstancesAttributes()
1815                 .get(componentInstanceId);
1816             for (final ComponentInstanceAttribute property : props) {
1817                 final StorageOperationStatus status = updateOrAddComponentInstanceAttribute(containerComponent, componentInstanceId,
1818                     originalComponentInstProps, property);
1819                 if (status != StorageOperationStatus.OK) {
1820                     return Either.right(status);
1821                 }
1822             }
1823         }
1824         return Either.left(instProperties);
1825     }
1826
1827     private StorageOperationStatus populateAndUpdateInstanceCapProperty(Component containerComponent, String componentInstanceId,
1828                                                                         Map<String, List<CapabilityDefinition>> containerComponentCapabilities,
1829                                                                         ComponentInstanceProperty property,
1830                                                                         CapabilityDefinition capabilityDefinition) {
1831         List<CapabilityDefinition> capabilityDefinitions = containerComponentCapabilities.get(capabilityDefinition.getType());
1832         if (CollectionUtils.isEmpty(capabilityDefinitions)) {
1833             return null;
1834         }
1835         Optional<CapabilityDefinition> capDefToGetProp = capabilityDefinitions.stream()
1836             .filter(cap -> cap.getUniqueId().equals(capabilityDefinition.getUniqueId()) && cap.getPath().size() == 1).findAny();
1837         if (capDefToGetProp.isPresent()) {
1838             return updateInstanceCapabilityProperty(containerComponent, componentInstanceId, property, capDefToGetProp.get());
1839         }
1840         return null;
1841     }
1842
1843     private StorageOperationStatus updateOrAddComponentInstanceProperty(Component containerComponent, String componentInstanceId,
1844                                                                         List<ComponentInstanceProperty> originalComponentInstProps,
1845                                                                         ComponentInstanceProperty property) {
1846         StorageOperationStatus status;
1847         // check if the property already exists or not
1848         Optional<ComponentInstanceProperty> instanceProperty = originalComponentInstProps.stream()
1849             .filter(p -> p.getUniqueId().equals(property.getUniqueId())).findAny();
1850         if (instanceProperty.isPresent()) {
1851             status = updateComponentInstanceProperty(containerComponent, componentInstanceId, property);
1852         } else {
1853             status = addComponentInstanceProperty(containerComponent, componentInstanceId, property);
1854         }
1855         if (status != StorageOperationStatus.OK) {
1856             log.debug("Failed to update instance property {} for instance {} error {} ", property, componentInstanceId, status);
1857         }
1858         return status;
1859     }
1860
1861     private StorageOperationStatus updateOrAddComponentInstanceAttribute(Component containerComponent, String componentInstanceId,
1862                                                                          List<ComponentInstanceAttribute> originalComponentInstProps,
1863                                                                          ComponentInstanceAttribute property) {
1864         StorageOperationStatus status;
1865         // check if the property already exists or not
1866         Optional<ComponentInstanceAttribute> instanceProperty = originalComponentInstProps.stream()
1867             .filter(p -> p.getUniqueId().equals(property.getUniqueId())).findAny();
1868         if (instanceProperty.isPresent()) {
1869             status = updateComponentInstanceAttribute(containerComponent, componentInstanceId, property);
1870         } else {
1871             status = addComponentInstanceAttribute(containerComponent, componentInstanceId, property);
1872         }
1873         if (status != StorageOperationStatus.OK) {
1874             log.debug("Failed to update instance property {} for instance {} error {} ", property, componentInstanceId, status);
1875         }
1876         return status;
1877     }
1878
1879     public StorageOperationStatus updateInstanceCapabilityProperty(Component containerComponent, String componentInstanceId,
1880                                                                    ComponentInstanceProperty property, CapabilityDefinition capabilityDefinition) {
1881         Optional<ComponentInstance> fetchedCIOptional = containerComponent.getComponentInstanceById(componentInstanceId);
1882         if (!fetchedCIOptional.isPresent()) {
1883             return StorageOperationStatus.GENERAL_ERROR;
1884         }
1885         Either<Component, StorageOperationStatus> getComponentRes = getToscaFullElement(fetchedCIOptional.get().getComponentUid());
1886         if (getComponentRes.isRight()) {
1887             return StorageOperationStatus.GENERAL_ERROR;
1888         }
1889         Optional<Component> componentOptional = isNodeServiceProxy(getComponentRes.left().value());
1890         String propOwner;
1891         if (!componentOptional.isPresent()) {
1892             propOwner = componentInstanceId;
1893         } else {
1894             propOwner = fetchedCIOptional.get().getSourceModelUid();
1895         }
1896         StorageOperationStatus status;
1897         StringBuilder sb = new StringBuilder(componentInstanceId);
1898         sb.append(ModelConverter.CAP_PROP_DELIM).append(propOwner).append(ModelConverter.CAP_PROP_DELIM).append(capabilityDefinition.getType())
1899             .append(ModelConverter.CAP_PROP_DELIM).append(capabilityDefinition.getName());
1900         String capKey = sb.toString();
1901         status = updateComponentInstanceCapabiltyProperty(containerComponent, componentInstanceId, capKey, property);
1902         if (status != StorageOperationStatus.OK) {
1903             log.debug("Failed to update instance capability property {} for instance {} error {} ", property, componentInstanceId, status);
1904             return status;
1905         }
1906         return StorageOperationStatus.OK;
1907     }
1908
1909     private Optional<Component> isNodeServiceProxy(Component component) {
1910         if (component.getComponentType().equals(ComponentTypeEnum.SERVICE)) {
1911             return Optional.empty();
1912         }
1913         Resource resource = (Resource) component;
1914         ResourceTypeEnum resType = resource.getResourceType();
1915         if (resType.equals(ResourceTypeEnum.ServiceProxy)) {
1916             return Optional.of(component);
1917         }
1918         return Optional.empty();
1919     }
1920
1921     public StorageOperationStatus associateCapabilitiesToService(Map<String, ListCapabilityDataDefinition> capabilities, String componentId) {
1922         Either<GraphVertex, JanusGraphOperationStatus> getVertexEither = janusGraphDao.getVertexById(componentId, JsonParseFlagEnum.NoParse);
1923         if (getVertexEither.isRight()) {
1924             log.debug(COULDNT_FETCH_COMPONENT_WITH_AND_UNIQUE_ID_ERROR, componentId, getVertexEither.right().value());
1925             return DaoStatusConverter.convertJanusGraphStatusToStorageStatus(getVertexEither.right().value());
1926         }
1927         GraphVertex vertex = getVertexEither.left().value();
1928         if (MapUtils.isNotEmpty(capabilities)) {
1929             Either<GraphVertex, StorageOperationStatus> associateElementToData = topologyTemplateOperation
1930                 .associateElementToData(vertex, VertexTypeEnum.CAPABILITIES, EdgeLabelEnum.CAPABILITIES, capabilities);
1931             if (associateElementToData.isRight()) {
1932                 return associateElementToData.right().value();
1933             }
1934         }
1935         return StorageOperationStatus.OK;
1936     }
1937
1938     public StorageOperationStatus associateRequirementsToService(Map<String, ListRequirementDataDefinition> requirements, String componentId) {
1939         Either<GraphVertex, JanusGraphOperationStatus> getVertexEither = janusGraphDao.getVertexById(componentId, JsonParseFlagEnum.NoParse);
1940         if (getVertexEither.isRight()) {
1941             log.debug(COULDNT_FETCH_COMPONENT_WITH_AND_UNIQUE_ID_ERROR, componentId, getVertexEither.right().value());
1942             return DaoStatusConverter.convertJanusGraphStatusToStorageStatus(getVertexEither.right().value());
1943         }
1944         GraphVertex vertex = getVertexEither.left().value();
1945         if (MapUtils.isNotEmpty(requirements)) {
1946             Either<GraphVertex, StorageOperationStatus> associateElementToData = topologyTemplateOperation
1947                 .associateElementToData(vertex, VertexTypeEnum.REQUIREMENTS, EdgeLabelEnum.REQUIREMENTS, requirements);
1948             if (associateElementToData.isRight()) {
1949                 return associateElementToData.right().value();
1950             }
1951         }
1952         return StorageOperationStatus.OK;
1953     }
1954
1955     public StorageOperationStatus associateDeploymentArtifactsToInstances(Map<String, Map<String, ArtifactDefinition>> instDeploymentArtifacts,
1956                                                                           Component component, User user) {
1957         Either<GraphVertex, JanusGraphOperationStatus> getVertexEither = janusGraphDao
1958             .getVertexById(component.getUniqueId(), JsonParseFlagEnum.NoParse);
1959         if (getVertexEither.isRight()) {
1960             log.debug(COULDNT_FETCH_COMPONENT_WITH_AND_UNIQUE_ID_ERROR, component.getUniqueId(), getVertexEither.right().value());
1961             return DaoStatusConverter.convertJanusGraphStatusToStorageStatus(getVertexEither.right().value());
1962         }
1963         GraphVertex vertex = getVertexEither.left().value();
1964         Map<String, MapArtifactDataDefinition> instArtMap = new HashMap<>();
1965         if (instDeploymentArtifacts != null) {
1966             MapArtifactDataDefinition artifactsMap;
1967             for (Entry<String, Map<String, ArtifactDefinition>> entry : instDeploymentArtifacts.entrySet()) {
1968                 Map<String, ArtifactDefinition> artList = entry.getValue();
1969                 Map<String, ArtifactDataDefinition> artifacts = artList.entrySet().stream()
1970                     .collect(Collectors.toMap(Map.Entry::getKey, e -> new ArtifactDataDefinition(e.getValue())));
1971                 artifactsMap = nodeTemplateOperation
1972                     .prepareInstDeploymentArtifactPerInstance(artifacts, entry.getKey(), user, NodeTemplateOperation.HEAT_VF_ENV_NAME);
1973                 instArtMap.put(entry.getKey(), artifactsMap);
1974             }
1975         }
1976         ModelConverter.setComponentInstancesDeploymentArtifactsToComponent(instArtMap, component);
1977         return topologyTemplateOperation.associateInstDeploymentArtifactsToComponent(vertex, instArtMap);
1978     }
1979
1980     public StorageOperationStatus associateArtifactsToInstances(Map<String, Map<String, ArtifactDefinition>> instArtifacts, Component component) {
1981         Either<GraphVertex, JanusGraphOperationStatus> getVertexEither = janusGraphDao
1982             .getVertexById(component.getUniqueId(), JsonParseFlagEnum.NoParse);
1983         if (getVertexEither.isRight()) {
1984             log.debug(COULDNT_FETCH_COMPONENT_WITH_AND_UNIQUE_ID_ERROR, component.getUniqueId(), getVertexEither.right().value());
1985             return DaoStatusConverter.convertJanusGraphStatusToStorageStatus(getVertexEither.right().value());
1986         }
1987         GraphVertex vertex = getVertexEither.left().value();
1988         Map<String, MapArtifactDataDefinition> instArtMap = new HashMap<>();
1989         if (instArtifacts != null) {
1990             MapArtifactDataDefinition artifactsMap;
1991             for (Entry<String, Map<String, ArtifactDefinition>> entry : instArtifacts.entrySet()) {
1992                 Map<String, ArtifactDefinition> artList = entry.getValue();
1993                 Map<String, ArtifactDataDefinition> artifacts = artList.entrySet().stream()
1994                     .collect(Collectors.toMap(Map.Entry::getKey, e -> new ArtifactDataDefinition(e.getValue())));
1995                 artifactsMap = new MapArtifactDataDefinition(artifacts);
1996                 instArtMap.put(entry.getKey(), artifactsMap);
1997             }
1998         }
1999         ModelConverter.setComponentInstancesInformationalArtifactsToComponent(instArtMap, component);
2000         return topologyTemplateOperation.associateInstArtifactsToComponent(vertex, instArtMap);
2001     }
2002
2003     public StorageOperationStatus associateInstAttributeToComponentToInstances(Map<String, List<AttributeDefinition>> instArttributes,
2004                                                                                Component component) {
2005         Either<GraphVertex, JanusGraphOperationStatus> getVertexEither = janusGraphDao
2006             .getVertexById(component.getUniqueId(), JsonParseFlagEnum.NoParse);
2007         if (getVertexEither.isRight()) {
2008             log.debug(COULDNT_FETCH_COMPONENT_WITH_AND_UNIQUE_ID_ERROR, component.getUniqueId(), getVertexEither.right().value());
2009             return DaoStatusConverter.convertJanusGraphStatusToStorageStatus(getVertexEither.right().value());
2010         }
2011         GraphVertex vertex = getVertexEither.left().value();
2012         Map<String, MapAttributesDataDefinition> instAttr = new HashMap<>();
2013         if (instArttributes != null) {
2014             MapAttributesDataDefinition attributesMap;
2015             for (Entry<String, List<AttributeDefinition>> entry : instArttributes.entrySet()) {
2016                 final List<AttributeDefinition> value = entry.getValue();
2017                 attributesMap = new MapAttributesDataDefinition();
2018                 attributesMap.setMapToscaDataDefinition(
2019                     value.stream().map(AttributeDefinition::new).collect(Collectors.toMap(AttributeDefinition::getName, e -> e)));
2020                 instAttr.put(entry.getKey(), attributesMap);
2021             }
2022         }
2023         setComponentInstanceAttributesOnComponent(component, instAttr);
2024         return topologyTemplateOperation.associateInstAttributeToComponent(vertex, instAttr);
2025     }
2026
2027     // endregion
2028     private void setComponentInstanceAttributesOnComponent(Component resource, Map<String, MapAttributesDataDefinition> instAttr) {
2029         Map<String, List<ComponentInstanceAttribute>> componentInstancesAttributes = resource.getComponentInstancesAttributes();
2030         if (componentInstancesAttributes == null) {
2031             componentInstancesAttributes = new HashMap<>();
2032         }
2033         componentInstancesAttributes.putAll(ModelConverter.getComponentInstancesAttributes(instAttr));
2034         resource.setComponentInstancesAttributes(componentInstancesAttributes);
2035     }
2036
2037     public StorageOperationStatus associateOrAddCalculatedCapReq(Map<ComponentInstance, Map<String, List<CapabilityDefinition>>> instCapabilties,
2038                                                                  Map<ComponentInstance, Map<String, List<RequirementDefinition>>> instReg,
2039                                                                  Component component) {
2040         Either<GraphVertex, JanusGraphOperationStatus> getVertexEither = janusGraphDao
2041             .getVertexById(component.getUniqueId(), JsonParseFlagEnum.NoParse);
2042         if (getVertexEither.isRight()) {
2043             log.debug(COULDNT_FETCH_COMPONENT_WITH_AND_UNIQUE_ID_ERROR, component.getUniqueId(), getVertexEither.right().value());
2044             return DaoStatusConverter.convertJanusGraphStatusToStorageStatus(getVertexEither.right().value());
2045         }
2046         GraphVertex vertex = getVertexEither.left().value();
2047         Map<String, MapListRequirementDataDefinition> calcRequirements = new HashMap<>();
2048         Map<String, MapListCapabilityDataDefinition> calcCapabilty = new HashMap<>();
2049         Map<String, MapCapabilityProperty> calculatedCapabilitiesProperties = new HashMap<>();
2050         if (instCapabilties != null) {
2051             for (Entry<ComponentInstance, Map<String, List<CapabilityDefinition>>> entry : instCapabilties.entrySet()) {
2052                 Map<String, List<CapabilityDefinition>> caps = entry.getValue();
2053                 Map<String, ListCapabilityDataDefinition> mapToscaDataDefinition = new HashMap<>();
2054                 for (Entry<String, List<CapabilityDefinition>> instCapability : caps.entrySet()) {
2055                     mapToscaDataDefinition.put(instCapability.getKey(), new ListCapabilityDataDefinition(
2056                         instCapability.getValue().stream().map(CapabilityDataDefinition::new).collect(Collectors.toList())));
2057                 }
2058                 ComponentInstanceDataDefinition componentInstance = new ComponentInstanceDataDefinition(entry.getKey());
2059                 MapListCapabilityDataDefinition capMap = nodeTemplateOperation
2060                     .prepareCalculatedCapabiltyForNodeType(mapToscaDataDefinition, componentInstance);
2061                 MapCapabilityProperty mapCapabilityProperty = ModelConverter
2062                     .convertToMapOfMapCapabiltyProperties(caps, componentInstance.getUniqueId(), true);
2063                 calcCapabilty.put(entry.getKey().getUniqueId(), capMap);
2064                 calculatedCapabilitiesProperties.put(entry.getKey().getUniqueId(), mapCapabilityProperty);
2065             }
2066         }
2067         if (instReg != null) {
2068             for (Entry<ComponentInstance, Map<String, List<RequirementDefinition>>> entry : instReg.entrySet()) {
2069                 Map<String, List<RequirementDefinition>> req = entry.getValue();
2070                 Map<String, ListRequirementDataDefinition> mapToscaDataDefinition = new HashMap<>();
2071                 for (Entry<String, List<RequirementDefinition>> instReq : req.entrySet()) {
2072                     mapToscaDataDefinition.put(instReq.getKey(), new ListRequirementDataDefinition(
2073                         instReq.getValue().stream().map(RequirementDataDefinition::new).collect(Collectors.toList())));
2074                 }
2075                 MapListRequirementDataDefinition reqMap = nodeTemplateOperation
2076                     .prepareCalculatedRequirementForNodeType(mapToscaDataDefinition, new ComponentInstanceDataDefinition(entry.getKey()));
2077                 String componentInstanceId = entry.getKey().getUniqueId();
2078                 calcRequirements.put(componentInstanceId, reqMap);
2079             }
2080         }
2081         StorageOperationStatus storageOperationStatus = topologyTemplateOperation
2082             .associateOrAddCalcCapReqToComponent(vertex, calcRequirements, calcCapabilty, calculatedCapabilitiesProperties);
2083         updateInstancesCapAndReqOnComponentFromDB(component);
2084         return storageOperationStatus;
2085     }
2086
2087     public StorageOperationStatus updateCalculatedCapabilitiesRequirements(
2088         final Map<ComponentInstance, Map<String, List<CapabilityDefinition>>> instCapabilties,
2089         final Map<ComponentInstance, Map<String, List<RequirementDefinition>>> instReg,
2090         final Component component) {
2091         StorageOperationStatus storageOperationStatus = StorageOperationStatus.OK;
2092         if (instCapabilties != null) {
2093             for (Entry<ComponentInstance, Map<String, List<CapabilityDefinition>>> entry : instCapabilties.entrySet()) {
2094                 final Map<String, List<CapabilityDefinition>> cap = entry.getValue();
2095                 for (List<CapabilityDefinition> capabilityList : cap.values()) {
2096                     for (CapabilityDefinition capability : capabilityList) {
2097                         nodeTemplateOperation.updateComponentInstanceCapabilities(component.getUniqueId(), entry.getKey().getUniqueId(), capability);
2098                     }
2099                 }
2100             }
2101         }
2102         if (instReg != null) {
2103             for (Entry<ComponentInstance, Map<String, List<RequirementDefinition>>> entry : instReg.entrySet()) {
2104                 final Map<String, List<RequirementDefinition>> req = entry.getValue();
2105                 for (List<RequirementDefinition> requirementList : req.values()) {
2106                     for (RequirementDefinition requirement : requirementList) {
2107                         storageOperationStatus = nodeTemplateOperation.updateComponentInstanceRequirement(component.getUniqueId(),
2108                             entry.getKey().getUniqueId(), requirement);
2109                         if (storageOperationStatus != StorageOperationStatus.OK) {
2110                             return storageOperationStatus;
2111                         }
2112                     }
2113                 }
2114             }
2115         }
2116         return storageOperationStatus;
2117     }
2118
2119     private void updateInstancesCapAndReqOnComponentFromDB(Component component) {
2120         ComponentParametersView componentParametersView = new ComponentParametersView(true);
2121         componentParametersView.setIgnoreCapabilities(false);
2122         componentParametersView.setIgnoreRequirements(false);
2123         componentParametersView.setIgnoreCapabiltyProperties(false);
2124         componentParametersView.setIgnoreComponentInstances(false);
2125         Either<Component, StorageOperationStatus> componentEither = getToscaElement(component.getUniqueId(), componentParametersView);
2126         if (componentEither.isRight()) {
2127             throw new StorageException(StorageOperationStatus.NOT_FOUND);
2128         }
2129         Component updatedComponent = componentEither.left().value();
2130         component.setCapabilities(updatedComponent.getCapabilities());
2131         component.setRequirements(updatedComponent.getRequirements());
2132         component.setComponentInstancesRelations(updatedComponent.getComponentInstancesRelations());
2133         component.setComponentInstances(updatedComponent.getComponentInstances());
2134     }
2135
2136     private Either<List<Service>, StorageOperationStatus> getLatestVersionNonCheckoutServicesMetadataOnly(Map<GraphPropertyEnum, Object> hasProps,
2137                                                                                                           Map<GraphPropertyEnum, Object> hasNotProps,
2138                                                                                                           String modelName) {
2139         List<Service> services = new ArrayList<>();
2140         List<LifecycleStateEnum> states = new ArrayList<>();
2141         // include props
2142         hasProps.put(GraphPropertyEnum.COMPONENT_TYPE, ComponentTypeEnum.SERVICE.name());
2143         hasProps.put(GraphPropertyEnum.IS_HIGHEST_VERSION, true);
2144         if (modelName != null) {
2145             hasProps.put(GraphPropertyEnum.MODEL, modelName);
2146         }
2147         // exclude props
2148         states.add(LifecycleStateEnum.NOT_CERTIFIED_CHECKOUT);
2149         hasNotProps.put(GraphPropertyEnum.STATE, states);
2150         hasNotProps.put(GraphPropertyEnum.IS_DELETED, true);
2151         hasNotProps.put(GraphPropertyEnum.IS_ARCHIVED, true);
2152         return fetchServicesByCriteria(services, hasProps, hasNotProps, modelName);
2153     }
2154
2155     private Either<List<Component>, StorageOperationStatus> getLatestVersionNotAbstractToscaElementsMetadataOnly(final boolean isAbstract,
2156                                                                                                                  final ComponentTypeEnum componentTypeEnum,
2157                                                                                                                  final String internalComponentType,
2158                                                                                                                  final VertexTypeEnum vertexType,
2159                                                                                                                  final String modelName,
2160                                                                                                                  final boolean includeNormativeExtensionModels) {
2161         List<Service> services = null;
2162         Map<GraphPropertyEnum, Object> hasProps = new EnumMap<>(GraphPropertyEnum.class);
2163         Map<GraphPropertyEnum, Object> hasNotProps = new EnumMap<>(GraphPropertyEnum.class);
2164         fillPropsMap(hasProps, hasNotProps, internalComponentType, componentTypeEnum, isAbstract, vertexType, modelName);
2165         Either<List<GraphVertex>, JanusGraphOperationStatus> getRes = janusGraphDao
2166             .getByCriteria(vertexType, hasProps, hasNotProps, JsonParseFlagEnum.ParseMetadata, modelName, includeNormativeExtensionModels);
2167         if (getRes.isRight() && !JanusGraphOperationStatus.NOT_FOUND.equals(getRes.right().value())) {
2168             return Either.right(DaoStatusConverter.convertJanusGraphStatusToStorageStatus(getRes.right().value()));
2169         }
2170         // region -> Fetch non checked-out services
2171         if (internalComponentType != null && internalComponentType.toLowerCase().trim().equals(SERVICE) && VertexTypeEnum.NODE_TYPE == vertexType) {
2172             Either<List<Service>, StorageOperationStatus> result = getLatestVersionNonCheckoutServicesMetadataOnly(
2173                 new EnumMap<>(GraphPropertyEnum.class), new EnumMap<>(GraphPropertyEnum.class), modelName);
2174             if (result.isRight()) {
2175                 log.debug("Failed to fetch services for");
2176                 return Either.right(result.right().value());
2177             }
2178             services = result.left().value();
2179             if (log.isTraceEnabled() && isEmpty(services)) {
2180                 log.trace("No relevant services available");
2181             }
2182         }
2183         // endregion
2184         List<Component> nonAbstractLatestComponents = new ArrayList<>();
2185         ComponentParametersView params = new ComponentParametersView(true);
2186         params.setIgnoreAllVersions(false);
2187         if (getRes.isLeft()) {
2188             for (GraphVertex vertexComponent : getRes.left().value()) {
2189                 Either<ToscaElement, StorageOperationStatus> componentRes = topologyTemplateOperation
2190                     .getLightComponent(vertexComponent, componentTypeEnum, params);
2191                 if (componentRes.isRight()) {
2192                     log.debug("Failed to fetch light element for {} error {}", vertexComponent.getUniqueId(), componentRes.right().value());
2193                     return Either.right(componentRes.right().value());
2194                 } else {
2195                     Component component = ModelConverter.convertFromToscaElement(componentRes.left().value());
2196                     nonAbstractLatestComponents.add(component);
2197                 }
2198             }
2199         }
2200         if (CollectionUtils.isNotEmpty(services)) {
2201             nonAbstractLatestComponents.addAll(services);
2202         }
2203         return Either.left(nonAbstractLatestComponents);
2204     }
2205
2206     public Either<ComponentMetadataData, StorageOperationStatus> getLatestComponentMetadataByUuid(String componentUuid, JsonParseFlagEnum parseFlag,
2207                                                                                                   Boolean isHighest) {
2208         Either<ComponentMetadataData, StorageOperationStatus> result;
2209         Map<GraphPropertyEnum, Object> hasProperties = new EnumMap<>(GraphPropertyEnum.class);
2210         hasProperties.put(GraphPropertyEnum.UUID, componentUuid);
2211         if (isHighest != null) {
2212             hasProperties.put(GraphPropertyEnum.IS_HIGHEST_VERSION, isHighest);
2213         }
2214         Map<GraphPropertyEnum, Object> propertiesNotToMatch = new EnumMap<>(GraphPropertyEnum.class);
2215         propertiesNotToMatch.put(GraphPropertyEnum.IS_DELETED, true);
2216         propertiesNotToMatch.put(GraphPropertyEnum.IS_ARCHIVED, true); //US382674, US382683
2217         Either<List<GraphVertex>, JanusGraphOperationStatus> getRes = janusGraphDao
2218             .getByCriteria(null, hasProperties, propertiesNotToMatch, parseFlag);
2219         if (getRes.isRight()) {
2220             result = Either.right(DaoStatusConverter.convertJanusGraphStatusToStorageStatus(getRes.right().value()));
2221         } else {
2222             List<ComponentMetadataData> latestVersionList = getRes.left().value().stream().map(ModelConverter::convertToComponentMetadata)
2223                 .collect(Collectors.toList());
2224             ComponentMetadataData latestVersion = latestVersionList.size() == 1 ? latestVersionList.get(0) : latestVersionList.stream().max(
2225                 (c1, c2) -> Double.compare(Double.parseDouble(c1.getMetadataDataDefinition().getVersion()),
2226                     Double.parseDouble(c2.getMetadataDataDefinition().getVersion()))).get();
2227             result = Either.left(latestVersion);
2228         }
2229         return result;
2230     }
2231
2232     public Either<ComponentMetadataData, StorageOperationStatus> getComponentMetadata(String componentId) {
2233         Either<ComponentMetadataData, StorageOperationStatus> result;
2234         Either<GraphVertex, JanusGraphOperationStatus> getRes = janusGraphDao.getVertexById(componentId, JsonParseFlagEnum.ParseMetadata);
2235         if (getRes.isRight()) {
2236             result = Either.right(DaoStatusConverter.convertJanusGraphStatusToStorageStatus(getRes.right().value()));
2237         } else {
2238             ComponentMetadataData componentMetadata = ModelConverter.convertToComponentMetadata(getRes.left().value());
2239             result = Either.left(componentMetadata);
2240         }
2241         return result;
2242     }
2243
2244     public Either<List<Component>, StorageOperationStatus> getLatestVersionNotAbstractComponents(boolean isAbstract,
2245                                                                                                  ComponentTypeEnum componentTypeEnum,
2246                                                                                                  String internalComponentType,
2247                                                                                                  List<String> componentUids) {
2248         List<Component> components = new ArrayList<>();
2249         if (componentUids == null) {
2250             Either<List<String>, StorageOperationStatus> componentUidsRes = getComponentUids(isAbstract, componentTypeEnum, internalComponentType);
2251             if (componentUidsRes.isRight()) {
2252                 return Either.right(componentUidsRes.right().value());
2253             }
2254             componentUids = componentUidsRes.left().value();
2255         }
2256         if (!isEmpty(componentUids)) {
2257             for (String componentUid : componentUids) {
2258                 ComponentParametersView componentParametersView = buildComponentViewForNotAbstract();
2259                 if ("vl".equalsIgnoreCase(internalComponentType)) {
2260                     componentParametersView.setIgnoreCapabilities(false);
2261                     componentParametersView.setIgnoreRequirements(false);
2262                 }
2263                 Either<ToscaElement, StorageOperationStatus> getToscaElementRes = nodeTemplateOperation.getToscaElementOperation(componentTypeEnum)
2264                     .getLightComponent(componentUid, componentTypeEnum, componentParametersView);
2265                 if (getToscaElementRes.isRight()) {
2266                     log.debug("Failed to fetch resource for error is {}", getToscaElementRes.right().value());
2267                     return Either.right(getToscaElementRes.right().value());
2268                 }
2269                 Component component = ModelConverter.convertFromToscaElement(getToscaElementRes.left().value());
2270                 nullifySomeComponentProperties(component);
2271                 components.add(component);
2272             }
2273         }
2274         return Either.left(components);
2275     }
2276
2277     public void nullifySomeComponentProperties(Component component) {
2278         component.setContactId(null);
2279         component.setCreationDate(null);
2280         component.setCreatorUserId(null);
2281         component.setCreatorFullName(null);
2282         component.setLastUpdateDate(null);
2283         component.setLastUpdaterUserId(null);
2284         component.setLastUpdaterFullName(null);
2285         component.setNormalizedName(null);
2286     }
2287
2288     private Either<List<String>, StorageOperationStatus> getComponentUids(boolean isAbstract, ComponentTypeEnum componentTypeEnum,
2289                                                                           String internalComponentType) {
2290         Either<List<Component>, StorageOperationStatus> getToscaElementsRes = getLatestVersionNotAbstractMetadataOnly(isAbstract, componentTypeEnum,
2291             internalComponentType, null, false);
2292         if (getToscaElementsRes.isRight()) {
2293             return Either.right(getToscaElementsRes.right().value());
2294         }
2295         List<Component> collection = getToscaElementsRes.left().value();
2296         List<String> componentUids;
2297         if (collection == null) {
2298             componentUids = new ArrayList<>();
2299         } else {
2300             componentUids = collection.stream().map(Component::getUniqueId).collect(Collectors.toList());
2301         }
2302         return Either.left(componentUids);
2303     }
2304
2305     private ComponentParametersView buildComponentViewForNotAbstract() {
2306         ComponentParametersView componentParametersView = new ComponentParametersView();
2307         componentParametersView.disableAll();
2308         componentParametersView.setIgnoreCategories(false);
2309         componentParametersView.setIgnoreAllVersions(false);
2310         return componentParametersView;
2311     }
2312
2313     public Either<Boolean, StorageOperationStatus> validateComponentNameExists(String name, ResourceTypeEnum resourceType,
2314                                                                                ComponentTypeEnum componentType) {
2315         Either<Boolean, StorageOperationStatus> result = validateComponentNameUniqueness(name, resourceType, componentType);
2316         if (result.isLeft()) {
2317             result = Either.left(!result.left().value());
2318         }
2319         return result;
2320     }
2321
2322     public Either<Boolean, StorageOperationStatus> validateComponentNameUniqueness(String name, ResourceTypeEnum resourceType,
2323                                                                                    ComponentTypeEnum componentType) {
2324         String normalizedName = ValidationUtils.normaliseComponentName(name);
2325         Either<List<GraphVertex>, JanusGraphOperationStatus> vertexEither = janusGraphDao
2326             .getByCriteria(getVertexTypeEnum(resourceType), propertiesToMatch(normalizedName, componentType), JsonParseFlagEnum.NoParse);
2327         if (vertexEither.isRight() && vertexEither.right().value() != JanusGraphOperationStatus.NOT_FOUND) {
2328             log.debug("failed to get vertex from graph with property normalizedName: {}", normalizedName);
2329             return Either.right(DaoStatusConverter.convertJanusGraphStatusToStorageStatus(vertexEither.right().value()));
2330         }
2331         return Either.left(CollectionUtils.isEmpty(vertexEither.isLeft() ? vertexEither.left().value() : null));
2332     }
2333
2334     public Either<Boolean, StorageOperationStatus> validateComponentNameAndModelExists(final String resourceName, final String model,
2335                                                                                        final ResourceTypeEnum resourceType,
2336                                                                                        final ComponentTypeEnum componentType) {
2337         Either<Boolean, StorageOperationStatus> result = validateComponentNameAndModelUniqueness(resourceName, model, resourceType, componentType);
2338         if (result.isLeft()) {
2339             result = Either.left(!result.left().value());
2340         }
2341         return result;
2342     }
2343
2344     private Either<Boolean, StorageOperationStatus> validateComponentNameAndModelUniqueness(final String resourceName, final String modelName,
2345                                                                                             final ResourceTypeEnum resourceType,
2346                                                                                             final ComponentTypeEnum componentType) {
2347         final String normalizedName = ValidationUtils.normaliseComponentName(resourceName);
2348         final Either<List<GraphVertex>, JanusGraphOperationStatus> vertexEither = janusGraphDao
2349             .getByCriteria(getVertexTypeEnum(resourceType), propertiesToMatch(normalizedName, componentType), null, null, JsonParseFlagEnum.NoParse,
2350                 modelName);
2351         if (vertexEither.isRight() && vertexEither.right().value() != JanusGraphOperationStatus.NOT_FOUND) {
2352             log.debug("failed to get vertex from graph with property normalizedName: {} and model: {}", normalizedName, modelName);
2353             return Either.right(DaoStatusConverter.convertJanusGraphStatusToStorageStatus(vertexEither.right().value()));
2354         }
2355         return Either.left(CollectionUtils.isEmpty(vertexEither.isLeft() ? vertexEither.left().value().stream()
2356             .collect(Collectors.toList()) : null));
2357     }
2358
2359     private VertexTypeEnum getVertexTypeEnum(final ResourceTypeEnum resourceType) {
2360         return ModelConverter.isAtomicComponent(resourceType) ? VertexTypeEnum.NODE_TYPE : VertexTypeEnum.TOPOLOGY_TEMPLATE;
2361     }
2362
2363     private Map<GraphPropertyEnum, Object> propertiesToMatch(final String normalizedName, final ComponentTypeEnum componentType) {
2364         final Map<GraphPropertyEnum, Object> properties = new EnumMap<>(GraphPropertyEnum.class);
2365         properties.put(GraphPropertyEnum.NORMALIZED_NAME, normalizedName);
2366         properties.put(GraphPropertyEnum.COMPONENT_TYPE, componentType.name());
2367         return properties;
2368     }
2369
2370     private void fillNodeTypePropsMap(final Map<GraphPropertyEnum, Object> hasProps, final Map<GraphPropertyEnum, Object> hasNotProps,
2371                                       final String internalComponentType, String modelName) {
2372         final Configuration configuration = ConfigurationManager.getConfigurationManager().getConfiguration();
2373         final List<String> allowedTypes;
2374         if (ComponentTypeEnum.SERVICE.getValue().equalsIgnoreCase(internalComponentType)) {
2375             allowedTypes = containerInstanceTypesData.getServiceAllowedList(modelName);
2376         } else {
2377             final ResourceTypeEnum resourceType = ResourceTypeEnum.getTypeIgnoreCase(internalComponentType);
2378             allowedTypes = containerInstanceTypesData.getComponentAllowedList(ComponentTypeEnum.RESOURCE, resourceType);
2379         }
2380         final List<String> allResourceTypes = configuration.getResourceTypes();
2381         if (allowedTypes == null) {
2382             hasNotProps.put(GraphPropertyEnum.RESOURCE_TYPE, allResourceTypes);
2383             return;
2384         }
2385         if (ResourceTypeEnum.VL.getValue().equalsIgnoreCase(internalComponentType)) {
2386             hasProps.put(GraphPropertyEnum.RESOURCE_TYPE, allowedTypes);
2387         } else {
2388             final List<String> notAllowedTypes = allResourceTypes.stream().filter(s -> !allowedTypes.contains(s)).collect(Collectors.toList());
2389             hasNotProps.put(GraphPropertyEnum.RESOURCE_TYPE, notAllowedTypes);
2390         }
2391     }
2392
2393     private void fillTopologyTemplatePropsMap(Map<GraphPropertyEnum, Object> hasProps, Map<GraphPropertyEnum, Object> hasNotProps,
2394                                               ComponentTypeEnum componentTypeEnum) {
2395         switch (componentTypeEnum) {
2396             case RESOURCE:
2397                 hasProps.put(GraphPropertyEnum.COMPONENT_TYPE, ComponentTypeEnum.RESOURCE.name());
2398                 break;
2399             case SERVICE:
2400                 hasProps.put(GraphPropertyEnum.COMPONENT_TYPE, ComponentTypeEnum.SERVICE.name());
2401                 break;
2402             default:
2403                 break;
2404         }
2405         hasNotProps.put(GraphPropertyEnum.RESOURCE_TYPE, ResourceTypeEnum.CVFC.name());
2406     }
2407
2408     private void fillPropsMap(Map<GraphPropertyEnum, Object> hasProps, Map<GraphPropertyEnum, Object> hasNotProps, String internalComponentType,
2409                               ComponentTypeEnum componentTypeEnum, boolean isAbstract, VertexTypeEnum internalVertexType, String modelName) {
2410         hasNotProps.put(GraphPropertyEnum.STATE, LifecycleStateEnum.NOT_CERTIFIED_CHECKOUT.name());
2411         hasNotProps.put(GraphPropertyEnum.IS_DELETED, true);
2412         hasNotProps.put(GraphPropertyEnum.IS_ARCHIVED, true);
2413         hasProps.put(GraphPropertyEnum.IS_HIGHEST_VERSION, true);
2414
2415         if (VertexTypeEnum.NODE_TYPE == internalVertexType) {
2416             hasProps.put(GraphPropertyEnum.IS_ABSTRACT, isAbstract);
2417             if (internalComponentType != null) {
2418                 fillNodeTypePropsMap(hasProps, hasNotProps, internalComponentType, modelName);
2419             }
2420         } else {
2421             fillTopologyTemplatePropsMap(hasProps, hasNotProps, componentTypeEnum);
2422         }
2423     }
2424
2425     private List<VertexTypeEnum> getInternalVertexTypes(ComponentTypeEnum componentTypeEnum, String internalComponentType) {
2426         List<VertexTypeEnum> internalVertexTypes = new ArrayList<>();
2427         if (ComponentTypeEnum.RESOURCE == componentTypeEnum) {
2428             internalVertexTypes.add(VertexTypeEnum.NODE_TYPE);
2429         }
2430         if (ComponentTypeEnum.SERVICE == componentTypeEnum || SERVICE.equalsIgnoreCase(internalComponentType) || VF.equalsIgnoreCase(
2431             internalComponentType)) {
2432             internalVertexTypes.add(VertexTypeEnum.TOPOLOGY_TEMPLATE);
2433         }
2434         return internalVertexTypes;
2435     }
2436
2437     public Either<List<Component>, StorageOperationStatus> getLatestVersionNotAbstractMetadataOnly(boolean isAbstract,
2438                                                                                                    final ComponentTypeEnum componentTypeEnum,
2439                                                                                                    final String internalComponentType,
2440                                                                                                    final String modelName,
2441                                                                                                    final boolean includeNormativeExtensionModels) {
2442         List<VertexTypeEnum> internalVertexTypes = getInternalVertexTypes(componentTypeEnum, internalComponentType);
2443         List<Component> result = new ArrayList<>();
2444         for (VertexTypeEnum vertexType : internalVertexTypes) {
2445             Either<List<Component>, StorageOperationStatus> listByVertexType = getLatestVersionNotAbstractToscaElementsMetadataOnly(isAbstract,
2446                 componentTypeEnum, internalComponentType, vertexType, modelName, includeNormativeExtensionModels);
2447             if (listByVertexType.isRight()) {
2448                 return listByVertexType;
2449             }
2450             result.addAll(listByVertexType.left().value());
2451         }
2452         return Either.left(result);
2453     }
2454
2455     private Either<List<Component>, StorageOperationStatus> getLatestComponentListByUuid(String componentUuid,
2456                                                                                          Map<GraphPropertyEnum, Object> additionalPropertiesToMatch) {
2457         Map<GraphPropertyEnum, Object> propertiesToMatch = new EnumMap<>(GraphPropertyEnum.class);
2458         if (additionalPropertiesToMatch != null) {
2459             propertiesToMatch.putAll(additionalPropertiesToMatch);
2460         }
2461         propertiesToMatch.put(GraphPropertyEnum.IS_HIGHEST_VERSION, true);
2462         return getComponentListByUuid(componentUuid, propertiesToMatch);
2463     }
2464
2465     public Either<Component, StorageOperationStatus> getComponentByUuidAndVersion(String componentUuid, String version) {
2466         Map<GraphPropertyEnum, Object> propertiesToMatch = new EnumMap<>(GraphPropertyEnum.class);
2467         propertiesToMatch.put(GraphPropertyEnum.UUID, componentUuid);
2468         propertiesToMatch.put(GraphPropertyEnum.VERSION, version);
2469         Map<GraphPropertyEnum, Object> propertiesNotToMatch = new EnumMap<>(GraphPropertyEnum.class);
2470         propertiesNotToMatch.put(GraphPropertyEnum.IS_DELETED, true);
2471         Either<List<GraphVertex>, JanusGraphOperationStatus> vertexEither = janusGraphDao
2472             .getByCriteria(null, propertiesToMatch, propertiesNotToMatch, JsonParseFlagEnum.ParseAll);
2473         if (vertexEither.isRight()) {
2474             return Either.right(DaoStatusConverter.convertJanusGraphStatusToStorageStatus(vertexEither.right().value()));
2475         }
2476         List<GraphVertex> vertexList = vertexEither.isLeft() ? vertexEither.left().value() : null;
2477         if (vertexList == null || vertexList.isEmpty() || vertexList.size() > 1) {
2478             return Either.right(StorageOperationStatus.NOT_FOUND);
2479         }
2480         return getToscaElementByOperation(vertexList.get(0));
2481     }
2482
2483     public Either<List<Component>, StorageOperationStatus> getComponentListByUuid(String componentUuid,
2484                                                                                   Map<GraphPropertyEnum, Object> additionalPropertiesToMatch) {
2485         Map<GraphPropertyEnum, Object> propertiesToMatch = new EnumMap<>(GraphPropertyEnum.class);
2486         if (additionalPropertiesToMatch != null) {
2487             propertiesToMatch.putAll(additionalPropertiesToMatch);
2488         }
2489         propertiesToMatch.put(GraphPropertyEnum.UUID, componentUuid);
2490         Map<GraphPropertyEnum, Object> propertiesNotToMatch = new EnumMap<>(GraphPropertyEnum.class);
2491         propertiesNotToMatch.put(GraphPropertyEnum.IS_DELETED, true);
2492         propertiesNotToMatch.put(GraphPropertyEnum.IS_ARCHIVED, true); //US382674, US382683
2493         Either<List<GraphVertex>, JanusGraphOperationStatus> vertexEither = janusGraphDao
2494             .getByCriteria(null, propertiesToMatch, propertiesNotToMatch, JsonParseFlagEnum.ParseAll);
2495         if (vertexEither.isRight()) {
2496             log.debug("Couldn't fetch metadata for component with uuid {}, error: {}", componentUuid, vertexEither.right().value());
2497             return Either.right(DaoStatusConverter.convertJanusGraphStatusToStorageStatus(vertexEither.right().value()));
2498         }
2499         List<GraphVertex> vertexList = vertexEither.isLeft() ? vertexEither.left().value() : null;
2500         if (vertexList == null || vertexList.isEmpty()) {
2501             log.debug("Component with uuid {} was not found", componentUuid);
2502             return Either.right(StorageOperationStatus.NOT_FOUND);
2503         }
2504         ArrayList<Component> latestComponents = new ArrayList<>();
2505         for (GraphVertex vertex : vertexList) {
2506             Either<Component, StorageOperationStatus> toscaElementByOperation = getToscaElementByOperation(vertex);
2507             if (toscaElementByOperation.isRight()) {
2508                 log.debug("Could not fetch the following Component by UUID {}", vertex.getUniqueId());
2509                 return Either.right(toscaElementByOperation.right().value());
2510             }
2511             latestComponents.add(toscaElementByOperation.left().value());
2512         }
2513         if (latestComponents.size() > 1) {
2514             for (Component component : latestComponents) {
2515                 if (Boolean.TRUE.equals(component.isHighestVersion())) {
2516                     LinkedList<Component> highestComponent = new LinkedList<>();
2517                     highestComponent.add(component);
2518                     return Either.left(highestComponent);
2519                 }
2520             }
2521         }
2522         return Either.left(latestComponents);
2523     }
2524
2525     public Either<Component, StorageOperationStatus> getLatestServiceByUuid(String serviceUuid) {
2526         Map<GraphPropertyEnum, Object> propertiesToMatch = new EnumMap<>(GraphPropertyEnum.class);
2527         propertiesToMatch.put(GraphPropertyEnum.COMPONENT_TYPE, ComponentTypeEnum.SERVICE.name());
2528         return getLatestComponentByUuid(serviceUuid, propertiesToMatch);
2529     }
2530
2531     public Either<Component, StorageOperationStatus> getLatestComponentByUuid(String componentUuid) {
2532         return getLatestComponentByUuid(componentUuid, null);
2533     }
2534
2535     public Either<Component, StorageOperationStatus> getLatestComponentByUuid(String componentUuid,
2536                                                                               Map<GraphPropertyEnum, Object> propertiesToMatch) {
2537         Either<List<Component>, StorageOperationStatus> latestVersionListEither = getLatestComponentListByUuid(componentUuid, propertiesToMatch);
2538         if (latestVersionListEither.isRight()) {
2539             return Either.right(latestVersionListEither.right().value());
2540         }
2541         List<Component> latestVersionList = latestVersionListEither.left().value();
2542         if (latestVersionList.isEmpty()) {
2543             return Either.right(StorageOperationStatus.NOT_FOUND);
2544         }
2545         Component component = latestVersionList.size() == 1 ? latestVersionList.get(0)
2546             : latestVersionList.stream().max((c1, c2) -> Double.compare(Double.parseDouble(c1.getVersion()), Double.parseDouble(c2.getVersion())))
2547                 .get();
2548         return Either.left(component);
2549     }
2550
2551     public Either<List<Resource>, StorageOperationStatus> getAllCertifiedResources(boolean isAbstract, Boolean isHighest) {
2552         List<Resource> resources = new ArrayList<>();
2553         Map<GraphPropertyEnum, Object> propertiesToMatch = new EnumMap<>(GraphPropertyEnum.class);
2554         Map<GraphPropertyEnum, Object> propertiesNotToMatch = new EnumMap<>(GraphPropertyEnum.class);
2555         propertiesToMatch.put(GraphPropertyEnum.IS_ABSTRACT, isAbstract);
2556         if (isHighest != null) {
2557             propertiesToMatch.put(GraphPropertyEnum.IS_HIGHEST_VERSION, isHighest);
2558         }
2559         propertiesToMatch.put(GraphPropertyEnum.STATE, LifecycleStateEnum.CERTIFIED.name());
2560         propertiesToMatch.put(GraphPropertyEnum.COMPONENT_TYPE, ComponentTypeEnum.RESOURCE.name());
2561         propertiesNotToMatch.put(GraphPropertyEnum.IS_DELETED, true);
2562         Either<List<GraphVertex>, JanusGraphOperationStatus> getResourcesRes = janusGraphDao
2563             .getByCriteria(null, propertiesToMatch, propertiesNotToMatch, JsonParseFlagEnum.ParseAll);
2564         if (getResourcesRes.isRight()) {
2565             log.debug("Failed to fetch all certified resources. Status is {}", getResourcesRes.right().value());
2566             return Either.right(DaoStatusConverter.convertJanusGraphStatusToStorageStatus(getResourcesRes.right().value()));
2567         }
2568         List<GraphVertex> resourceVerticies = getResourcesRes.left().value();
2569         for (GraphVertex resourceV : resourceVerticies) {
2570             Either<Resource, StorageOperationStatus> getResourceRes = getToscaElement(resourceV);
2571             if (getResourceRes.isRight()) {
2572                 return Either.right(getResourceRes.right().value());
2573             }
2574             resources.add(getResourceRes.left().value());
2575         }
2576         return Either.left(resources);
2577     }
2578
2579     public <T extends Component> Either<T, StorageOperationStatus> getLatestByNameAndVersion(String name, String version,
2580                                                                                              JsonParseFlagEnum parseFlag, String model) {
2581         Either<T, StorageOperationStatus> result;
2582         Map<GraphPropertyEnum, Object> hasProperties = new EnumMap<>(GraphPropertyEnum.class);
2583         Map<GraphPropertyEnum, Object> hasNotProperties = new EnumMap<>(GraphPropertyEnum.class);
2584         hasProperties.put(GraphPropertyEnum.NAME, name);
2585         hasProperties.put(GraphPropertyEnum.VERSION, version);
2586         hasProperties.put(GraphPropertyEnum.IS_HIGHEST_VERSION, true);
2587         hasNotProperties.put(GraphPropertyEnum.IS_DELETED, true);
2588         Either<List<GraphVertex>, JanusGraphOperationStatus> getResourceRes = janusGraphDao
2589             .getByCriteria(null, hasProperties, hasNotProperties, parseFlag, model);
2590         if (getResourceRes.isRight()) {
2591             JanusGraphOperationStatus status = getResourceRes.right().value();
2592             log.debug("failed to find resource with name {}, version {}. Status is {} ", name, version, status);
2593             result = Either.right(DaoStatusConverter.convertJanusGraphStatusToStorageStatus(status));
2594             return result;
2595         }
2596         return getToscaElementByOperation(getResourceRes.left().value().get(0));
2597     }
2598
2599     public Either<Resource, StorageOperationStatus> getLatestComponentByCsarOrName(ComponentTypeEnum componentType, String csarUUID,
2600                                                                                    String systemName) {
2601         return getLatestComponentByCsarOrName(componentType, csarUUID, systemName, JsonParseFlagEnum.ParseAll);
2602     }
2603
2604     public Either<Resource, StorageOperationStatus> getLatestComponentByCsarOrName(ComponentTypeEnum componentType, String csarUUID,
2605                                                                                    String systemName, JsonParseFlagEnum parseFlag) {
2606         Map<GraphPropertyEnum, Object> props = new EnumMap<>(GraphPropertyEnum.class);
2607         Map<GraphPropertyEnum, Object> propsHasNot = new EnumMap<>(GraphPropertyEnum.class);
2608         props.put(GraphPropertyEnum.CSAR_UUID, csarUUID);
2609         props.put(GraphPropertyEnum.IS_HIGHEST_VERSION, true);
2610         if (componentType != null) {
2611             props.put(GraphPropertyEnum.COMPONENT_TYPE, componentType.name());
2612         }
2613         propsHasNot.put(GraphPropertyEnum.IS_DELETED, true);
2614         GraphVertex resourceMetadataData = null;
2615         List<GraphVertex> resourceMetadataDataList = null;
2616         Either<List<GraphVertex>, JanusGraphOperationStatus> byCsar = janusGraphDao
2617             .getByCriteria(null, props, propsHasNot, JsonParseFlagEnum.ParseMetadata);
2618         if (byCsar.isRight()) {
2619             if (JanusGraphOperationStatus.NOT_FOUND == byCsar.right().value()) {
2620                 // Fix Defect DE256036
2621                 if (StringUtils.isEmpty(systemName)) {
2622                     return Either.right(DaoStatusConverter.convertJanusGraphStatusToStorageStatus(JanusGraphOperationStatus.NOT_FOUND));
2623                 }
2624                 props.clear();
2625                 props.put(GraphPropertyEnum.IS_HIGHEST_VERSION, true);
2626                 props.put(GraphPropertyEnum.SYSTEM_NAME, systemName);
2627                 Either<List<GraphVertex>, JanusGraphOperationStatus> bySystemname = janusGraphDao
2628                     .getByCriteria(null, props, JsonParseFlagEnum.ParseMetadata);
2629                 if (bySystemname.isRight()) {
2630                     log.debug("getLatestResourceByCsarOrName - Failed to find by system name {}  error {} ", systemName,
2631                         bySystemname.right().value());
2632                     return Either.right(DaoStatusConverter.convertJanusGraphStatusToStorageStatus(bySystemname.right().value()));
2633                 }
2634                 if (bySystemname.left().value().size() > 2) {
2635                     log.debug(
2636                         "getLatestResourceByCsarOrName - getByCriteria(by system name) must return only 2 latest version, but was returned - {}",
2637                         bySystemname.left().value().size());
2638                     return Either.right(StorageOperationStatus.GENERAL_ERROR);
2639                 }
2640                 resourceMetadataDataList = bySystemname.left().value();
2641                 if (resourceMetadataDataList.size() == 1) {
2642                     resourceMetadataData = resourceMetadataDataList.get(0);
2643                 } else {
2644                     for (GraphVertex curResource : resourceMetadataDataList) {
2645                         if (!((String) curResource.getJsonMetadataField(JsonPresentationFields.LIFECYCLE_STATE)).equals("CERTIFIED")) {
2646                             resourceMetadataData = curResource;
2647                             break;
2648                         }
2649                     }
2650                 }
2651                 if (resourceMetadataData == null) {
2652                     log.debug("getLatestResourceByCsarOrName - getByCriteria(by system name) returned 2 latest CERTIFIED versions");
2653                     return Either.right(StorageOperationStatus.GENERAL_ERROR);
2654                 }
2655                 final Object csarUuid = resourceMetadataData.getJsonMetadataField(JsonPresentationFields.CSAR_UUID);
2656                 if (csarUuid != null && !csarUuid.equals(csarUUID)) {
2657                     log.debug("getLatestResourceByCsarOrName - same system name {} but different csarUUID. exist {} and new {} ", systemName,
2658                         csarUuid, csarUUID);
2659                     // correct error will be returned from create flow. with all
2660
2661                     // correct audit records!!!!!
2662                     return Either.right(StorageOperationStatus.NOT_FOUND);
2663                 }
2664                 return getToscaElement(resourceMetadataData.getUniqueId());
2665             }
2666         } else {
2667             resourceMetadataDataList = byCsar.left().value();
2668             if (resourceMetadataDataList.size() > 2) {
2669                 log.debug("getLatestResourceByCsarOrName - getByCriteria(by csar) must return only 2 latest version, but was returned - {}",
2670                     byCsar.left().value().size());
2671                 return Either.right(StorageOperationStatus.GENERAL_ERROR);
2672             }
2673             if (resourceMetadataDataList.size() == 1) {
2674                 resourceMetadataData = resourceMetadataDataList.get(0);
2675             } else {
2676                 for (GraphVertex curResource : resourceMetadataDataList) {
2677                     if (!((String) curResource.getJsonMetadataField(JsonPresentationFields.LIFECYCLE_STATE)).equals("CERTIFIED")) {
2678                         resourceMetadataData = curResource;
2679                         break;
2680                     }
2681                 }
2682             }
2683             if (resourceMetadataData == null) {
2684                 log.debug("getLatestResourceByCsarOrName - getByCriteria(by csar) returned 2 latest CERTIFIED versions");
2685                 return Either.right(StorageOperationStatus.GENERAL_ERROR);
2686             }
2687             return getToscaElement((String) resourceMetadataData.getJsonMetadataField(JsonPresentationFields.UNIQUE_ID), parseFlag);
2688         }
2689         return null;
2690     }
2691
2692     public Either<Boolean, StorageOperationStatus> validateToscaResourceNameExtends(String templateNameCurrent, String templateNameExtends,
2693                                                                                     String model) {
2694         String currentTemplateNameChecked = templateNameExtends;
2695         while (currentTemplateNameChecked != null && !currentTemplateNameChecked.equalsIgnoreCase(templateNameCurrent)) {
2696             Either<Resource, StorageOperationStatus> latestByToscaResourceName = getLatestByToscaResourceName(currentTemplateNameChecked, model);
2697             if (latestByToscaResourceName.isRight()) {
2698                 return latestByToscaResourceName.right().value() == StorageOperationStatus.NOT_FOUND ? Either.left(false)
2699                     : Either.right(latestByToscaResourceName.right().value());
2700             }
2701             Resource value = latestByToscaResourceName.left().value();
2702             if (value.getDerivedFrom() != null) {
2703                 currentTemplateNameChecked = value.getDerivedFrom().get(0);
2704             } else {
2705                 currentTemplateNameChecked = null;
2706             }
2707         }
2708         return (currentTemplateNameChecked != null && currentTemplateNameChecked.equalsIgnoreCase(templateNameCurrent)) ? Either.left(true)
2709             : Either.left(false);
2710     }
2711
2712     public Either<List<Component>, StorageOperationStatus> fetchMetaDataByResourceType(String resourceType, ComponentParametersView filterBy) {
2713         Map<GraphPropertyEnum, Object> props = new EnumMap<>(GraphPropertyEnum.class);
2714         props.put(GraphPropertyEnum.RESOURCE_TYPE, resourceType);
2715         props.put(GraphPropertyEnum.IS_HIGHEST_VERSION, true);
2716         Map<GraphPropertyEnum, Object> propsHasNotToMatch = new EnumMap<>(GraphPropertyEnum.class);
2717         propsHasNotToMatch.put(GraphPropertyEnum.IS_DELETED, true);
2718         Either<List<GraphVertex>, JanusGraphOperationStatus> resourcesByTypeEither = janusGraphDao
2719             .getByCriteria(null, props, propsHasNotToMatch, JsonParseFlagEnum.ParseMetadata);
2720         if (resourcesByTypeEither.isRight()) {
2721             return Either.right(DaoStatusConverter.convertJanusGraphStatusToStorageStatus(resourcesByTypeEither.right().value()));
2722         }
2723         List<GraphVertex> vertexList = resourcesByTypeEither.left().value();
2724         List<Component> components = new ArrayList<>();
2725         for (GraphVertex vertex : vertexList) {
2726             components.add(getToscaElementByOperation(vertex, filterBy).left().value());
2727         }
2728         return Either.left(components);
2729     }
2730
2731     public void commit() {
2732         janusGraphDao.commit();
2733     }
2734
2735     public Either<Service, StorageOperationStatus> updateDistributionStatus(Service service, User user, DistributionStatusEnum distributionStatus) {
2736         Either<GraphVertex, StorageOperationStatus> updateDistributionStatus = topologyTemplateOperation
2737             .updateDistributionStatus(service.getUniqueId(), user, distributionStatus);
2738         if (updateDistributionStatus.isRight()) {
2739             return Either.right(updateDistributionStatus.right().value());
2740         }
2741         GraphVertex serviceV = updateDistributionStatus.left().value();
2742         service.setDistributionStatus(distributionStatus);
2743         service.setLastUpdateDate((Long) serviceV.getJsonMetadataField(JsonPresentationFields.LAST_UPDATE_DATE));
2744         return Either.left(service);
2745     }
2746
2747     public Either<ComponentMetadataData, StorageOperationStatus> updateComponentLastUpdateDateOnGraph(Component component) {
2748         Either<ComponentMetadataData, StorageOperationStatus> result = null;
2749         GraphVertex serviceVertex;
2750         Either<GraphVertex, JanusGraphOperationStatus> updateRes = null;
2751         Either<GraphVertex, JanusGraphOperationStatus> getRes = janusGraphDao.getVertexById(component.getUniqueId(), JsonParseFlagEnum.ParseMetadata);
2752         if (getRes.isRight()) {
2753             JanusGraphOperationStatus status = getRes.right().value();
2754             log.error("Failed to fetch component {}. status is {}", component.getUniqueId(), status);
2755             result = Either.right(DaoStatusConverter.convertJanusGraphStatusToStorageStatus(status));
2756         }
2757         if (result == null) {
2758             serviceVertex = getRes.left().value();
2759             long lastUpdateDate = System.currentTimeMillis();
2760             serviceVertex.setJsonMetadataField(JsonPresentationFields.LAST_UPDATE_DATE, lastUpdateDate);
2761             component.setLastUpdateDate(lastUpdateDate);
2762             updateRes = janusGraphDao.updateVertex(serviceVertex);
2763             if (updateRes.isRight()) {
2764                 result = Either.right(DaoStatusConverter.convertJanusGraphStatusToStorageStatus(updateRes.right().value()));
2765             }
2766         }
2767         if (result == null) {
2768             result = Either.left(ModelConverter.convertToComponentMetadata(updateRes.left().value()));
2769         }
2770         return result;
2771     }
2772
2773     public HealingJanusGraphDao getJanusGraphDao() {
2774         return janusGraphDao;
2775     }
2776
2777     public Either<List<Service>, StorageOperationStatus> getCertifiedServicesWithDistStatus(Set<DistributionStatusEnum> distStatus) {
2778         Map<GraphPropertyEnum, Object> propertiesToMatch = new EnumMap<>(GraphPropertyEnum.class);
2779         propertiesToMatch.put(GraphPropertyEnum.STATE, LifecycleStateEnum.CERTIFIED.name());
2780         return getServicesWithDistStatus(distStatus, propertiesToMatch);
2781     }
2782
2783     public Either<List<Service>, StorageOperationStatus> getServicesWithDistStatus(Set<DistributionStatusEnum> distStatus,
2784                                                                                    Map<GraphPropertyEnum, Object> additionalPropertiesToMatch) {
2785         List<Service> servicesAll = new ArrayList<>();
2786         Map<GraphPropertyEnum, Object> propertiesToMatch = new EnumMap<>(GraphPropertyEnum.class);
2787         Map<GraphPropertyEnum, Object> propertiesNotToMatch = new EnumMap<>(GraphPropertyEnum.class);
2788         if (additionalPropertiesToMatch != null && !additionalPropertiesToMatch.isEmpty()) {
2789             propertiesToMatch.putAll(additionalPropertiesToMatch);
2790         }
2791         propertiesToMatch.put(GraphPropertyEnum.COMPONENT_TYPE, ComponentTypeEnum.SERVICE.name());
2792         propertiesNotToMatch.put(GraphPropertyEnum.IS_DELETED, true);
2793         if (distStatus != null && !distStatus.isEmpty()) {
2794             for (DistributionStatusEnum state : distStatus) {
2795                 propertiesToMatch.put(GraphPropertyEnum.DISTRIBUTION_STATUS, state.name());
2796                 Either<List<Service>, StorageOperationStatus> fetchServicesByCriteria = fetchServicesByCriteria(servicesAll, propertiesToMatch,
2797                     propertiesNotToMatch, null);
2798                 if (fetchServicesByCriteria.isRight()) {
2799                     return fetchServicesByCriteria;
2800                 } else {
2801                     servicesAll = fetchServicesByCriteria.left().value();
2802                 }
2803             }
2804             return Either.left(servicesAll);
2805         } else {
2806             return fetchServicesByCriteria(servicesAll, propertiesToMatch, propertiesNotToMatch, null);
2807         }
2808     }
2809
2810     private Either<List<Service>, StorageOperationStatus> fetchServicesByCriteria(List<Service> servicesAll,
2811                                                                                   Map<GraphPropertyEnum, Object> propertiesToMatch,
2812                                                                                   Map<GraphPropertyEnum, Object> propertiesNotToMatch,
2813                                                                                   String modelName) {
2814         Either<List<GraphVertex>, JanusGraphOperationStatus> getRes = janusGraphDao
2815             .getByCriteria(VertexTypeEnum.TOPOLOGY_TEMPLATE, propertiesToMatch, propertiesNotToMatch, JsonParseFlagEnum.ParseAll, modelName);
2816         if (getRes.isRight()) {
2817             if (getRes.right().value() != JanusGraphOperationStatus.NOT_FOUND) {
2818                 CommonUtility.addRecordToLog(log, LogLevelEnum.DEBUG,
2819                     "Failed to fetch certified services by match properties {} not match properties {} . Status is {}. ", propertiesToMatch,
2820                     propertiesNotToMatch, getRes.right().value());
2821                 return Either.right(DaoStatusConverter.convertJanusGraphStatusToStorageStatus(getRes.right().value()));
2822             }
2823         } else {
2824             for (final GraphVertex vertex : getRes.left().value()) {
2825                 Either<ToscaElement, StorageOperationStatus> getServiceRes = topologyTemplateOperation
2826                     .getLightComponent(vertex, ComponentTypeEnum.SERVICE, new ComponentParametersView(true));
2827                 if (getServiceRes.isRight()) {
2828                     CommonUtility.addRecordToLog(log, LogLevelEnum.DEBUG, "Failed to fetch certified service {}. Status is {}. ",
2829                         vertex.getJsonMetadataField(JsonPresentationFields.NAME), getServiceRes.right().value());
2830                     return Either.right(getServiceRes.right().value());
2831                 } else {
2832                     servicesAll.add(ModelConverter.convertFromToscaElement(getServiceRes.left().value()));
2833                 }
2834             }
2835         }
2836         return Either.left(servicesAll);
2837     }
2838
2839     public void rollback() {
2840         janusGraphDao.rollback();
2841     }
2842
2843     public StorageOperationStatus addDeploymentArtifactsToInstance(String componentId, ComponentInstance componentInstance,
2844                                                                    Map<String, ArtifactDefinition> finalDeploymentArtifacts) {
2845         Map<String, ArtifactDataDefinition> instDeplArtifacts = finalDeploymentArtifacts.entrySet().stream()
2846             .collect(Collectors.toMap(Map.Entry::getKey, e -> new ArtifactDataDefinition(e.getValue())));
2847         return nodeTemplateOperation.addDeploymentArtifactsToInstance(componentId, componentInstance.getUniqueId(), instDeplArtifacts);
2848     }
2849
2850     public StorageOperationStatus addInformationalArtifactsToInstance(String componentId, ComponentInstance componentInstance,
2851                                                                       Map<String, ArtifactDefinition> artifacts) {
2852         StorageOperationStatus status = StorageOperationStatus.OK;
2853         if (MapUtils.isNotEmpty(artifacts)) {
2854             Map<String, ArtifactDataDefinition> instDeplArtifacts = artifacts.entrySet().stream()
2855                 .collect(Collectors.toMap(Map.Entry::getKey, e -> new ArtifactDataDefinition(e.getValue())));
2856             status = nodeTemplateOperation.addInformationalArtifactsToInstance(componentId, componentInstance.getUniqueId(), instDeplArtifacts);
2857         }
2858         return status;
2859     }
2860
2861     public StorageOperationStatus generateCustomizationUUIDOnInstance(String componentId, String instanceId) {
2862         return nodeTemplateOperation.generateCustomizationUUIDOnInstance(componentId, instanceId);
2863     }
2864
2865     public StorageOperationStatus generateCustomizationUUIDOnInstanceGroup(String componentId, String instanceId, List<String> groupInstances) {
2866         return nodeTemplateOperation.generateCustomizationUUIDOnInstanceGroup(componentId, instanceId, groupInstances);
2867     }
2868
2869     public Either<PropertyDefinition, StorageOperationStatus> addPropertyToComponent(PropertyDefinition newPropertyDefinition,
2870                                                                                      Component component) {
2871         final String propertyName = newPropertyDefinition.getName();
2872         StorageOperationStatus status = getToscaElementOperation(component)
2873             .addToscaDataToToscaElement(component.getUniqueId(), EdgeLabelEnum.PROPERTIES, VertexTypeEnum.PROPERTIES, newPropertyDefinition,
2874                 JsonPresentationFields.NAME);
2875         if (status != StorageOperationStatus.OK) {
2876             CommonUtility.addRecordToLog(log, LogLevelEnum.DEBUG, "Failed to add the property {} to the component {}. Status is {}. ", propertyName,
2877                 component.getName(), status);
2878             return Either.right(status);
2879         }
2880         ComponentParametersView filter = new ComponentParametersView(true);
2881         filter.setIgnoreProperties(false);
2882         filter.setIgnoreInputs(false);
2883         Either<Component, StorageOperationStatus> getUpdatedComponentRes = getToscaElement(component.getUniqueId(), filter);
2884         if (getUpdatedComponentRes.isRight()) {
2885             CommonUtility.addRecordToLog(log, LogLevelEnum.DEBUG, "Failed to get updated component {}. Status is {}. ", component.getUniqueId(),
2886                 getUpdatedComponentRes.right().value());
2887             return Either.right(status);
2888         }
2889         PropertyDefinition newProperty = null;
2890         List<PropertyDefinition> properties = (getUpdatedComponentRes.left().value()).getProperties();
2891         if (CollectionUtils.isNotEmpty(properties)) {
2892             Optional<PropertyDefinition> propertyOptional = properties.stream().filter(propertyEntry -> propertyEntry.getName().equals(propertyName))
2893                 .findAny();
2894             if (propertyOptional.isPresent()) {
2895                 newProperty = propertyOptional.get();
2896             }
2897         }
2898         if (newProperty == null) {
2899             CommonUtility.addRecordToLog(log, LogLevelEnum.DEBUG, "Failed to find recently added property {} on the component {}. Status is {}. ",
2900                 propertyName, component.getUniqueId(), StorageOperationStatus.NOT_FOUND);
2901             return Either.right(StorageOperationStatus.NOT_FOUND);
2902         }
2903         return Either.left(newProperty);
2904     }
2905
2906     public Either<InputDefinition, StorageOperationStatus> addInputToComponent(String inputName, InputDefinition newInputDefinition,
2907                                                                                Component component) {
2908         newInputDefinition.setName(inputName);
2909         StorageOperationStatus status = getToscaElementOperation(component)
2910             .addToscaDataToToscaElement(component.getUniqueId(), EdgeLabelEnum.INPUTS, VertexTypeEnum.INPUTS, newInputDefinition,
2911                 JsonPresentationFields.NAME);
2912         if (status != StorageOperationStatus.OK) {
2913             CommonUtility.addRecordToLog(log, LogLevelEnum.DEBUG, "Failed to add the input {} to the component {}. Status is {}. ", inputName,
2914                 component.getName(), status);
2915             return Either.right(status);
2916         }
2917         ComponentParametersView filter = new ComponentParametersView(true);
2918         filter.setIgnoreProperties(false);
2919         filter.setIgnoreInputs(false);
2920         Either<Component, StorageOperationStatus> getUpdatedComponentRes = getToscaElement(component.getUniqueId(), filter);
2921         if (getUpdatedComponentRes.isRight()) {
2922             CommonUtility.addRecordToLog(log, LogLevelEnum.DEBUG, "Failed to get updated component {}. Status is {}. ", component.getUniqueId(),
2923                 getUpdatedComponentRes.right().value());
2924             return Either.right(status);
2925         }
2926         InputDefinition newInput = null;
2927         List<InputDefinition> inputs = (getUpdatedComponentRes.left().value()).getInputs();
2928         if (CollectionUtils.isNotEmpty(inputs)) {
2929             Optional<InputDefinition> inputOptional = inputs.stream().filter(inputEntry -> inputEntry.getName().equals(inputName)).findAny();
2930             if (inputOptional.isPresent()) {
2931                 newInput = inputOptional.get();
2932             }
2933         }
2934         if (newInput == null) {
2935             CommonUtility
2936                 .addRecordToLog(log, LogLevelEnum.DEBUG, "Failed to find recently added input {} " + "on the component {}. Status is {}. ", inputs,
2937                     component.getUniqueId(), StorageOperationStatus.NOT_FOUND);
2938             return Either.right(StorageOperationStatus.NOT_FOUND);
2939         }
2940         return Either.left(newInput);
2941     }
2942
2943     public StorageOperationStatus deletePropertyOfComponent(Component component, String propertyName) {
2944         return getToscaElementOperation(component)
2945             .deleteToscaDataElement(component.getUniqueId(), EdgeLabelEnum.PROPERTIES, VertexTypeEnum.PROPERTIES, propertyName,
2946                 JsonPresentationFields.NAME);
2947     }
2948
2949     public StorageOperationStatus deleteAttributeOfResource(Component component, String attributeName) {
2950         return getToscaElementOperation(component)
2951             .deleteToscaDataElement(component.getUniqueId(), EdgeLabelEnum.ATTRIBUTES, VertexTypeEnum.ATTRIBUTES, attributeName,
2952                 JsonPresentationFields.NAME);
2953     }
2954
2955     public StorageOperationStatus deleteInputOfResource(Component resource, String inputName) {
2956         return getToscaElementOperation(resource)
2957             .deleteToscaDataElement(resource.getUniqueId(), EdgeLabelEnum.INPUTS, VertexTypeEnum.INPUTS, inputName, JsonPresentationFields.NAME);
2958     }
2959
2960     public StorageOperationStatus deleteOutputOfResource(final Component resource, final String outputName) {
2961         return getToscaElementOperation(resource)
2962             .deleteToscaDataElement(resource.getUniqueId(), EdgeLabelEnum.OUTPUTS, VertexTypeEnum.OUTPUTS, outputName, JsonPresentationFields.NAME);
2963     }
2964
2965     /**
2966      * Deletes a data type from a component.
2967      *
2968      * @param component    the container which has the data type
2969      * @param dataTypeName the data type name to be deleted
2970      * @return Operation result.
2971      */
2972     public StorageOperationStatus deleteDataTypeOfComponent(Component component, String dataTypeName) {
2973         return getToscaElementOperation(component)
2974             .deleteToscaDataElement(component.getUniqueId(), EdgeLabelEnum.DATA_TYPES, VertexTypeEnum.DATA_TYPES, dataTypeName,
2975                 JsonPresentationFields.NAME);
2976     }
2977
2978     public Either<PropertyDefinition, StorageOperationStatus> updatePropertyOfComponent(Component component,
2979                                                                                         PropertyDefinition newPropertyDefinition) {
2980         Either<Component, StorageOperationStatus> getUpdatedComponentRes = null;
2981         Either<PropertyDefinition, StorageOperationStatus> result = null;
2982         StorageOperationStatus status = getToscaElementOperation(component)
2983             .updateToscaDataOfToscaElement(component.getUniqueId(), EdgeLabelEnum.PROPERTIES, VertexTypeEnum.PROPERTIES, newPropertyDefinition,
2984                 JsonPresentationFields.NAME);
2985         if (status != StorageOperationStatus.OK) {
2986             CommonUtility
2987                 .addRecordToLog(log, LogLevelEnum.DEBUG, FAILED_TO_ADD_THE_PROPERTY_TO_THE_RESOURCE_STATUS_IS, newPropertyDefinition.getName(),
2988                     component.getName(), status);
2989             result = Either.right(status);
2990         }
2991         if (result == null) {
2992             ComponentParametersView filter = new ComponentParametersView(true);
2993             filter.setIgnoreProperties(false);
2994             getUpdatedComponentRes = getToscaElement(component.getUniqueId(), filter);
2995             if (getUpdatedComponentRes.isRight()) {
2996                 CommonUtility.addRecordToLog(log, LogLevelEnum.DEBUG, FAILED_TO_GET_UPDATED_RESOURCE_STATUS_IS, component.getUniqueId(),
2997                     getUpdatedComponentRes.right().value());
2998                 result = Either.right(status);
2999             }
3000         }
3001         if (result == null) {
3002             Optional<PropertyDefinition> newProperty = (getUpdatedComponentRes.left().value()).getProperties().stream()
3003                 .filter(p -> p.getName().equals(newPropertyDefinition.getName())).findAny();
3004             if (newProperty.isPresent()) {
3005                 result = Either.left(newProperty.get());
3006             } else {
3007                 CommonUtility.addRecordToLog(log, LogLevelEnum.DEBUG, FAILED_TO_FIND_RECENTLY_ADDED_PROPERTY_ON_THE_RESOURCE_STATUS_IS,
3008                     newPropertyDefinition.getName(), component.getUniqueId(), StorageOperationStatus.NOT_FOUND);
3009                 result = Either.right(StorageOperationStatus.NOT_FOUND);
3010             }
3011         }
3012         return result;
3013     }
3014
3015     public Either<AttributeDefinition, StorageOperationStatus> updateAttributeOfComponent(Component component,
3016                                                                                           AttributeDefinition newPropertyDefinition) {
3017         Either<Component, StorageOperationStatus> getUpdatedComponentRes = null;
3018         Either<AttributeDefinition, StorageOperationStatus> result = null;
3019         StorageOperationStatus status = getToscaElementOperation(component)
3020             .updateToscaDataOfToscaElement(component.getUniqueId(), EdgeLabelEnum.ATTRIBUTES, VertexTypeEnum.ATTRIBUTES, newPropertyDefinition,
3021                 JsonPresentationFields.NAME);
3022         if (status != StorageOperationStatus.OK) {
3023             CommonUtility
3024                 .addRecordToLog(log, LogLevelEnum.DEBUG, FAILED_TO_ADD_THE_PROPERTY_TO_THE_RESOURCE_STATUS_IS, newPropertyDefinition.getName(),
3025                     component.getName(), status);
3026             result = Either.right(status);
3027         }
3028         if (result == null) {
3029             ComponentParametersView filter = new ComponentParametersView(true);
3030             filter.setIgnoreProperties(false);
3031             getUpdatedComponentRes = getToscaElement(component.getUniqueId(), filter);
3032             if (getUpdatedComponentRes.isRight()) {
3033                 CommonUtility.addRecordToLog(log, LogLevelEnum.DEBUG, FAILED_TO_GET_UPDATED_RESOURCE_STATUS_IS, component.getUniqueId(),
3034                     getUpdatedComponentRes.right().value());
3035                 result = Either.right(status);
3036             }
3037         }
3038         if (result == null) {
3039             Optional<AttributeDefinition> newProperty = (getUpdatedComponentRes.left().value()).getAttributes().stream()
3040                 .filter(p -> p.getName().equals(newPropertyDefinition.getName())).findAny();
3041             if (newProperty.isPresent()) {
3042                 result = Either.left(newProperty.get());
3043             } else {
3044                 CommonUtility.addRecordToLog(log, LogLevelEnum.DEBUG, FAILED_TO_FIND_RECENTLY_ADDED_PROPERTY_ON_THE_RESOURCE_STATUS_IS,
3045                     newPropertyDefinition.getName(), component.getUniqueId(), StorageOperationStatus.NOT_FOUND);
3046                 result = Either.right(StorageOperationStatus.NOT_FOUND);
3047             }
3048         }
3049         return result;
3050     }
3051
3052     public Either<AttributeDefinition, StorageOperationStatus> addAttributeOfResource(Component component, AttributeDefinition newAttributeDef) {
3053         Either<Component, StorageOperationStatus> getUpdatedComponentRes = null;
3054         Either<AttributeDefinition, StorageOperationStatus> result = null;
3055         if (newAttributeDef.getUniqueId() == null || newAttributeDef.getUniqueId().isEmpty()) {
3056             String attUniqueId = UniqueIdBuilder.buildAttributeUid(component.getUniqueId(), newAttributeDef.getName());
3057             newAttributeDef.setUniqueId(attUniqueId);
3058             newAttributeDef.setOwnerId(component.getUniqueId());
3059         }
3060         StorageOperationStatus status = getToscaElementOperation(component)
3061             .addToscaDataToToscaElement(component.getUniqueId(), EdgeLabelEnum.ATTRIBUTES, VertexTypeEnum.ATTRIBUTES, newAttributeDef,
3062                 JsonPresentationFields.NAME);
3063         if (status != StorageOperationStatus.OK) {
3064             CommonUtility.addRecordToLog(log, LogLevelEnum.DEBUG, FAILED_TO_ADD_THE_PROPERTY_TO_THE_RESOURCE_STATUS_IS, newAttributeDef.getName(),
3065                 component.getName(), status);
3066             result = Either.right(status);
3067         }
3068         if (result == null) {
3069             ComponentParametersView filter = new ComponentParametersView(true);
3070             filter.setIgnoreAttributes(false);
3071             getUpdatedComponentRes = getToscaElement(component.getUniqueId(), filter);
3072             if (getUpdatedComponentRes.isRight()) {
3073                 CommonUtility.addRecordToLog(log, LogLevelEnum.DEBUG, FAILED_TO_GET_UPDATED_RESOURCE_STATUS_IS, component.getUniqueId(),
3074                     getUpdatedComponentRes.right().value());
3075                 result = Either.right(status);
3076             }
3077         }
3078         if (result == null) {
3079             Optional<AttributeDefinition> newAttribute = ((Resource) getUpdatedComponentRes.left().value()).getAttributes().stream()
3080                 .filter(p -> p.getName().equals(newAttributeDef.getName())).findAny();
3081             if (newAttribute.isPresent()) {
3082                 result = Either.left(newAttribute.get());
3083             } else {
3084                 CommonUtility.addRecordToLog(log, LogLevelEnum.DEBUG, FAILED_TO_FIND_RECENTLY_ADDED_PROPERTY_ON_THE_RESOURCE_STATUS_IS,
3085                     newAttributeDef.getName(), component.getUniqueId(), StorageOperationStatus.NOT_FOUND);
3086                 result = Either.right(StorageOperationStatus.NOT_FOUND);
3087             }
3088         }
3089         return result;
3090     }
3091
3092     public Either<AttributeDefinition, StorageOperationStatus> updateAttributeOfResource(Component component, AttributeDefinition newAttributeDef) {
3093         Either<Component, StorageOperationStatus> getUpdatedComponentRes = null;
3094         Either<AttributeDefinition, StorageOperationStatus> result = null;
3095         StorageOperationStatus status = getToscaElementOperation(component)
3096             .updateToscaDataOfToscaElement(component.getUniqueId(), EdgeLabelEnum.ATTRIBUTES, VertexTypeEnum.ATTRIBUTES, newAttributeDef,
3097                 JsonPresentationFields.NAME);
3098         if (status != StorageOperationStatus.OK) {
3099             CommonUtility.addRecordToLog(log, LogLevelEnum.DEBUG, FAILED_TO_ADD_THE_PROPERTY_TO_THE_RESOURCE_STATUS_IS, newAttributeDef.getName(),
3100                 component.getName(), status);
3101             result = Either.right(status);
3102         }
3103         if (result == null) {
3104             ComponentParametersView filter = new ComponentParametersView(true);
3105             filter.setIgnoreAttributes(false);
3106             getUpdatedComponentRes = getToscaElement(component.getUniqueId(), filter);
3107             if (getUpdatedComponentRes.isRight()) {
3108                 CommonUtility.addRecordToLog(log, LogLevelEnum.DEBUG, FAILED_TO_GET_UPDATED_RESOURCE_STATUS_IS, component.getUniqueId(),
3109                     getUpdatedComponentRes.right().value());
3110                 result = Either.right(status);
3111             }
3112         }
3113         if (result == null) {
3114             Optional<AttributeDefinition> newProperty = ((Resource) getUpdatedComponentRes.left().value()).getAttributes().stream()
3115                 .filter(p -> p.getName().equals(newAttributeDef.getName())).findAny();
3116             if (newProperty.isPresent()) {
3117                 result = Either.left(newProperty.get());
3118             } else {
3119                 CommonUtility.addRecordToLog(log, LogLevelEnum.DEBUG, FAILED_TO_FIND_RECENTLY_ADDED_PROPERTY_ON_THE_RESOURCE_STATUS_IS,
3120                     newAttributeDef.getName(), component.getUniqueId(), StorageOperationStatus.NOT_FOUND);
3121                 result = Either.right(StorageOperationStatus.NOT_FOUND);
3122             }
3123         }
3124         return result;
3125     }
3126
3127     public Either<InputDefinition, StorageOperationStatus> updateInputOfComponent(Component component, InputDefinition newInputDefinition) {
3128         Either<Component, StorageOperationStatus> getUpdatedComponentRes = null;
3129         Either<InputDefinition, StorageOperationStatus> result = null;
3130         StorageOperationStatus status = getToscaElementOperation(component)
3131             .updateToscaDataOfToscaElement(component.getUniqueId(), EdgeLabelEnum.INPUTS, VertexTypeEnum.INPUTS, newInputDefinition,
3132                 JsonPresentationFields.NAME);
3133         if (status != StorageOperationStatus.OK) {
3134             CommonUtility.addRecordToLog(log, LogLevelEnum.DEBUG, "Failed to update the input {} to the component {}. Status is {}. ",
3135                 newInputDefinition.getName(), component.getName(), status);
3136             result = Either.right(status);
3137         }
3138         if (result == null) {
3139             ComponentParametersView filter = new ComponentParametersView(true);
3140             filter.setIgnoreInputs(false);
3141             getUpdatedComponentRes = getToscaElement(component.getUniqueId(), filter);
3142             if (getUpdatedComponentRes.isRight()) {
3143                 CommonUtility.addRecordToLog(log, LogLevelEnum.DEBUG, FAILED_TO_GET_UPDATED_RESOURCE_STATUS_IS, component.getUniqueId(),
3144                     getUpdatedComponentRes.right().value());
3145                 result = Either.right(status);
3146             }
3147         }
3148         if (result == null) {
3149             Optional<InputDefinition> updatedInput = getUpdatedComponentRes.left().value().getInputs().stream()
3150                 .filter(p -> p.getName().equals(newInputDefinition.getName())).findAny();
3151             if (updatedInput.isPresent()) {
3152                 result = Either.left(updatedInput.get());
3153             } else {
3154                 CommonUtility.addRecordToLog(log, LogLevelEnum.DEBUG, "Failed to find recently updated inputs {} on the resource {}. Status is {}. ",
3155                     newInputDefinition.getName(), component.getUniqueId(), StorageOperationStatus.NOT_FOUND);
3156                 result = Either.right(StorageOperationStatus.NOT_FOUND);
3157             }
3158         }
3159         return result;
3160     }
3161
3162     /**
3163      * method - ename the group instances after referenced container name renamed flow - VF rename -(triggers)-> Group rename
3164      *
3165      * @param containerComponent  - container such as service
3166      * @param componentInstance   - context component
3167      * @param componentInstanceId - id
3168      * @return - successfull/failed status
3169      **/
3170     public Either<StorageOperationStatus, StorageOperationStatus> cleanAndAddGroupInstancesToComponentInstance(Component containerComponent,
3171                                                                                                                ComponentInstance componentInstance,
3172                                                                                                                String componentInstanceId) {
3173         String uniqueId = componentInstance.getUniqueId();
3174         StorageOperationStatus status = nodeTemplateOperation
3175             .deleteToscaDataDeepElementsBlockOfToscaElement(containerComponent.getUniqueId(), EdgeLabelEnum.INST_GROUPS, VertexTypeEnum.INST_GROUPS,
3176                 uniqueId);
3177         if (status != StorageOperationStatus.OK && status != StorageOperationStatus.NOT_FOUND) {
3178             CommonUtility
3179                 .addRecordToLog(log, LogLevelEnum.DEBUG, "Failed to delete group instances for container {}. error {] ", componentInstanceId, status);
3180             return Either.right(status);
3181         }
3182         if (componentInstance.getGroupInstances() != null) {
3183             status = addGroupInstancesToComponentInstance(containerComponent, componentInstance, componentInstance.getGroupInstances());
3184             if (status != StorageOperationStatus.OK && status != StorageOperationStatus.NOT_FOUND) {
3185                 CommonUtility
3186                     .addRecordToLog(log, LogLevelEnum.DEBUG, "Failed to add group instances for container {}. error {] ", componentInstanceId,
3187                         status);
3188                 return Either.right(status);
3189             }
3190         }
3191         return Either.left(status);
3192     }
3193
3194     public StorageOperationStatus addGroupInstancesToComponentInstance(Component containerComponent, ComponentInstance componentInstance,
3195                                                                        List<GroupDefinition> groups,
3196                                                                        Map<String, List<ArtifactDefinition>> groupInstancesArtifacts) {
3197         return nodeTemplateOperation.addGroupInstancesToComponentInstance(containerComponent, componentInstance, groups, groupInstancesArtifacts);
3198     }
3199
3200     public Either<List<GroupDefinition>, StorageOperationStatus> updateGroupsOnComponent(Component component,
3201                                                                                          List<GroupDataDefinition> updatedGroups) {
3202         return groupsOperation.updateGroups(component, updatedGroups, PromoteVersionEnum.MINOR);
3203     }
3204
3205     public Either<List<GroupInstance>, StorageOperationStatus> updateGroupInstancesOnComponent(Component component, String instanceId,
3206                                                                                                List<GroupInstance> updatedGroupInstances) {
3207         return groupsOperation.updateGroupInstances(component, instanceId, updatedGroupInstances);
3208     }
3209
3210     public StorageOperationStatus addGroupInstancesToComponentInstance(Component containerComponent, ComponentInstance componentInstance,
3211                                                                        List<GroupInstance> groupInstances) {
3212         return nodeTemplateOperation.addGroupInstancesToComponentInstance(containerComponent, componentInstance, groupInstances);
3213     }
3214
3215     public StorageOperationStatus addDeploymentArtifactsToComponentInstance(Component containerComponent, ComponentInstance componentInstance,
3216                                                                             Map<String, ArtifactDefinition> deploymentArtifacts) {
3217         return nodeTemplateOperation.addDeploymentArtifactsToComponentInstance(containerComponent, componentInstance, deploymentArtifacts);
3218     }
3219
3220     public StorageOperationStatus updateComponentInstanceProperty(Component containerComponent, String componentInstanceId,
3221                                                                   ComponentInstanceProperty property) {
3222         return nodeTemplateOperation.updateComponentInstanceProperty(containerComponent, componentInstanceId, property);
3223     }
3224
3225     public StorageOperationStatus updateComponentInstanceProperties(Component containerComponent, String componentInstanceId,
3226                                                                     List<ComponentInstanceProperty> properties) {
3227         return nodeTemplateOperation.updateComponentInstanceProperties(containerComponent, componentInstanceId, properties);
3228     }
3229
3230     public StorageOperationStatus updateComponentInstanceAttributes(final Component containerComponent, final String componentInstanceId,
3231                                                                     final List<ComponentInstanceAttribute> attributes) {
3232         return nodeTemplateOperation.updateComponentInstanceAttributes(containerComponent, componentInstanceId, attributes);
3233     }
3234
3235     public StorageOperationStatus addComponentInstanceProperty(Component containerComponent, String componentInstanceId,
3236                                                                ComponentInstanceProperty property) {
3237         return nodeTemplateOperation.addComponentInstanceProperty(containerComponent, componentInstanceId, property);
3238     }
3239
3240     public StorageOperationStatus updateComponentInstanceAttribute(final Component containerComponent, final String componentInstanceId,
3241                                                                    final ComponentInstanceAttribute attribute) {
3242         return nodeTemplateOperation.updateComponentInstanceAttribute(containerComponent, componentInstanceId, attribute);
3243     }
3244
3245     public StorageOperationStatus addComponentInstanceAttribute(Component containerComponent, String componentInstanceId,
3246                                                                 ComponentInstanceAttribute attribute) {
3247         return nodeTemplateOperation.addComponentInstanceAttribute(containerComponent, componentInstanceId, attribute);
3248     }
3249
3250     public StorageOperationStatus updateComponentInstanceInput(Component containerComponent, String componentInstanceId,
3251                                                                ComponentInstanceInput property) {
3252         return nodeTemplateOperation.updateComponentInstanceInput(containerComponent, componentInstanceId, property);
3253     }
3254
3255     public StorageOperationStatus updateComponentInstanceOutput(Component containerComponent, String componentInstanceId,
3256                                                                 ComponentInstanceOutput property) {
3257         return nodeTemplateOperation.updateComponentInstanceOutput(containerComponent, componentInstanceId, property);
3258     }
3259
3260     public StorageOperationStatus updateComponentInstanceInputs(Component containerComponent, String componentInstanceId,
3261                                                                 List<ComponentInstanceInput> instanceInputs) {
3262         return nodeTemplateOperation.updateComponentInstanceInputs(containerComponent, componentInstanceId, instanceInputs);
3263     }
3264
3265     public StorageOperationStatus updateComponentInstanceOutputs(Component containerComponent, String componentInstanceId,
3266                                                                  List<ComponentInstanceOutput> instanceInputs) {
3267         return nodeTemplateOperation.updateComponentInstanceOutputs(containerComponent, componentInstanceId, instanceInputs);
3268     }
3269
3270     public StorageOperationStatus addComponentInstanceInput(Component containerComponent, String componentInstanceId,
3271                                                             ComponentInstanceInput property) {
3272         return nodeTemplateOperation.addComponentInstanceInput(containerComponent, componentInstanceId, property);
3273     }
3274
3275     public StorageOperationStatus addComponentInstanceOutput(Component containerComponent, String componentInstanceId,
3276                                                              ComponentInstanceOutput property) {
3277         return nodeTemplateOperation.addComponentInstanceOutput(containerComponent, componentInstanceId, property);
3278     }
3279
3280     public void setNodeTypeOperation(NodeTypeOperation nodeTypeOperation) {
3281         this.nodeTypeOperation = nodeTypeOperation;
3282     }
3283
3284     public void setTopologyTemplateOperation(TopologyTemplateOperation topologyTemplateOperation) {
3285         this.topologyTemplateOperation = topologyTemplateOperation;
3286     }
3287
3288     public StorageOperationStatus deleteComponentInstanceInputsFromTopologyTemplate(Component containerComponent,
3289                                                                                     List<InputDefinition> inputsToDelete) {
3290         return topologyTemplateOperation.deleteToscaDataElements(containerComponent.getUniqueId(), EdgeLabelEnum.INPUTS,
3291             inputsToDelete.stream().map(PropertyDataDefinition::getName).collect(Collectors.toList()));
3292     }
3293
3294     public StorageOperationStatus deleteComponentInstanceOutputsFromTopologyTemplate(final Component containerComponent,
3295                                                                                      final List<OutputDefinition> outputsToDelete) {
3296         return topologyTemplateOperation.deleteToscaDataElements(containerComponent.getUniqueId(), EdgeLabelEnum.OUTPUTS,
3297             outputsToDelete.stream().map(AttributeDataDefinition::getName).collect(Collectors.toList()));
3298     }
3299
3300     public StorageOperationStatus updateComponentInstanceCapabiltyProperty(Component containerComponent, String componentInstanceUniqueId,
3301                                                                            String capabilityPropertyKey, ComponentInstanceProperty property) {
3302         return nodeTemplateOperation
3303             .updateComponentInstanceCapabilityProperty(containerComponent, componentInstanceUniqueId, capabilityPropertyKey, property);
3304     }
3305
3306     public StorageOperationStatus updateComponentInstanceCapabilityProperties(Component containerComponent, String componentInstanceUniqueId) {
3307         return convertComponentInstanceProperties(containerComponent, componentInstanceUniqueId).map(instanceCapProps -> topologyTemplateOperation
3308                 .updateComponentInstanceCapabilityProperties(containerComponent, componentInstanceUniqueId, instanceCapProps))
3309             .orElse(StorageOperationStatus.NOT_FOUND);
3310     }
3311
3312     public StorageOperationStatus updateComponentInstanceRequirement(String containerComponentId, String componentInstanceUniqueId,
3313                                                                      RequirementDataDefinition requirementDataDefinition) {
3314         return nodeTemplateOperation.updateComponentInstanceRequirement(containerComponentId, componentInstanceUniqueId, requirementDataDefinition);
3315     }
3316
3317     public CapabilityDataDefinition updateComponentInstanceCapability(final String containerComponentId, final String componentInstanceUniqueId,
3318                                                                       final CapabilityDataDefinition capabilityDataDefinition) {
3319
3320         return nodeTemplateOperation.updateComponentInstanceCapabilities(containerComponentId, componentInstanceUniqueId, capabilityDataDefinition);
3321     }
3322
3323     public StorageOperationStatus updateComponentInstanceInterfaces(Component containerComponent, String componentInstanceUniqueId) {
3324         MapInterfaceDataDefinition mapInterfaceDataDefinition = convertComponentInstanceInterfaces(containerComponent, componentInstanceUniqueId);
3325         return topologyTemplateOperation.updateComponentInstanceInterfaces(containerComponent, componentInstanceUniqueId, mapInterfaceDataDefinition);
3326     }
3327
3328     public StorageOperationStatus updateComponentInterfaces(final Component component, final String componentInterfaceUpdatedKey) {
3329         MapInterfaceDataDefinition mapInterfaceDataDefinition = convertComponentInterfaces(component.getInterfaces());
3330         return topologyTemplateOperation.updateComponentInterfaces(component.getUniqueId(), mapInterfaceDataDefinition, componentInterfaceUpdatedKey);
3331     }
3332
3333     public Either<InterfaceDefinition, StorageOperationStatus> addInterfaceToComponent(final String interfaceName,
3334                                                                                        final InterfaceDefinition interfaceDefinition,
3335                                                                                        final Component component) {
3336
3337         final boolean match = component.getInterfaces().keySet().stream().anyMatch(s -> s.equals(interfaceName));
3338         StorageOperationStatus status = StorageOperationStatus.OK;
3339         final ToscaElementOperation toscaElementOperation = getToscaElementOperation(component);
3340         if (match) {
3341             status = toscaElementOperation.updateToscaDataOfToscaElement(component.getUniqueId(), EdgeLabelEnum.INTERFACE_ARTIFACTS,
3342                 VertexTypeEnum.INTERFACE_ARTIFACTS, interfaceDefinition, JsonPresentationFields.TYPE);
3343         } else {
3344             status = toscaElementOperation.addToscaDataToToscaElement(component.getUniqueId(), EdgeLabelEnum.INTERFACE_ARTIFACTS,
3345                 VertexTypeEnum.INTERFACE_ARTIFACTS, interfaceDefinition, JsonPresentationFields.TYPE);
3346         }
3347
3348         if (status != StorageOperationStatus.OK) {
3349             CommonUtility.addRecordToLog(log, LogLevelEnum.DEBUG, "Failed to add the interface {} to the component {}. Status is {}. ",
3350                 interfaceName, component.getName(), status);
3351             return Either.right(status);
3352         }
3353         final ComponentParametersView filter = new ComponentParametersView(true);
3354         filter.setIgnoreInterfaces(false);
3355         filter.setIgnoreInterfaceInstances(false);
3356         final Either<Component, StorageOperationStatus> getUpdatedComponentRes = getToscaElement(component.getUniqueId(), filter);
3357         if (getUpdatedComponentRes.isRight()) {
3358             CommonUtility.addRecordToLog(log, LogLevelEnum.DEBUG, "Failed to get updated component {}. Status is {}. ",
3359                 component.getUniqueId(), getUpdatedComponentRes.right().value());
3360             return Either.right(getUpdatedComponentRes.right().value());
3361         }
3362         InterfaceDefinition newInterfaceDefinition = null;
3363         final Map<String, InterfaceDefinition> interfaces = (getUpdatedComponentRes.left().value()).getInterfaces();
3364         if (MapUtils.isNotEmpty(interfaces)) {
3365             final Optional<String> interfaceNameOptional = interfaces.keySet().stream().filter(key -> key.equals(interfaceName)).findAny();
3366             if (interfaceNameOptional.isPresent()) {
3367                 newInterfaceDefinition = interfaces.get(interfaceNameOptional.get());
3368             }
3369         }
3370         if (newInterfaceDefinition == null) {
3371             CommonUtility.addRecordToLog(log, LogLevelEnum.DEBUG, "Failed to find recently added interface {} on the component {}. Status is {}. ",
3372                 interfaceName, component.getUniqueId(), StorageOperationStatus.NOT_FOUND);
3373             return Either.right(StorageOperationStatus.NOT_FOUND);
3374         }
3375         return Either.left(newInterfaceDefinition);
3376     }
3377
3378     public StorageOperationStatus updateComponentCalculatedCapabilitiesProperties(Component containerComponent) {
3379         Map<String, MapCapabilityProperty> mapCapabiltyPropertyMap = convertComponentCapabilitiesProperties(containerComponent);
3380         return nodeTemplateOperation.overrideComponentCapabilitiesProperties(containerComponent, mapCapabiltyPropertyMap);
3381     }
3382
3383     public StorageOperationStatus deleteAllCalculatedCapabilitiesRequirements(String topologyTemplateId) {
3384         StorageOperationStatus status = topologyTemplateOperation
3385             .removeToscaData(topologyTemplateId, EdgeLabelEnum.CALCULATED_CAPABILITIES, VertexTypeEnum.CALCULATED_CAPABILITIES);
3386         if (status == StorageOperationStatus.OK) {
3387             status = topologyTemplateOperation
3388                 .removeToscaData(topologyTemplateId, EdgeLabelEnum.CALCULATED_REQUIREMENTS, VertexTypeEnum.CALCULATED_REQUIREMENTS);
3389         }
3390         if (status == StorageOperationStatus.OK) {
3391             status = topologyTemplateOperation
3392                 .removeToscaData(topologyTemplateId, EdgeLabelEnum.CALCULATED_CAP_PROPERTIES, VertexTypeEnum.CALCULATED_CAP_PROPERTIES);
3393         }
3394         return status;
3395     }
3396
3397     public Either<Component, StorageOperationStatus> shouldUpgradeToLatestDerived(Resource clonedResource) {
3398         String componentId = clonedResource.getUniqueId();
3399         Either<GraphVertex, JanusGraphOperationStatus> getVertexEither = janusGraphDao.getVertexById(componentId, JsonParseFlagEnum.NoParse);
3400         if (getVertexEither.isRight()) {
3401             log.debug(COULDNT_FETCH_COMPONENT_WITH_AND_UNIQUE_ID_ERROR, componentId, getVertexEither.right().value());
3402             return Either.right(DaoStatusConverter.convertJanusGraphStatusToStorageStatus(getVertexEither.right().value()));
3403         }
3404         GraphVertex nodeTypeV = getVertexEither.left().value();
3405         ToscaElement toscaElementToUpdate = ModelConverter.convertToToscaElement(clonedResource);
3406         Either<ToscaElement, StorageOperationStatus> shouldUpdateDerivedVersion = nodeTypeOperation
3407             .shouldUpdateDerivedVersion(toscaElementToUpdate, nodeTypeV);
3408         if (shouldUpdateDerivedVersion.isRight() && StorageOperationStatus.OK != shouldUpdateDerivedVersion.right().value()) {
3409             log.debug("Failed to update derived version for node type {} derived {}, error: {}", componentId, clonedResource.getDerivedFrom().get(0),
3410                 shouldUpdateDerivedVersion.right().value());
3411             return Either.right(shouldUpdateDerivedVersion.right().value());
3412         }
3413         if (shouldUpdateDerivedVersion.isLeft()) {
3414             return Either.left(ModelConverter.convertFromToscaElement(shouldUpdateDerivedVersion.left().value()));
3415         }
3416         return Either.left(clonedResource);
3417     }
3418
3419     /**
3420      * Returns list of ComponentInstanceProperty belonging to component instance capability specified by name, type and ownerId
3421      */
3422     public Either<List<ComponentInstanceProperty>, StorageOperationStatus> getComponentInstanceCapabilityProperties(String componentId,
3423                                                                                                                     String instanceId,
3424                                                                                                                     String capabilityName,
3425                                                                                                                     String capabilityType,
3426                                                                                                                     String ownerId) {
3427         return topologyTemplateOperation.getComponentInstanceCapabilityProperties(componentId, instanceId, capabilityName, capabilityType, ownerId);
3428     }
3429
3430     private MapInterfaceDataDefinition convertComponentInstanceInterfaces(Component currComponent, String componentInstanceId) {
3431         MapInterfaceDataDefinition mapInterfaceDataDefinition = new MapInterfaceDataDefinition();
3432         List<ComponentInstanceInterface> componentInterface = currComponent.getComponentInstancesInterfaces().get(componentInstanceId);
3433         if (CollectionUtils.isNotEmpty(componentInterface)) {
3434             componentInterface.stream().forEach(interfaceDef -> mapInterfaceDataDefinition.put(interfaceDef.getUniqueId(), interfaceDef));
3435         }
3436         return mapInterfaceDataDefinition;
3437     }
3438
3439     private MapInterfaceDataDefinition convertComponentInterfaces(final Map<String, InterfaceDefinition> interfaces) {
3440         final MapInterfaceDataDefinition mapInterfaceDataDefinition = new MapInterfaceDataDefinition();
3441         if (MapUtils.isNotEmpty(interfaces)) {
3442             interfaces.values().stream().forEach(interfaceDef -> mapInterfaceDataDefinition.put(interfaceDef.getType(), interfaceDef));
3443         }
3444         return mapInterfaceDataDefinition;
3445     }
3446
3447     private Map<String, MapCapabilityProperty> convertComponentCapabilitiesProperties(Component currComponent) {
3448         Map<String, MapCapabilityProperty> map = ModelConverter.extractCapabilityPropertiesFromGroups(currComponent.getGroups(), true);
3449         map.putAll(ModelConverter.extractCapabilityProperteisFromInstances(currComponent.getComponentInstances(), true));
3450         return map;
3451     }
3452
3453     private Optional<MapCapabilityProperty> convertComponentInstanceProperties(Component component, String instanceId) {
3454         return component.fetchInstanceById(instanceId)
3455             .map(ci -> ModelConverter.convertToMapOfMapCapabilityProperties(ci.getCapabilities(), instanceId, ci.getOriginType().isAtomicType()));
3456     }
3457
3458     public Either<PolicyDefinition, StorageOperationStatus> associatePolicyToComponent(String componentId, PolicyDefinition policyDefinition,
3459                                                                                        int counter) {
3460         Either<PolicyDefinition, StorageOperationStatus> result = null;
3461         Either<GraphVertex, JanusGraphOperationStatus> getVertexEither;
3462         getVertexEither = janusGraphDao.getVertexById(componentId, JsonParseFlagEnum.ParseMetadata);
3463         if (getVertexEither.isRight()) {
3464             log.error(COULDNT_FETCH_A_COMPONENT_WITH_AND_UNIQUE_ID_ERROR, componentId, getVertexEither.right().value());
3465             result = Either.right(DaoStatusConverter.convertJanusGraphStatusToStorageStatus(getVertexEither.right().value()));
3466         } else {
3467             if (getVertexEither.left().value().getLabel() != VertexTypeEnum.TOPOLOGY_TEMPLATE) {
3468                 log.error("Policy association to component of Tosca type {} is not allowed. ", getVertexEither.left().value().getLabel());
3469                 result = Either.right(StorageOperationStatus.BAD_REQUEST);
3470             }
3471         }
3472         if (result == null) {
3473             StorageOperationStatus status = topologyTemplateOperation
3474                 .addPolicyToToscaElement(getVertexEither.left().value(), policyDefinition, counter);
3475             if (status != StorageOperationStatus.OK) {
3476                 return Either.right(status);
3477             }
3478         }
3479         if (result == null) {
3480             result = Either.left(policyDefinition);
3481         }
3482         return result;
3483     }
3484
3485     public StorageOperationStatus associatePoliciesToComponent(String componentId, List<PolicyDefinition> policies) {
3486         log.debug("#associatePoliciesToComponent - associating policies for component {}.", componentId);
3487         return janusGraphDao.getVertexById(componentId, JsonParseFlagEnum.ParseMetadata)
3488             .either(containerVertex -> topologyTemplateOperation.addPoliciesToToscaElement(containerVertex, policies),
3489                 DaoStatusConverter::convertJanusGraphStatusToStorageStatus);
3490     }
3491
3492     public Either<PolicyDefinition, StorageOperationStatus> updatePolicyOfComponent(String componentId, PolicyDefinition policyDefinition,
3493                                                                                     PromoteVersionEnum promoteVersionEnum) {
3494         Either<PolicyDefinition, StorageOperationStatus> result = null;
3495         Either<GraphVertex, JanusGraphOperationStatus> getVertexEither;
3496         getVertexEither = janusGraphDao.getVertexById(componentId, JsonParseFlagEnum.NoParse);
3497         if (getVertexEither.isRight()) {
3498             log.error(COULDNT_FETCH_A_COMPONENT_WITH_AND_UNIQUE_ID_ERROR, componentId, getVertexEither.right().value());
3499             result = Either.right(DaoStatusConverter.convertJanusGraphStatusToStorageStatus(getVertexEither.right().value()));
3500         }
3501         if (result == null) {
3502             policyDefinition.setVersion(GroupUtils.updateVersion(promoteVersionEnum, policyDefinition.getVersion()));
3503             StorageOperationStatus status = topologyTemplateOperation.updatePolicyOfToscaElement(getVertexEither.left().value(), policyDefinition);
3504             if (status != StorageOperationStatus.OK) {
3505                 return Either.right(status);
3506             }
3507         }
3508         if (result == null) {
3509             result = Either.left(policyDefinition);
3510         }
3511         return result;
3512     }
3513
3514     public StorageOperationStatus updatePoliciesOfComponent(String componentId, List<PolicyDefinition> policyDefinition) {
3515         log.debug("#updatePoliciesOfComponent - updating policies for component {}", componentId);
3516         return janusGraphDao.getVertexById(componentId, JsonParseFlagEnum.NoParse).right()
3517             .map(DaoStatusConverter::convertJanusGraphStatusToStorageStatus)
3518             .either(containerVertex -> topologyTemplateOperation.updatePoliciesOfToscaElement(containerVertex, policyDefinition), err -> err);
3519     }
3520
3521     public StorageOperationStatus removePolicyFromComponent(String componentId, String policyId) {
3522         StorageOperationStatus status = null;
3523         Either<GraphVertex, JanusGraphOperationStatus> getVertexEither = janusGraphDao.getVertexById(componentId, JsonParseFlagEnum.NoParse);
3524         if (getVertexEither.isRight()) {
3525             log.error(COULDNT_FETCH_A_COMPONENT_WITH_AND_UNIQUE_ID_ERROR, componentId, getVertexEither.right().value());
3526             status = DaoStatusConverter.convertJanusGraphStatusToStorageStatus(getVertexEither.right().value());
3527         }
3528         if (status == null) {
3529             status = topologyTemplateOperation.removePolicyFromToscaElement(getVertexEither.left().value(), policyId);
3530         }
3531         return status;
3532     }
3533
3534     public boolean canAddGroups(String componentId) {
3535         GraphVertex vertex = janusGraphDao.getVertexById(componentId).left().on(this::onJanusGraphError);
3536         return topologyTemplateOperation.hasEdgeOfType(vertex, EdgeLabelEnum.GROUPS);
3537     }
3538
3539     GraphVertex onJanusGraphError(JanusGraphOperationStatus toe) {
3540         throw new StorageException(DaoStatusConverter.convertJanusGraphStatusToStorageStatus(toe));
3541     }
3542
3543     public CatalogUpdateTimestamp updateCatalogTimes() {
3544         long now = System.currentTimeMillis();
3545         GraphVertex catalogRoot = janusGraphDao.getVertexByLabel(VertexTypeEnum.CATALOG_ROOT).left().on(this::onJanusGraphError);
3546         Long currentTime = (Long) catalogRoot.getMetadataProperty(GraphPropertyEnum.CURRENT_CATALOG_UPDATE_TIME);
3547         catalogRoot.addMetadataProperty(GraphPropertyEnum.PREV_CATALOG_UPDATE_TIME, currentTime);
3548         catalogRoot.addMetadataProperty(GraphPropertyEnum.CURRENT_CATALOG_UPDATE_TIME, now);
3549         janusGraphDao.updateVertex(catalogRoot).left().on(this::onJanusGraphError);
3550         return new CatalogUpdateTimestamp(currentTime, now);
3551     }
3552
3553     public CatalogUpdateTimestamp getCatalogTimes() {
3554         GraphVertex catalogRoot = janusGraphDao.getVertexByLabel(VertexTypeEnum.CATALOG_ROOT).left().on(this::onJanusGraphError);
3555         Long currentTime = (Long) catalogRoot.getMetadataProperty(GraphPropertyEnum.CURRENT_CATALOG_UPDATE_TIME);
3556         Long prevTime = (Long) catalogRoot.getMetadataProperty(GraphPropertyEnum.PREV_CATALOG_UPDATE_TIME);
3557         return new CatalogUpdateTimestamp(prevTime == null ? 0 : prevTime.longValue(), currentTime == null ? 0 : currentTime.longValue());
3558     }
3559
3560     public void updateNamesOfCalculatedCapabilitiesRequirements(String componentId) {
3561         topologyTemplateOperation.updateNamesOfCalculatedCapabilitiesRequirements(componentId, getTopologyTemplate(componentId));
3562     }
3563
3564     public void revertNamesOfCalculatedCapabilitiesRequirements(String componentId) {
3565         topologyTemplateOperation.revertNamesOfCalculatedCapabilitiesRequirements(componentId, getTopologyTemplate(componentId));
3566     }
3567
3568     private TopologyTemplate getTopologyTemplate(String componentId) {
3569         return (TopologyTemplate) topologyTemplateOperation.getToscaElement(componentId, getFilterComponentWithCapProperties()).left()
3570             .on(this::throwStorageException);
3571     }
3572
3573     private ComponentParametersView getFilterComponentWithCapProperties() {
3574         ComponentParametersView filter = new ComponentParametersView();
3575         filter.setIgnoreCapabiltyProperties(false);
3576         return filter;
3577     }
3578
3579     private ToscaElement throwStorageException(StorageOperationStatus status) {
3580         throw new StorageException(status);
3581     }
3582
3583     public Either<Boolean, StorageOperationStatus> isComponentInUse(String componentId) {
3584         final List<EdgeLabelEnum> forbiddenEdgeLabelEnums = Arrays
3585             .asList(EdgeLabelEnum.INSTANCE_OF, EdgeLabelEnum.PROXY_OF, EdgeLabelEnum.ALLOTTED_OF);
3586         Either<GraphVertex, JanusGraphOperationStatus> vertexById = janusGraphDao.getVertexById(componentId);
3587         if (vertexById.isLeft()) {
3588             for (EdgeLabelEnum edgeLabelEnum : forbiddenEdgeLabelEnums) {
3589                 Iterator<Edge> edgeItr = vertexById.left().value().getVertex().edges(Direction.IN, edgeLabelEnum.name());
3590                 if (edgeItr != null && edgeItr.hasNext()) {
3591                     return Either.left(true);
3592                 }
3593             }
3594         }
3595         return Either.left(false);
3596     }
3597
3598     public Either<List<Component>, StorageOperationStatus> getComponentListByInvariantUuid(String componentInvariantUuid,
3599                                                                                            Map<GraphPropertyEnum, Object> additionalPropertiesToMatch) {
3600         Map<GraphPropertyEnum, Object> propertiesToMatch = new EnumMap<>(GraphPropertyEnum.class);
3601         if (MapUtils.isNotEmpty(additionalPropertiesToMatch)) {
3602             propertiesToMatch.putAll(additionalPropertiesToMatch);
3603         }
3604         propertiesToMatch.put(GraphPropertyEnum.INVARIANT_UUID, componentInvariantUuid);
3605         Either<List<GraphVertex>, JanusGraphOperationStatus> vertexEither = janusGraphDao
3606             .getByCriteria(null, propertiesToMatch, JsonParseFlagEnum.ParseMetadata);
3607         if (vertexEither.isRight()) {
3608             log.debug("Couldn't fetch metadata for component with type {} and invariantUUId {}, error: {}", componentInvariantUuid,
3609                 vertexEither.right().value());
3610             return Either.right(DaoStatusConverter.convertJanusGraphStatusToStorageStatus(vertexEither.right().value()));
3611         }
3612         List<GraphVertex> vertexList = vertexEither.isLeft() ? vertexEither.left().value() : null;
3613         if (vertexList == null || vertexList.isEmpty()) {
3614             log.debug("Component with invariantUUId {} was not found", componentInvariantUuid);
3615             return Either.right(StorageOperationStatus.NOT_FOUND);
3616         }
3617         ArrayList<Component> components = new ArrayList<>();
3618         for (GraphVertex vertex : vertexList) {
3619             Either<Component, StorageOperationStatus> toscaElementByOperation = getToscaElementByOperation(vertex);
3620             if (toscaElementByOperation.isRight()) {
3621                 log.debug("Could not fetch the following Component by Invariant UUID {}", vertex.getUniqueId());
3622                 return Either.right(toscaElementByOperation.right().value());
3623             }
3624             components.add(toscaElementByOperation.left().value());
3625         }
3626         return Either.left(components);
3627     }
3628
3629     public Either<List<Component>, StorageOperationStatus> getParentComponents(String componentId) {
3630         List<Component> parentComponents = new ArrayList<>();
3631         final List<EdgeLabelEnum> relationEdgeLabelEnums = Arrays.asList(EdgeLabelEnum.INSTANCE_OF, EdgeLabelEnum.PROXY_OF);
3632         Either<GraphVertex, JanusGraphOperationStatus> vertexById = janusGraphDao.getVertexById(componentId);
3633         if (vertexById.isLeft()) {
3634             for (EdgeLabelEnum edgeLabelEnum : relationEdgeLabelEnums) {
3635                 Either<GraphVertex, JanusGraphOperationStatus> parentVertexEither = janusGraphDao
3636                     .getParentVertex(vertexById.left().value(), edgeLabelEnum, JsonParseFlagEnum.ParseJson);
3637                 if (parentVertexEither.isLeft()) {
3638                     Either<Component, StorageOperationStatus> componentEither = getToscaElement(parentVertexEither.left().value().getUniqueId());
3639                     if (componentEither.isLeft()) {
3640                         parentComponents.add(componentEither.left().value());
3641                     }
3642                 }
3643             }
3644         }
3645         return Either.left(parentComponents);
3646     }
3647
3648     public void updateCapReqPropertiesOwnerId(String componentId) {
3649         topologyTemplateOperation.updateCapReqPropertiesOwnerId(componentId, getTopologyTemplate(componentId));
3650     }
3651
3652     public <T extends Component> Either<T, StorageOperationStatus> getLatestByServiceName(String serviceName) {
3653         return getLatestByName(GraphPropertyEnum.NAME, serviceName, null);
3654     }
3655 }