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