Improve getting Service with specific version
[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<T, StorageOperationStatus> getBySystemNameAndVersion(final ComponentTypeEnum componentType,
852                                                                                              final String systemName,
853                                                                                              final String version) {
854         final Map<GraphPropertyEnum, Object> propertiesToMatch = new EnumMap<>(GraphPropertyEnum.class);
855         final Map<GraphPropertyEnum, Object> propertiesNotToMatch = new EnumMap<>(GraphPropertyEnum.class);
856         propertiesToMatch.put(GraphPropertyEnum.SYSTEM_NAME, systemName);
857         propertiesToMatch.put(GraphPropertyEnum.VERSION, version);
858         if (componentType != null) {
859             propertiesToMatch.put(GraphPropertyEnum.COMPONENT_TYPE, componentType.name());
860         }
861         propertiesNotToMatch.put(GraphPropertyEnum.IS_DELETED, true);
862
863         final Either<List<GraphVertex>, JanusGraphOperationStatus> getResourceResult
864             = janusGraphDao.getByCriteria(null, propertiesToMatch, propertiesNotToMatch,JsonParseFlagEnum.ParseAll);
865         if (getResourceResult.isRight()) {
866             final JanusGraphOperationStatus status = getResourceResult.right().value();
867             log.debug("Failed to find resource with systemName {}, version {}. Status is {} ", systemName, version, status);
868             return Either.right(DaoStatusConverter.convertJanusGraphStatusToStorageStatus(status));
869         }
870         return getToscaElementByOperation(getResourceResult.left().value().get(0));
871     }
872
873     public <T extends Component> Either<T, StorageOperationStatus> getComponentByNameAndVersion(ComponentTypeEnum componentType, String name,
874                                                                                                 String version) {
875         return getComponentByNameAndVersion(componentType, name, version, JsonParseFlagEnum.ParseAll);
876     }
877
878     public <T extends Component> Either<T, StorageOperationStatus> getComponentByNameAndVersion(ComponentTypeEnum componentType, String name,
879                                                                                                 String version, JsonParseFlagEnum parseFlag) {
880         Map<GraphPropertyEnum, Object> hasProperties = new EnumMap<>(GraphPropertyEnum.class);
881         Map<GraphPropertyEnum, Object> hasNotProperties = new EnumMap<>(GraphPropertyEnum.class);
882         hasProperties.put(GraphPropertyEnum.NAME, name);
883         hasProperties.put(GraphPropertyEnum.VERSION, version);
884         hasNotProperties.put(GraphPropertyEnum.IS_DELETED, true);
885         if (componentType != null) {
886             hasProperties.put(GraphPropertyEnum.COMPONENT_TYPE, componentType.name());
887         }
888         Either<List<GraphVertex>, JanusGraphOperationStatus> getResourceRes = janusGraphDao
889             .getByCriteria(null, hasProperties, hasNotProperties, parseFlag);
890         if (getResourceRes.isRight()) {
891             JanusGraphOperationStatus status = getResourceRes.right().value();
892             log.debug("failed to find resource with name {}, version {}. Status is {} ", name, version, status);
893             return Either.right(DaoStatusConverter.convertJanusGraphStatusToStorageStatus(status));
894         }
895         return getToscaElementByOperation(getResourceRes.left().value().get(0));
896     }
897
898     public <T extends Component> Either<T, StorageOperationStatus> getComponentByNameAndVendorRelease(final ComponentTypeEnum componentType,
899                                                                                                       final String name, final String vendorRelease,
900                                                                                                       final JsonParseFlagEnum parseFlag,
901                                                                                                       final String modelName) {
902         Map<GraphPropertyEnum, Object> hasProperties = new EnumMap<>(GraphPropertyEnum.class);
903         Map<GraphPropertyEnum, Object> hasNotProperties = new EnumMap<>(GraphPropertyEnum.class);
904         hasProperties.put(GraphPropertyEnum.NAME, name);
905         hasNotProperties.put(GraphPropertyEnum.IS_DELETED, true);
906         if (componentType != null) {
907             hasProperties.put(GraphPropertyEnum.COMPONENT_TYPE, componentType.name());
908         }
909         Map<String, Entry<JanusGraphPredicate, Object>> predicateCriteria = getVendorVersionPredicate(vendorRelease);
910         Either<List<GraphVertex>, JanusGraphOperationStatus> getResourceRes = janusGraphDao.getByCriteria(null, hasProperties, hasNotProperties,
911             predicateCriteria, parseFlag, modelName);
912         if (getResourceRes.isRight()) {
913             JanusGraphOperationStatus status = getResourceRes.right().value();
914             log.debug("failed to find resource with name {}, version {}. Status is {} ", name, predicateCriteria, status);
915             return Either.right(DaoStatusConverter.convertJanusGraphStatusToStorageStatus(status));
916         }
917         return getToscaElementByOperation(getResourceRes.left().value().get(0));
918     }
919
920     public Either<List<CatalogComponent>, StorageOperationStatus> getCatalogOrArchiveComponents(boolean isCatalog,
921                                                                                                 List<OriginTypeEnum> excludeTypes) {
922         List<ResourceTypeEnum> excludedResourceTypes = Optional.ofNullable(excludeTypes).orElse(Collections.emptyList()).stream()
923             .filter(type -> !type.equals(OriginTypeEnum.SERVICE)).map(type -> ResourceTypeEnum.getTypeByName(type.name()))
924             .collect(Collectors.toList());
925         return topologyTemplateOperation.getElementCatalogData(isCatalog, excludedResourceTypes);
926     }
927
928     // endregion
929     public <T extends Component> Either<List<T>, StorageOperationStatus> getCatalogComponents(ComponentTypeEnum componentType,
930                                                                                               List<OriginTypeEnum> excludeTypes,
931                                                                                               boolean isHighestVersions) {
932         List<T> components = new ArrayList<>();
933         Either<List<ToscaElement>, StorageOperationStatus> catalogDataResult;
934         List<ToscaElement> toscaElements = new ArrayList<>();
935         List<ResourceTypeEnum> excludedResourceTypes = Optional.ofNullable(excludeTypes).orElse(Collections.emptyList()).stream()
936             .filter(type -> !type.equals(OriginTypeEnum.SERVICE)).map(type -> ResourceTypeEnum.getTypeByName(type.name()))
937             .collect(Collectors.toList());
938         switch (componentType) {
939             case RESOURCE:
940                 catalogDataResult = nodeTypeOperation.getElementCatalogData(ComponentTypeEnum.RESOURCE, excludedResourceTypes, isHighestVersions);
941                 if (catalogDataResult.isRight()) {
942                     return Either.right(catalogDataResult.right().value());
943                 }
944                 toscaElements = catalogDataResult.left().value();
945                 break;
946             case SERVICE:
947                 if (excludeTypes != null && excludeTypes.contains(OriginTypeEnum.SERVICE)) {
948                     break;
949                 }
950                 catalogDataResult = topologyTemplateOperation.getElementCatalogData(ComponentTypeEnum.SERVICE, null, isHighestVersions);
951                 if (catalogDataResult.isRight()) {
952                     return Either.right(catalogDataResult.right().value());
953                 }
954                 toscaElements = catalogDataResult.left().value();
955                 break;
956             default:
957                 log.debug(NOT_SUPPORTED_COMPONENT_TYPE, componentType);
958                 return Either.right(StorageOperationStatus.BAD_REQUEST);
959         }
960         toscaElements.forEach(te -> {
961             T component = ModelConverter.convertFromToscaElement(te);
962             components.add(component);
963         });
964         return Either.left(components);
965     }
966
967     public Either<List<String>, StorageOperationStatus> deleteMarkedElements(ComponentTypeEnum componentType) {
968         Either<List<GraphVertex>, StorageOperationStatus> allComponentsMarkedForDeletion;
969         switch (componentType) {
970             case RESOURCE:
971                 allComponentsMarkedForDeletion = nodeTypeOperation.getAllComponentsMarkedForDeletion(componentType);
972                 break;
973             case SERVICE:
974             case PRODUCT:
975                 allComponentsMarkedForDeletion = topologyTemplateOperation.getAllComponentsMarkedForDeletion(componentType);
976                 break;
977             default:
978                 log.debug(NOT_SUPPORTED_COMPONENT_TYPE, componentType);
979                 return Either.right(StorageOperationStatus.BAD_REQUEST);
980         }
981         if (allComponentsMarkedForDeletion.isRight()) {
982             return Either.right(allComponentsMarkedForDeletion.right().value());
983         }
984         List<GraphVertex> allMarked = allComponentsMarkedForDeletion.left().value();
985         return Either.left(checkIfInUseAndDelete(allMarked));
986     }
987
988     public List<String> deleteService(String invariantUUID, final boolean inTransaction) {
989         return deleteComponent(invariantUUID, NodeTypeEnum.Service, inTransaction);
990     }
991
992     public List<String> deleteComponent(String invariantUUID, NodeTypeEnum componentType, final boolean inTransaction) {
993         final List<GraphVertex> allServiceVerticesToDelete = findVertexListByInvariantUuid(invariantUUID);
994         List<String> affectedComponentIds = new ArrayList<>();
995         try {
996             checkNotUsed(allServiceVerticesToDelete);
997             lockAllVerticesByNodeType(allServiceVerticesToDelete, componentType);
998             for (GraphVertex elementV : allServiceVerticesToDelete) {
999                 Either<ToscaElement, StorageOperationStatus> deleteToscaElement = deleteToscaElement(elementV);
1000                 if (deleteToscaElement.isRight()) {
1001                     log.debug("Failed to delete element UniqueID {}, Name {}, error {}", elementV.getUniqueId(),
1002                         elementV.getMetadataProperties().get(GraphPropertyEnum.NAME), deleteToscaElement.right().value());
1003                     throwStorageException(deleteToscaElement.right().value());
1004                 }
1005                 affectedComponentIds.add(elementV.getUniqueId());
1006             }
1007             if (!inTransaction) {
1008                 janusGraphDao.commit();
1009             }
1010         } catch (Exception exception) {
1011             if (!inTransaction) {
1012                 janusGraphDao.rollback();
1013             }
1014             throw exception;
1015         } finally {
1016             unlockAllVerticesByNodeType(allServiceVerticesToDelete, componentType);
1017         }
1018         return affectedComponentIds;
1019     }
1020
1021     private void checkNotUsed(List<GraphVertex> vertices) {
1022         boolean isInUse = isAnyComponentInUse(vertices);
1023         if (isInUse) {
1024             Set<GraphVertex> listOfVertices = getComponentsUsingComponents(vertices);
1025             List<String> listOfStringComponents = new ArrayList<>();
1026             for (GraphVertex componentVertex : listOfVertices) {
1027                 listOfStringComponents.add(
1028                     componentVertex.getMetadataJson().get(GraphPropertyEnum.COMPONENT_TYPE.getProperty()) + " "
1029                         + componentVertex.getMetadataJson().get(GraphPropertyEnum.NAME.getProperty())
1030                 );
1031             }
1032             String stringOfComponents = String.join(", ", listOfStringComponents);
1033             throw ToscaOperationExceptionSupplier.componentInUse(stringOfComponents).get();
1034         }
1035     }
1036
1037     public List<GraphVertex> findVertexListByInvariantUuid(final String invariantUuid) {
1038         try {
1039             return janusGraphDao.findAllVertexByInvariantUuid(invariantUuid, Collections.emptyMap());
1040         } catch (final JanusGraphException e) {
1041             log.error(EcompLoggerErrorCode.DATA_ERROR, this.getClass().getName(), e.getMessage());
1042             throw new StorageException(e.getStatus());
1043         }
1044     }
1045
1046     public void commitAndCheck(String componentId) {
1047         JanusGraphOperationStatus status = janusGraphDao.commit();
1048         if (!status.equals(JanusGraphOperationStatus.OK)) {
1049             log.debug("error occurred when trying to DELETE {}. Return code is: {}", componentId, status);
1050             throwStorageException(DaoStatusConverter.convertJanusGraphStatusToStorageStatus(status));
1051         }
1052     }
1053
1054     private Set<GraphVertex> getComponentsUsingComponents(List<GraphVertex> componentVertices) {
1055         Set<GraphVertex> inUseBy = new TreeSet<>(Comparator.comparing(GraphVertex::getUniqueId));
1056         for (final GraphVertex elementV : componentVertices) {
1057             List<GraphVertex> inUseByVertex = isInUse(elementV);
1058             if (!inUseByVertex.isEmpty()) {
1059                 inUseBy.addAll(inUseByVertex);
1060             }
1061         }
1062         return inUseBy;
1063     }
1064
1065     private boolean isAnyComponentInUse(List<GraphVertex> componentVertices) {
1066         boolean isComponentInUse = false;
1067         if (log.isDebugEnabled()) {
1068             for (final GraphVertex graphVertex : componentVertices) {
1069                 if (!isInUse(graphVertex).isEmpty()) {
1070                     isComponentInUse = true;
1071                 }
1072             }
1073         } else {
1074             isComponentInUse = componentVertices.stream().anyMatch(vertex -> !isInUse(vertex).isEmpty());
1075         }
1076         return isComponentInUse;
1077     }
1078
1079     private List<GraphVertex> isInUse(GraphVertex elementV) {
1080         final List<EdgeLabelEnum> forbiddenEdgeLabelEnums = Arrays
1081             .asList(EdgeLabelEnum.INSTANCE_OF, EdgeLabelEnum.PROXY_OF, EdgeLabelEnum.ALLOTTED_OF);
1082         for (EdgeLabelEnum edgeLabelEnum : forbiddenEdgeLabelEnums) {
1083             Either<List<GraphVertex>, JanusGraphOperationStatus> inUseBy =
1084                 janusGraphDao.getParentVertices(elementV, edgeLabelEnum, JsonParseFlagEnum.ParseAll);
1085             if (inUseBy.isLeft()) {
1086                 if (log.isDebugEnabled()) {
1087                     log.debug("Element {} in use.", elementV.getUniqueId());
1088                 }
1089                 return inUseBy.left().value();
1090             }
1091         }
1092         return Collections.emptyList();
1093     }
1094
1095     private List<String> checkIfInUseAndDelete(List<GraphVertex> allMarked) {
1096         List<String> deleted = new ArrayList<>();
1097         for (GraphVertex elementV : allMarked) {
1098             boolean isAllowedToDelete = !isInUse(elementV).isEmpty();
1099             if (isAllowedToDelete) {
1100                 Either<ToscaElement, StorageOperationStatus> deleteToscaElement = deleteToscaElement(elementV);
1101                 if (deleteToscaElement.isRight()) {
1102                     log.debug("Failed to delete marked element UniqueID {}, Name {}, error {}", elementV.getUniqueId(),
1103                         elementV.getMetadataProperties().get(GraphPropertyEnum.NAME), deleteToscaElement.right().value());
1104                     continue;
1105                 }
1106                 deleted.add(elementV.getUniqueId());
1107             }
1108         }
1109         return deleted;
1110     }
1111
1112     private void lockAllVerticesByNodeType(List<GraphVertex> allVerticesToLock, NodeTypeEnum nodeType) {
1113         for (GraphVertex graphVertex : allVerticesToLock) {
1114             StorageOperationStatus storageOperationStatus = graphLockOperation.lockComponent(graphVertex.getUniqueId(), nodeType);
1115             if (!storageOperationStatus.equals(StorageOperationStatus.OK)) {
1116                 throwStorageException(storageOperationStatus);
1117             }
1118         }
1119     }
1120
1121     private void unlockAllVerticesByNodeType(List<GraphVertex> allVerticesToUnlock, NodeTypeEnum nodeType) {
1122         for (GraphVertex graphVertex : allVerticesToUnlock) {
1123             graphLockOperation.unlockComponent(graphVertex.getUniqueId(), nodeType);
1124         }
1125     }
1126
1127     public Either<List<String>, StorageOperationStatus> getAllComponentsMarkedForDeletion(ComponentTypeEnum componentType) {
1128         Either<List<GraphVertex>, StorageOperationStatus> allComponentsMarkedForDeletion;
1129         switch (componentType) {
1130             case RESOURCE:
1131                 allComponentsMarkedForDeletion = nodeTypeOperation.getAllComponentsMarkedForDeletion(componentType);
1132                 break;
1133             case SERVICE:
1134             case PRODUCT:
1135                 allComponentsMarkedForDeletion = topologyTemplateOperation.getAllComponentsMarkedForDeletion(componentType);
1136                 break;
1137             default:
1138                 log.debug(NOT_SUPPORTED_COMPONENT_TYPE, componentType);
1139                 return Either.right(StorageOperationStatus.BAD_REQUEST);
1140         }
1141         if (allComponentsMarkedForDeletion.isRight()) {
1142             return Either.right(allComponentsMarkedForDeletion.right().value());
1143         }
1144         return Either.left(allComponentsMarkedForDeletion.left().value().stream().map(GraphVertex::getUniqueId).collect(Collectors.toList()));
1145     }
1146
1147     // region - Component Update
1148     public Either<ImmutablePair<Component, String>, StorageOperationStatus> addComponentInstanceToTopologyTemplate(Component containerComponent,
1149                                                                                                                    Component origComponent,
1150                                                                                                                    ComponentInstance componentInstance,
1151                                                                                                                    boolean allowDeleted, User user) {
1152         Either<ImmutablePair<Component, String>, StorageOperationStatus> result = null;
1153         Either<ToscaElement, StorageOperationStatus> updateContainerComponentRes = null;
1154         if (StringUtils.isEmpty(componentInstance.getIcon())) {
1155             componentInstance.setIcon(origComponent.getIcon());
1156         }
1157         String nameToFindForCounter;
1158         switch (componentInstance.getOriginType()) {
1159             case ServiceProxy:
1160                 nameToFindForCounter = ValidationUtils.normaliseComponentName(componentInstance.getSourceModelName()) + PROXY_SUFFIX;
1161                 break;
1162             case ServiceSubstitution:
1163                 nameToFindForCounter = ValidationUtils.normaliseComponentName(componentInstance.getSourceModelName());
1164                 break;
1165             default:
1166                 nameToFindForCounter = origComponent.getName();
1167         }
1168         String nextComponentInstanceCounter = getNextComponentInstanceCounter(containerComponent, nameToFindForCounter);
1169         Either<ImmutablePair<TopologyTemplate, String>, StorageOperationStatus> addResult = nodeTemplateOperation
1170             .addComponentInstanceToTopologyTemplate(ModelConverter.convertToToscaElement(containerComponent),
1171                 ModelConverter.convertToToscaElement(origComponent), nextComponentInstanceCounter, componentInstance, allowDeleted, user);
1172         if (addResult.isRight()) {
1173             CommonUtility.addRecordToLog(log, LogLevelEnum.DEBUG, "Failed to add the component instance {} to container component {}. ",
1174                 componentInstance.getName(), containerComponent.getName());
1175             result = Either.right(addResult.right().value());
1176         }
1177         if (result == null) {
1178             updateContainerComponentRes = topologyTemplateOperation.getToscaElement(containerComponent.getUniqueId());
1179             if (updateContainerComponentRes.isRight()) {
1180                 CommonUtility
1181                     .addRecordToLog(log, LogLevelEnum.DEBUG, "Failed to fetch updated topology template {} with updated component instance {}. ",
1182                         containerComponent.getName(), componentInstance.getName());
1183                 result = Either.right(updateContainerComponentRes.right().value());
1184             }
1185         }
1186         if (result == null) {
1187             Component updatedComponent = ModelConverter.convertFromToscaElement(updateContainerComponentRes.left().value());
1188             String createdInstanceId = addResult.left().value().getRight();
1189             CommonUtility
1190                 .addRecordToLog(log, LogLevelEnum.TRACE, "The component instance {} has been added to container component {}. ", createdInstanceId,
1191                     updatedComponent.getName());
1192             result = Either.left(new ImmutablePair<>(updatedComponent, createdInstanceId));
1193         }
1194         return result;
1195     }
1196
1197     public void associateComponentInstancesToComponent(Component containerComponent, Map<ComponentInstance, Resource> resourcesInstancesMap,
1198                                                        boolean allowDeleted, boolean isUpdateCsar) {
1199         CommonUtility.addRecordToLog(log, LogLevelEnum.DEBUG, "Going to add component instances to component {}", containerComponent.getUniqueId());
1200         Either<GraphVertex, JanusGraphOperationStatus> metadataVertex = janusGraphDao
1201             .getVertexById(containerComponent.getUniqueId(), JsonParseFlagEnum.ParseAll);
1202         if (metadataVertex.isRight()) {
1203             JanusGraphOperationStatus status = metadataVertex.right().value();
1204             if (status == JanusGraphOperationStatus.NOT_FOUND) {
1205                 status = JanusGraphOperationStatus.INVALID_ID;
1206             }
1207             throw new StorageException(DaoStatusConverter.convertJanusGraphStatusToStorageStatus(status));
1208         }
1209         Map<String, ComponentInstanceDataDefinition> compnentInstancesMap = nodeTemplateOperation
1210             .associateComponentInstancesToComponent(containerComponent, resourcesInstancesMap, metadataVertex.left().value(), allowDeleted,
1211                 isUpdateCsar);
1212         containerComponent.setComponentInstances(ModelConverter.getComponentInstancesFromMapObject(compnentInstancesMap, containerComponent));
1213     }
1214
1215     public Either<ImmutablePair<Component, String>, StorageOperationStatus> updateComponentInstanceMetadataOfTopologyTemplate(
1216         Component containerComponent, Component origComponent, ComponentInstance componentInstance) {
1217         Either<ImmutablePair<Component, String>, StorageOperationStatus> result = null;
1218         CommonUtility.addRecordToLog(log, LogLevelEnum.TRACE,
1219             "Going to update the metadata of the component instance {} belonging to container component {}. ", componentInstance.getName(),
1220             containerComponent.getName());
1221         componentInstance.setIcon(origComponent.getIcon());
1222         Either<ImmutablePair<TopologyTemplate, String>, StorageOperationStatus> updateResult = nodeTemplateOperation
1223             .updateComponentInstanceMetadataOfTopologyTemplate(ModelConverter.convertToToscaElement(containerComponent),
1224                 ModelConverter.convertToToscaElement(origComponent), componentInstance);
1225         if (updateResult.isRight()) {
1226             CommonUtility.addRecordToLog(log, LogLevelEnum.DEBUG,
1227                 "Failed to update the metadata of the component instance {} belonging to container component {}. ", componentInstance.getName(),
1228                 containerComponent.getName());
1229             result = Either.right(updateResult.right().value());
1230         }
1231         if (result == null) {
1232             Component updatedComponent = ModelConverter.convertFromToscaElement(updateResult.left().value().getLeft());
1233             String createdInstanceId = updateResult.left().value().getRight();
1234             CommonUtility
1235                 .addRecordToLog(log, LogLevelEnum.TRACE, "The metadata of the component instance {} has been updated to container component {}. ",
1236                     createdInstanceId, updatedComponent.getName());
1237             result = Either.left(new ImmutablePair<>(updatedComponent, createdInstanceId));
1238         }
1239         return result;
1240     }
1241
1242     public Either<Component, StorageOperationStatus> updateComponentInstanceMetadataOfTopologyTemplate(Component containerComponent) {
1243         return updateComponentInstanceMetadataOfTopologyTemplate(containerComponent, new ComponentParametersView());
1244     }
1245
1246     public Either<Component, StorageOperationStatus> updateComponentInstanceMetadataOfTopologyTemplate(Component containerComponent,
1247                                                                                                        ComponentParametersView filter) {
1248         Either<Component, StorageOperationStatus> result = null;
1249         CommonUtility.addRecordToLog(log, LogLevelEnum.TRACE, "Going to update the metadata  belonging to container component {}. ",
1250             containerComponent.getName());
1251         Either<TopologyTemplate, StorageOperationStatus> updateResult = nodeTemplateOperation
1252             .updateComponentInstanceMetadataOfTopologyTemplate(ModelConverter.convertToToscaElement(containerComponent), filter);
1253         if (updateResult.isRight()) {
1254             CommonUtility.addRecordToLog(log, LogLevelEnum.DEBUG, "Failed to update the metadata  belonging to container component {}. ",
1255                 containerComponent.getName());
1256             result = Either.right(updateResult.right().value());
1257         }
1258         if (result == null) {
1259             Component updatedComponent = ModelConverter.convertFromToscaElement(updateResult.left().value());
1260             CommonUtility
1261                 .addRecordToLog(log, LogLevelEnum.TRACE, "The metadata has been updated to container component {}. ", updatedComponent.getName());
1262             result = Either.left(updatedComponent);
1263         }
1264         return result;
1265     }
1266
1267     // endregion
1268     public Either<ImmutablePair<Component, String>, StorageOperationStatus> deleteComponentInstanceFromTopologyTemplate(Component containerComponent,
1269                                                                                                                         String resourceInstanceId) {
1270         Either<ImmutablePair<Component, String>, StorageOperationStatus> result = null;
1271         CommonUtility.addRecordToLog(log, LogLevelEnum.TRACE, "Going to delete the component instance {} belonging to container component {}. ",
1272             resourceInstanceId, containerComponent.getName());
1273         Either<ImmutablePair<TopologyTemplate, String>, StorageOperationStatus> updateResult = nodeTemplateOperation
1274             .deleteComponentInstanceFromTopologyTemplate(ModelConverter.convertToToscaElement(containerComponent), resourceInstanceId);
1275         if (updateResult.isRight()) {
1276             CommonUtility.addRecordToLog(log, LogLevelEnum.DEBUG, "Failed to delete the component instance {} belonging to container component {}. ",
1277                 resourceInstanceId, containerComponent.getName());
1278             result = Either.right(updateResult.right().value());
1279         }
1280         if (result == null) {
1281             Component updatedComponent = ModelConverter.convertFromToscaElement(updateResult.left().value().getLeft());
1282             String deletedInstanceId = updateResult.left().value().getRight();
1283             CommonUtility.addRecordToLog(log, LogLevelEnum.TRACE, "The component instance {} has been deleted from container component {}. ",
1284                 deletedInstanceId, updatedComponent.getName());
1285             result = Either.left(new ImmutablePair<>(updatedComponent, deletedInstanceId));
1286         }
1287         return result;
1288     }
1289
1290     private String getNextComponentInstanceCounter(Component containerComponent, String originResourceName) {
1291         Integer nextCounter = 0;
1292         if (CollectionUtils.isNotEmpty(containerComponent.getComponentInstances())) {
1293             String normalizedName = ValidationUtils.normalizeComponentInstanceName(originResourceName);
1294             Integer maxCounter = getMaxCounterFromNamesAndIds(containerComponent, normalizedName);
1295             if (maxCounter != null) {
1296                 nextCounter = maxCounter + 1;
1297             }
1298         }
1299         return nextCounter.toString();
1300     }
1301
1302     /**
1303      * @return max counter of component instance Id's, null if not found
1304      */
1305     private Integer getMaxCounterFromNamesAndIds(Component containerComponent, String normalizedName) {
1306         List<String> countersInNames = containerComponent.getComponentInstances().stream()
1307             .filter(ci -> ci.getNormalizedName() != null && ci.getNormalizedName().startsWith(normalizedName))
1308             .map(ci -> ci.getNormalizedName().split(normalizedName)[1].replaceAll("\\D", "")).collect(Collectors.toList());
1309         List<String> countersInIds = containerComponent.getComponentInstances().stream()
1310             .filter(ci -> ci.getUniqueId() != null && ci.getUniqueId().contains(normalizedName))
1311             .map(ci -> ci.getUniqueId().split(normalizedName)[1].replaceAll("\\D", "")).collect(Collectors.toList());
1312         List<String> namesAndIdsList = new ArrayList<>(countersInNames);
1313         namesAndIdsList.addAll(countersInIds);
1314         return getMaxInteger(namesAndIdsList);
1315     }
1316
1317     private Integer getMaxInteger(List<String> counters) {
1318         Integer maxCounter = 0;
1319         Integer currCounter = null;
1320         for (String counter : counters) {
1321             try {
1322                 currCounter = Integer.parseInt(counter);
1323                 if (maxCounter < currCounter) {
1324                     maxCounter = currCounter;
1325                 }
1326             } catch (NumberFormatException e) {
1327             }
1328         }
1329         return currCounter == null ? null : maxCounter;
1330     }
1331
1332     public Either<RequirementCapabilityRelDef, StorageOperationStatus> associateResourceInstances(Component component, String componentId,
1333                                                                                                   RequirementCapabilityRelDef requirementDef) {
1334         return nodeTemplateOperation.associateResourceInstances(componentId, requirementDef);
1335     }
1336
1337     public Either<List<InputDefinition>, StorageOperationStatus> createAndAssociateInputs(Map<String, InputDefinition> inputs, String componentId) {
1338         Either<GraphVertex, JanusGraphOperationStatus> getVertexEither = janusGraphDao.getVertexById(componentId, JsonParseFlagEnum.NoParse);
1339         if (getVertexEither.isRight()) {
1340             log.debug(COULDNT_FETCH_COMPONENT_WITH_AND_UNIQUE_ID_ERROR, componentId, getVertexEither.right().value());
1341             return Either.right(DaoStatusConverter.convertJanusGraphStatusToStorageStatus(getVertexEither.right().value()));
1342         }
1343         GraphVertex vertex = getVertexEither.left().value();
1344         Map<String, PropertyDataDefinition> inputsMap = inputs.entrySet().stream()
1345             .collect(Collectors.toMap(Map.Entry::getKey, e -> new PropertyDataDefinition(e.getValue())));
1346         StorageOperationStatus status = topologyTemplateOperation.associateInputsToComponent(vertex, inputsMap, componentId);
1347         if (StorageOperationStatus.OK == status) {
1348             log.debug(INPUTS_ASSOCIATED_TO_COMPONENT_SUCCESSFULLY);
1349             List<InputDefinition> inputsResList = null;
1350             if (inputsMap != null && !inputsMap.isEmpty()) {
1351                 inputsResList = inputsMap.values().stream().map(InputDefinition::new).collect(Collectors.toList());
1352             }
1353             return Either.left(inputsResList);
1354         }
1355         return Either.right(status);
1356     }
1357
1358     public Either<List<OutputDefinition>, StorageOperationStatus> createAndAssociateOutputs(final Map<String, OutputDefinition> outputs,
1359                                                                                             final String componentId) {
1360         final Either<GraphVertex, JanusGraphOperationStatus> getVertexEither = janusGraphDao.getVertexById(componentId, JsonParseFlagEnum.NoParse);
1361         if (getVertexEither.isRight()) {
1362             log.debug(COULDNT_FETCH_COMPONENT_WITH_AND_UNIQUE_ID_ERROR, componentId, getVertexEither.right().value());
1363             return Either.right(DaoStatusConverter.convertJanusGraphStatusToStorageStatus(getVertexEither.right().value()));
1364         }
1365         final GraphVertex vertex = getVertexEither.left().value();
1366         final Map<String, OutputDefinition> outputsMap = outputs.entrySet().stream()
1367             .collect(Collectors.toMap(Map.Entry::getKey, e -> new OutputDefinition(e.getValue())));
1368         final StorageOperationStatus status = topologyTemplateOperation.associateOutputsToComponent(vertex, outputsMap, componentId);
1369         if (StorageOperationStatus.OK == status) {
1370             log.debug(OUTPUTS_ASSOCIATED_TO_COMPONENT_SUCCESSFULLY);
1371             List<OutputDefinition> outputsResList = null;
1372             if (MapUtils.isNotEmpty(outputsMap)) {
1373                 outputsResList = outputsMap.values().stream().map(OutputDefinition::new).collect(Collectors.toList());
1374             }
1375             return Either.left(outputsResList);
1376         }
1377         return Either.right(status);
1378     }
1379
1380     public Either<List<InputDefinition>, StorageOperationStatus> addInputsToComponent(Map<String, InputDefinition> inputs, String componentId) {
1381         Either<GraphVertex, JanusGraphOperationStatus> getVertexEither = janusGraphDao.getVertexById(componentId, JsonParseFlagEnum.NoParse);
1382         if (getVertexEither.isRight()) {
1383             log.debug(COULDNT_FETCH_COMPONENT_WITH_AND_UNIQUE_ID_ERROR, componentId, getVertexEither.right().value());
1384             return Either.right(DaoStatusConverter.convertJanusGraphStatusToStorageStatus(getVertexEither.right().value()));
1385         }
1386         GraphVertex vertex = getVertexEither.left().value();
1387         Map<String, PropertyDefinition> inputsMap = inputs.entrySet().stream()
1388             .collect(Collectors.toMap(Map.Entry::getKey, e -> new PropertyDefinition(e.getValue())));
1389         StorageOperationStatus status = topologyTemplateOperation
1390             .addToscaDataToToscaElement(vertex, EdgeLabelEnum.INPUTS, VertexTypeEnum.INPUTS, inputsMap, JsonPresentationFields.NAME);
1391         if (StorageOperationStatus.OK == status) {
1392             log.debug(COMPONENT_CREATED_SUCCESSFULLY);
1393             List<InputDefinition> inputsResList = null;
1394             if (inputsMap != null && !inputsMap.isEmpty()) {
1395                 inputsResList = inputsMap.values().stream().map(InputDefinition::new).collect(Collectors.toList());
1396             }
1397             return Either.left(inputsResList);
1398         }
1399         return Either.right(status);
1400     }
1401
1402     public Either<List<OutputDefinition>, StorageOperationStatus> addOutputsToComponent(Map<String, OutputDefinition> outputs, String componentId) {
1403         Either<GraphVertex, JanusGraphOperationStatus> getVertexEither = janusGraphDao.getVertexById(componentId, JsonParseFlagEnum.NoParse);
1404         if (getVertexEither.isRight()) {
1405             log.debug(COULDNT_FETCH_COMPONENT_WITH_AND_UNIQUE_ID_ERROR, componentId, getVertexEither.right().value());
1406             return Either.right(DaoStatusConverter.convertJanusGraphStatusToStorageStatus(getVertexEither.right().value()));
1407         }
1408         GraphVertex vertex = getVertexEither.left().value();
1409         Map<String, AttributeDefinition> outputsMap = outputs.entrySet().stream()
1410             .collect(Collectors.toMap(Map.Entry::getKey, e -> new AttributeDefinition(e.getValue())));
1411         StorageOperationStatus status = topologyTemplateOperation
1412             .addToscaDataToToscaElement(vertex, EdgeLabelEnum.OUTPUTS, VertexTypeEnum.OUTPUTS, outputsMap, JsonPresentationFields.NAME);
1413         if (StorageOperationStatus.OK == status) {
1414             log.debug(COMPONENT_CREATED_SUCCESSFULLY);
1415             List<OutputDefinition> outputsResList = null;
1416             if (outputsMap != null && !outputsMap.isEmpty()) {
1417                 outputsResList = outputsMap.values().stream().map(OutputDefinition::new).collect(Collectors.toList());
1418             }
1419             return Either.left(outputsResList);
1420         }
1421         return Either.right(status);
1422     }
1423
1424     /**
1425      * Add data types into a Component.
1426      *
1427      * @param dataTypes   datatypes to be added. the key should be each name of data type.
1428      * @param componentId unique ID of Component.
1429      * @return list of data types.
1430      */
1431     public Either<List<DataTypeDefinition>, StorageOperationStatus> addDataTypesToComponent(Map<String, DataTypeDefinition> dataTypes,
1432                                                                                             String componentId) {
1433         log.trace("#addDataTypesToComponent - enter, componentId={}", componentId);
1434         /* get component vertex */
1435         Either<GraphVertex, JanusGraphOperationStatus> getVertexEither = janusGraphDao
1436             .getVertexById(componentId, JsonParseFlagEnum.NoParse);
1437         if (getVertexEither.isRight()) {
1438             /* not found / error */
1439             log.debug(COULDNT_FETCH_COMPONENT_WITH_AND_UNIQUE_ID_ERROR, componentId, getVertexEither.right().value());
1440             return Either.right(DaoStatusConverter.convertJanusGraphStatusToStorageStatus(getVertexEither.right().value()));
1441         }
1442         GraphVertex vertex = getVertexEither.left().value();
1443         log.trace("#addDataTypesToComponent - get vertex ok");
1444         // convert DataTypeDefinition to DataTypeDataDefinition
1445         Map<String, DataTypeDataDefinition> dataTypeDataMap = dataTypes.entrySet().stream()
1446             .collect(Collectors.toMap(Map.Entry::getKey, e -> convertDataTypeToDataTypeData(e.getValue())));
1447         // add datatype(s) to the Component.
1448
1449         // if child vertex does not exist, it will be created.
1450         StorageOperationStatus status = topologyTemplateOperation
1451             .addToscaDataToToscaElement(vertex, EdgeLabelEnum.DATA_TYPES, VertexTypeEnum.DATA_TYPES, dataTypeDataMap, JsonPresentationFields.NAME);
1452         if (StorageOperationStatus.OK == status) {
1453             log.debug(COMPONENT_CREATED_SUCCESSFULLY);
1454             List<DataTypeDefinition> inputsResList = null;
1455             if (!dataTypes.isEmpty()) {
1456                 inputsResList = new ArrayList<>(dataTypes.values());
1457             }
1458             return Either.left(inputsResList);
1459         }
1460         log.trace("#addDataTypesToComponent - leave");
1461         return Either.right(status);
1462     }
1463
1464     private DataTypeDataDefinition convertDataTypeToDataTypeData(DataTypeDefinition dataType) {
1465         DataTypeDataDefinition dataTypeData = new DataTypeDataDefinition(dataType);
1466         if (CollectionUtils.isNotEmpty(dataType.getProperties())) {
1467             List<PropertyDataDefinition> propertyDataList = dataType.getProperties().stream().map(PropertyDataDefinition::new)
1468                 .collect(Collectors.toList());
1469             dataTypeData.setPropertiesData(propertyDataList);
1470         }
1471         // if "derivedFrom" data_type exists, copy the name to "derivedFromName"
1472         if (dataType.getDerivedFrom() != null && StringUtils.isNotEmpty(dataType.getDerivedFrom().getName())) {
1473             // if names are different, log it
1474             if (!StringUtils.equals(dataTypeData.getDerivedFromName(), dataType.getDerivedFrom().getName())) {
1475                 log.debug("#convertDataTypeToDataTypeData - derivedFromName(={}) overwritten by derivedFrom.name(={})", dataType.getDerivedFromName(),
1476                     dataType.getDerivedFrom().getName());
1477             }
1478             dataTypeData.setDerivedFromName(dataType.getDerivedFrom().getName());
1479         }
1480         // supply "name" field to toscaPresentationValue in each datatype object for DAO operations
1481         dataTypeData.setToscaPresentationValue(JsonPresentationFields.NAME, dataType.getName());
1482         return dataTypeData;
1483     }
1484
1485     public Either<List<InputDefinition>, StorageOperationStatus> getComponentInputs(String componentId) {
1486         Either<GraphVertex, JanusGraphOperationStatus> getVertexEither = janusGraphDao.getVertexById(componentId, JsonParseFlagEnum.NoParse);
1487         if (getVertexEither.isRight()) {
1488             log.debug(COULDNT_FETCH_COMPONENT_WITH_AND_UNIQUE_ID_ERROR, componentId, getVertexEither.right().value());
1489             return Either.right(DaoStatusConverter.convertJanusGraphStatusToStorageStatus(getVertexEither.right().value()));
1490         }
1491         Either<ToscaElement, StorageOperationStatus> toscaElement = topologyTemplateOperation.getToscaElement(componentId);
1492         if (toscaElement.isRight()) {
1493             return Either.right(toscaElement.right().value());
1494         }
1495         TopologyTemplate topologyTemplate = (TopologyTemplate) toscaElement.left().value();
1496         Map<String, PropertyDataDefinition> inputsMap = topologyTemplate.getInputs();
1497         List<InputDefinition> inputs = new ArrayList<>();
1498         if (MapUtils.isNotEmpty(inputsMap)) {
1499             inputs = inputsMap.values().stream().map(p -> new InputDefinition(p)).collect(Collectors.toList());
1500         }
1501         return Either.left(inputs);
1502     }
1503
1504     public Either<List<InputDefinition>, StorageOperationStatus> updateInputsToComponent(List<InputDefinition> inputs, String componentId) {
1505         Either<GraphVertex, JanusGraphOperationStatus> getVertexEither = janusGraphDao.getVertexById(componentId, JsonParseFlagEnum.NoParse);
1506         if (getVertexEither.isRight()) {
1507             log.debug(COULDNT_FETCH_COMPONENT_WITH_AND_UNIQUE_ID_ERROR, componentId, getVertexEither.right().value());
1508             return Either.right(DaoStatusConverter.convertJanusGraphStatusToStorageStatus(getVertexEither.right().value()));
1509         }
1510         GraphVertex vertex = getVertexEither.left().value();
1511         List<PropertyDataDefinition> inputsAsDataDef = inputs.stream().map(PropertyDataDefinition::new).collect(Collectors.toList());
1512         StorageOperationStatus status = topologyTemplateOperation
1513             .updateToscaDataOfToscaElement(vertex, EdgeLabelEnum.INPUTS, VertexTypeEnum.INPUTS, inputsAsDataDef, JsonPresentationFields.NAME);
1514         if (StorageOperationStatus.OK == status) {
1515             log.debug(COMPONENT_CREATED_SUCCESSFULLY);
1516             List<InputDefinition> inputsResList = null;
1517             if (CollectionUtils.isNotEmpty(inputsAsDataDef)) {
1518                 inputsResList = inputsAsDataDef.stream().map(InputDefinition::new).collect(Collectors.toList());
1519             }
1520             return Either.left(inputsResList);
1521         }
1522         return Either.right(status);
1523     }
1524
1525     public Either<List<OutputDefinition>, StorageOperationStatus> updateOutputsToComponent(List<OutputDefinition> outputs, String componentId) {
1526         Either<GraphVertex, JanusGraphOperationStatus> getVertexEither = janusGraphDao.getVertexById(componentId, JsonParseFlagEnum.NoParse);
1527         if (getVertexEither.isRight()) {
1528             log.debug(COULDNT_FETCH_COMPONENT_WITH_AND_UNIQUE_ID_ERROR, componentId, getVertexEither.right().value());
1529             return Either.right(DaoStatusConverter.convertJanusGraphStatusToStorageStatus(getVertexEither.right().value()));
1530         }
1531         GraphVertex vertex = getVertexEither.left().value();
1532         List<AttributeDataDefinition> outputsAsDataDef = outputs.stream().map(AttributeDataDefinition::new).collect(Collectors.toList());
1533         StorageOperationStatus status = topologyTemplateOperation
1534             .updateToscaDataOfToscaElement(vertex, EdgeLabelEnum.OUTPUTS, VertexTypeEnum.OUTPUTS, outputsAsDataDef, JsonPresentationFields.NAME);
1535         if (StorageOperationStatus.OK == status) {
1536             log.debug(COMPONENT_CREATED_SUCCESSFULLY);
1537             List<OutputDefinition> outputsResList = null;
1538             if (!outputsAsDataDef.isEmpty()) {
1539                 outputsResList = outputsAsDataDef.stream().map(OutputDefinition::new).collect(Collectors.toList());
1540             }
1541             return Either.left(outputsResList);
1542         }
1543         return Either.right(status);
1544     }
1545
1546     // region - ComponentInstance
1547     public Either<Map<String, List<ComponentInstanceProperty>>, StorageOperationStatus> associateComponentInstancePropertiesToComponent(
1548         Map<String, List<ComponentInstanceProperty>> instProperties, String componentId) {
1549         Either<GraphVertex, JanusGraphOperationStatus> getVertexEither = janusGraphDao.getVertexById(componentId, JsonParseFlagEnum.NoParse);
1550         if (getVertexEither.isRight()) {
1551             log.debug(COULDNT_FETCH_COMPONENT_WITH_AND_UNIQUE_ID_ERROR, componentId, getVertexEither.right().value());
1552             return Either.right(DaoStatusConverter.convertJanusGraphStatusToStorageStatus(getVertexEither.right().value()));
1553         }
1554         GraphVertex vertex = getVertexEither.left().value();
1555         Map<String, MapPropertiesDataDefinition> instPropsMap = new HashMap<>();
1556         if (instProperties != null) {
1557             MapPropertiesDataDefinition propertiesMap;
1558             for (Entry<String, List<ComponentInstanceProperty>> entry : instProperties.entrySet()) {
1559                 propertiesMap = new MapPropertiesDataDefinition();
1560                 propertiesMap.setMapToscaDataDefinition(
1561                     entry.getValue().stream().map(PropertyDataDefinition::new).collect(Collectors.toMap(PropertyDataDefinition::getName, e -> e)));
1562                 instPropsMap.put(entry.getKey(), propertiesMap);
1563             }
1564         }
1565         StorageOperationStatus status = topologyTemplateOperation.associateInstPropertiesToComponent(vertex, instPropsMap);
1566         if (StorageOperationStatus.OK == status) {
1567             log.debug(COMPONENT_CREATED_SUCCESSFULLY);
1568             return Either.left(instProperties);
1569         }
1570         return Either.right(status);
1571     }
1572
1573     /**
1574      * saves the instInputs as the updated instance inputs of the component container in DB
1575      */
1576     public Either<Map<String, List<ComponentInstanceInput>>, StorageOperationStatus> updateComponentInstanceInputsToComponent(
1577         Map<String, List<ComponentInstanceInput>> instInputs, String componentId) {
1578         if (instInputs == null || instInputs.isEmpty()) {
1579             return Either.left(instInputs);
1580         }
1581         StorageOperationStatus status;
1582         for (Entry<String, List<ComponentInstanceInput>> inputsPerIntance : instInputs.entrySet()) {
1583             List<ComponentInstanceInput> toscaDataListPerInst = inputsPerIntance.getValue();
1584             List<String> pathKeysPerInst = new ArrayList<>();
1585             pathKeysPerInst.add(inputsPerIntance.getKey());
1586             status = topologyTemplateOperation
1587                 .updateToscaDataDeepElementsOfToscaElement(componentId, EdgeLabelEnum.INST_INPUTS, VertexTypeEnum.INST_INPUTS, toscaDataListPerInst,
1588                     pathKeysPerInst, JsonPresentationFields.NAME);
1589             if (status != StorageOperationStatus.OK) {
1590                 log.debug("Failed to update component instance inputs for instance {} in component {} edge type {} error {}",
1591                     inputsPerIntance.getKey(), componentId, EdgeLabelEnum.INST_INPUTS, status);
1592                 return Either.right(status);
1593             }
1594         }
1595         return Either.left(instInputs);
1596     }
1597
1598     /**
1599      * saves the instProps as the updated instance properties of the component container in DB
1600      */
1601     public Either<Map<String, List<ComponentInstanceProperty>>, StorageOperationStatus> updateComponentInstancePropsToComponent(
1602         Map<String, List<ComponentInstanceProperty>> instProps, String componentId) {
1603         if (instProps == null || instProps.isEmpty()) {
1604             return Either.left(instProps);
1605         }
1606         StorageOperationStatus status;
1607         for (Entry<String, List<ComponentInstanceProperty>> propsPerIntance : instProps.entrySet()) {
1608             List<ComponentInstanceProperty> toscaDataListPerInst = propsPerIntance.getValue();
1609             List<String> pathKeysPerInst = new ArrayList<>();
1610             pathKeysPerInst.add(propsPerIntance.getKey());
1611             status = topologyTemplateOperation
1612                 .updateToscaDataDeepElementsOfToscaElement(componentId, EdgeLabelEnum.INST_PROPERTIES, VertexTypeEnum.INST_PROPERTIES,
1613                     toscaDataListPerInst, pathKeysPerInst, JsonPresentationFields.NAME);
1614             if (status != StorageOperationStatus.OK) {
1615                 log.debug("Failed to update component instance inputs for instance {} in component {} edge type {} error {}",
1616                     propsPerIntance.getKey(), componentId, EdgeLabelEnum.INST_PROPERTIES, status);
1617                 return Either.right(status);
1618             }
1619         }
1620         return Either.left(instProps);
1621     }
1622
1623     public Either<Map<String, List<ComponentInstanceInput>>, StorageOperationStatus> associateComponentInstanceInputsToComponent(
1624         Map<String, List<ComponentInstanceInput>> instInputs, String componentId) {
1625         Either<GraphVertex, JanusGraphOperationStatus> getVertexEither = janusGraphDao.getVertexById(componentId, JsonParseFlagEnum.NoParse);
1626         if (getVertexEither.isRight()) {
1627             log.debug(COULDNT_FETCH_COMPONENT_WITH_AND_UNIQUE_ID_ERROR, componentId, getVertexEither.right().value());
1628             return Either.right(DaoStatusConverter.convertJanusGraphStatusToStorageStatus(getVertexEither.right().value()));
1629         }
1630         GraphVertex vertex = getVertexEither.left().value();
1631         Map<String, MapPropertiesDataDefinition> instPropsMap = new HashMap<>();
1632         if (instInputs != null) {
1633             MapPropertiesDataDefinition propertiesMap;
1634             for (Entry<String, List<ComponentInstanceInput>> entry : instInputs.entrySet()) {
1635                 propertiesMap = new MapPropertiesDataDefinition();
1636                 propertiesMap.setMapToscaDataDefinition(
1637                     entry.getValue().stream().map(PropertyDataDefinition::new).collect(Collectors.toMap(PropertyDataDefinition::getName, e -> e)));
1638                 instPropsMap.put(entry.getKey(), propertiesMap);
1639             }
1640         }
1641         StorageOperationStatus status = topologyTemplateOperation.associateInstInputsToComponent(vertex, instPropsMap);
1642         if (StorageOperationStatus.OK == status) {
1643             log.debug(COMPONENT_CREATED_SUCCESSFULLY);
1644             return Either.left(instInputs);
1645         }
1646         return Either.right(status);
1647     }
1648
1649     public Either<Map<String, MapInterfaceDataDefinition>, StorageOperationStatus> associateComponentInstanceInterfacesToComponent(
1650             Map<String, Map<String, InterfaceDefinition>> instInterfaces,
1651             String componentId
1652     ) {
1653         Either<GraphVertex, JanusGraphOperationStatus> getVertexEither = janusGraphDao.getVertexById(
1654                 componentId,
1655                 JsonParseFlagEnum.NoParse
1656         );
1657         if (getVertexEither.isRight()) {
1658             log.debug(
1659                     COULDNT_FETCH_COMPONENT_WITH_AND_UNIQUE_ID_ERROR,
1660                     componentId,
1661                     getVertexEither.right().value()
1662             );
1663             return Either.right(
1664                     DaoStatusConverter.convertJanusGraphStatusToStorageStatus(
1665                             getVertexEither.right().value()
1666                     )
1667             );
1668         }
1669         GraphVertex vertex = getVertexEither.left().value();
1670         Map<String, MapInterfaceDataDefinition> instInterfacesMap = new HashMap<>();
1671         if (instInterfaces != null) {
1672             MapInterfaceDataDefinition interfacesMap = new MapInterfaceDataDefinition();
1673             for (Map.Entry<String, Map<String, InterfaceDefinition>> entryInstances : instInterfaces.entrySet()) {
1674                 Map<String, InterfaceDataDefinition> incomingInterfacesMap = entryInstances.getValue().entrySet().stream()
1675                         .collect(Collectors.toMap(e -> e.getKey(), e -> e.getValue()));
1676                 interfacesMap.setMapToscaDataDefinition(incomingInterfacesMap);
1677                 instInterfacesMap.put(entryInstances.getKey(), interfacesMap);
1678             }
1679         }
1680         StorageOperationStatus status = topologyTemplateOperation.associateInstInterfacesToComponent(
1681                 vertex,
1682                 instInterfacesMap
1683         );
1684         if (StorageOperationStatus.OK == status) {
1685             log.debug(COMPONENT_CREATED_SUCCESSFULLY);
1686             return Either.left(instInterfacesMap);
1687         }
1688         return Either.right(status);
1689     }
1690
1691     public Either<Map<String, List<ComponentInstanceInput>>, StorageOperationStatus> addComponentInstanceInputsToComponent(
1692         Component containerComponent, Map<String, List<ComponentInstanceInput>> instProperties) {
1693         requireNonNull(instProperties);
1694         StorageOperationStatus status;
1695         for (Entry<String, List<ComponentInstanceInput>> entry : instProperties.entrySet()) {
1696             List<ComponentInstanceInput> props = entry.getValue();
1697             String componentInstanceId = entry.getKey();
1698             if (!isEmpty(props)) {
1699                 for (ComponentInstanceInput property : props) {
1700                     List<ComponentInstanceInput> componentInstancesInputs = containerComponent.getComponentInstancesInputs().get(componentInstanceId);
1701                     Optional<ComponentInstanceInput> instanceProperty = componentInstancesInputs.stream()
1702                         .filter(p -> p.getName().equals(property.getName())).findAny();
1703                     if (instanceProperty.isPresent()) {
1704                         status = updateComponentInstanceInput(containerComponent, componentInstanceId, property);
1705                     } else {
1706                         status = addComponentInstanceInput(containerComponent, componentInstanceId, property);
1707                     }
1708                     if (status != StorageOperationStatus.OK) {
1709                         log.debug("Failed to update instance input {} for instance {} error {} ", property, componentInstanceId, status);
1710                         return Either.right(status);
1711                     } else {
1712                         log.trace("instance input {} for instance {} updated", property, componentInstanceId);
1713                     }
1714                 }
1715             }
1716         }
1717         return Either.left(instProperties);
1718     }
1719
1720     public Either<Map<String, List<ComponentInstanceOutput>>, StorageOperationStatus> addComponentInstanceOutputsToComponent(
1721         Component containerComponent, Map<String, List<ComponentInstanceOutput>> instOutputs) {
1722         requireNonNull(instOutputs);
1723         StorageOperationStatus status;
1724         for (final Entry<String, List<ComponentInstanceOutput>> entry : instOutputs.entrySet()) {
1725             final List<ComponentInstanceOutput> outputs = entry.getValue();
1726             final String componentInstanceId = entry.getKey();
1727             if (!isEmpty(outputs)) {
1728                 for (final ComponentInstanceOutput output : outputs) {
1729                     final List<ComponentInstanceOutput> componentInstanceOutputs = containerComponent.getComponentInstancesOutputs()
1730                         .get(componentInstanceId);
1731                     final Optional<ComponentInstanceOutput> componentInstanceOutput = componentInstanceOutputs.stream()
1732                         .filter(p -> p.getName().equals(output.getName())).findAny();
1733                     if (componentInstanceOutput.isPresent()) {
1734                         status = updateComponentInstanceOutput(containerComponent, componentInstanceId, output);
1735                     } else {
1736                         status = addComponentInstanceOutput(containerComponent, componentInstanceId, output);
1737                     }
1738                     if (status != StorageOperationStatus.OK) {
1739                         log.debug("Failed to update instance output {} for instance {} error {} ", output, componentInstanceId, status);
1740                         return Either.right(status);
1741                     } else {
1742                         log.trace("instance output {} for instance {} updated", output, componentInstanceId);
1743                     }
1744                 }
1745             }
1746         }
1747         return Either.left(instOutputs);
1748     }
1749
1750     public Either<Map<String, List<ComponentInstanceProperty>>, StorageOperationStatus> addComponentInstancePropertiesToComponent(
1751         Component containerComponent, Map<String, List<ComponentInstanceProperty>> instProperties) {
1752         requireNonNull(instProperties);
1753         for (Entry<String, List<ComponentInstanceProperty>> entry : instProperties.entrySet()) {
1754             List<ComponentInstanceProperty> props = entry.getValue();
1755             String componentInstanceId = entry.getKey();
1756             List<ComponentInstanceProperty> originalComponentInstProps = containerComponent.getComponentInstancesProperties()
1757                 .get(componentInstanceId);
1758             Map<String, List<CapabilityDefinition>> containerComponentCapabilities = containerComponent.getCapabilities();
1759             if (isEmpty(props)) {
1760                 continue;
1761             }
1762             for (ComponentInstanceProperty property : props) {
1763                 StorageOperationStatus status = null;
1764                 String propertyParentUniqueId = property.getParentUniqueId();
1765                 Optional<CapabilityDefinition> capPropDefinition = getPropertyCapability(propertyParentUniqueId, containerComponent);
1766                 if (capPropDefinition.isPresent() && MapUtils.isNotEmpty(containerComponentCapabilities)) {
1767                     status = populateAndUpdateInstanceCapProperty(containerComponent, componentInstanceId, containerComponentCapabilities, property,
1768                         capPropDefinition.get());
1769                 }
1770                 if (status == null) {
1771                     status = updateOrAddComponentInstanceProperty(containerComponent, componentInstanceId, originalComponentInstProps, property);
1772                 }
1773                 if (status != StorageOperationStatus.OK) {
1774                     return Either.right(status);
1775                 }
1776             }
1777         }
1778         return Either.left(instProperties);
1779     }
1780
1781     public Either<Map<String, List<ComponentInstanceAttribute>>, StorageOperationStatus> addComponentInstanceAttributesToComponent(
1782         final Component containerComponent, final Map<String, List<ComponentInstanceAttribute>> instProperties) {
1783         requireNonNull(instProperties);
1784         for (final Entry<String, List<ComponentInstanceAttribute>> entry : instProperties.entrySet()) {
1785             final List<ComponentInstanceAttribute> props = entry.getValue();
1786             if (isEmpty(props)) {
1787                 continue;
1788             }
1789             final String componentInstanceId = entry.getKey();
1790             final List<ComponentInstanceAttribute> originalComponentInstProps = containerComponent.getComponentInstancesAttributes()
1791                 .get(componentInstanceId);
1792             for (final ComponentInstanceAttribute property : props) {
1793                 final StorageOperationStatus status = updateOrAddComponentInstanceAttribute(containerComponent, componentInstanceId,
1794                     originalComponentInstProps, property);
1795                 if (status != StorageOperationStatus.OK) {
1796                     return Either.right(status);
1797                 }
1798             }
1799         }
1800         return Either.left(instProperties);
1801     }
1802
1803     private StorageOperationStatus populateAndUpdateInstanceCapProperty(Component containerComponent, String componentInstanceId,
1804                                                                         Map<String, List<CapabilityDefinition>> containerComponentCapabilities,
1805                                                                         ComponentInstanceProperty property,
1806                                                                         CapabilityDefinition capabilityDefinition) {
1807         List<CapabilityDefinition> capabilityDefinitions = containerComponentCapabilities.get(capabilityDefinition.getType());
1808         if (CollectionUtils.isEmpty(capabilityDefinitions)) {
1809             return null;
1810         }
1811         Optional<CapabilityDefinition> capDefToGetProp = capabilityDefinitions.stream()
1812             .filter(cap -> cap.getUniqueId().equals(capabilityDefinition.getUniqueId()) && cap.getPath().size() == 1).findAny();
1813         if (capDefToGetProp.isPresent()) {
1814             return updateInstanceCapabilityProperty(containerComponent, componentInstanceId, property, capDefToGetProp.get());
1815         }
1816         return null;
1817     }
1818
1819     private StorageOperationStatus updateOrAddComponentInstanceProperty(Component containerComponent, String componentInstanceId,
1820                                                                         List<ComponentInstanceProperty> originalComponentInstProps,
1821                                                                         ComponentInstanceProperty property) {
1822         StorageOperationStatus status;
1823         // check if the property already exists or not
1824         Optional<ComponentInstanceProperty> instanceProperty = originalComponentInstProps.stream()
1825             .filter(p -> p.getUniqueId().equals(property.getUniqueId())).findAny();
1826         if (instanceProperty.isPresent()) {
1827             status = updateComponentInstanceProperty(containerComponent, componentInstanceId, property);
1828         } else {
1829             status = addComponentInstanceProperty(containerComponent, componentInstanceId, property);
1830         }
1831         if (status != StorageOperationStatus.OK) {
1832             log.debug("Failed to update instance property {} for instance {} error {} ", property, componentInstanceId, status);
1833         }
1834         return status;
1835     }
1836
1837     private StorageOperationStatus updateOrAddComponentInstanceAttribute(Component containerComponent, String componentInstanceId,
1838                                                                          List<ComponentInstanceAttribute> originalComponentInstProps,
1839                                                                          ComponentInstanceAttribute property) {
1840         StorageOperationStatus status;
1841         // check if the property already exists or not
1842         Optional<ComponentInstanceAttribute> instanceProperty = originalComponentInstProps.stream()
1843             .filter(p -> p.getUniqueId().equals(property.getUniqueId())).findAny();
1844         if (instanceProperty.isPresent()) {
1845             status = updateComponentInstanceAttribute(containerComponent, componentInstanceId, property);
1846         } else {
1847             status = addComponentInstanceAttribute(containerComponent, componentInstanceId, property);
1848         }
1849         if (status != StorageOperationStatus.OK) {
1850             log.debug("Failed to update instance property {} for instance {} error {} ", property, componentInstanceId, status);
1851         }
1852         return status;
1853     }
1854
1855     public StorageOperationStatus updateInstanceCapabilityProperty(Component containerComponent, String componentInstanceId,
1856                                                                    ComponentInstanceProperty property, CapabilityDefinition capabilityDefinition) {
1857         Optional<ComponentInstance> fetchedCIOptional = containerComponent.getComponentInstanceById(componentInstanceId);
1858         if (!fetchedCIOptional.isPresent()) {
1859             return StorageOperationStatus.GENERAL_ERROR;
1860         }
1861         Either<Component, StorageOperationStatus> getComponentRes = getToscaFullElement(fetchedCIOptional.get().getComponentUid());
1862         if (getComponentRes.isRight()) {
1863             return StorageOperationStatus.GENERAL_ERROR;
1864         }
1865         Optional<Component> componentOptional = isNodeServiceProxy(getComponentRes.left().value());
1866         String propOwner;
1867         if (!componentOptional.isPresent()) {
1868             propOwner = componentInstanceId;
1869         } else {
1870             propOwner = fetchedCIOptional.get().getSourceModelUid();
1871         }
1872         StorageOperationStatus status;
1873         StringBuilder sb = new StringBuilder(componentInstanceId);
1874         sb.append(ModelConverter.CAP_PROP_DELIM).append(propOwner).append(ModelConverter.CAP_PROP_DELIM).append(capabilityDefinition.getType())
1875             .append(ModelConverter.CAP_PROP_DELIM).append(capabilityDefinition.getName());
1876         String capKey = sb.toString();
1877         status = updateComponentInstanceCapabiltyProperty(containerComponent, componentInstanceId, capKey, property);
1878         if (status != StorageOperationStatus.OK) {
1879             log.debug("Failed to update instance capability property {} for instance {} error {} ", property, componentInstanceId, status);
1880             return status;
1881         }
1882         return StorageOperationStatus.OK;
1883     }
1884
1885     private Optional<Component> isNodeServiceProxy(Component component) {
1886         if (component.getComponentType().equals(ComponentTypeEnum.SERVICE)) {
1887             return Optional.empty();
1888         }
1889         Resource resource = (Resource) component;
1890         ResourceTypeEnum resType = resource.getResourceType();
1891         if (resType.equals(ResourceTypeEnum.ServiceProxy)) {
1892             return Optional.of(component);
1893         }
1894         return Optional.empty();
1895     }
1896
1897     public StorageOperationStatus associateCapabilitiesToService(Map<String, ListCapabilityDataDefinition> capabilities, String componentId) {
1898         Either<GraphVertex, JanusGraphOperationStatus> getVertexEither = janusGraphDao.getVertexById(componentId, JsonParseFlagEnum.NoParse);
1899         if (getVertexEither.isRight()) {
1900             log.debug(COULDNT_FETCH_COMPONENT_WITH_AND_UNIQUE_ID_ERROR, componentId, getVertexEither.right().value());
1901             return DaoStatusConverter.convertJanusGraphStatusToStorageStatus(getVertexEither.right().value());
1902         }
1903         GraphVertex vertex = getVertexEither.left().value();
1904         if (MapUtils.isNotEmpty(capabilities)) {
1905             Either<GraphVertex, StorageOperationStatus> associateElementToData = topologyTemplateOperation
1906                 .associateElementToData(vertex, VertexTypeEnum.CAPABILITIES, EdgeLabelEnum.CAPABILITIES, capabilities);
1907             if (associateElementToData.isRight()) {
1908                 return associateElementToData.right().value();
1909             }
1910         }
1911         return StorageOperationStatus.OK;
1912     }
1913
1914     public StorageOperationStatus associateRequirementsToService(Map<String, ListRequirementDataDefinition> requirements, String componentId) {
1915         Either<GraphVertex, JanusGraphOperationStatus> getVertexEither = janusGraphDao.getVertexById(componentId, JsonParseFlagEnum.NoParse);
1916         if (getVertexEither.isRight()) {
1917             log.debug(COULDNT_FETCH_COMPONENT_WITH_AND_UNIQUE_ID_ERROR, componentId, getVertexEither.right().value());
1918             return DaoStatusConverter.convertJanusGraphStatusToStorageStatus(getVertexEither.right().value());
1919         }
1920         GraphVertex vertex = getVertexEither.left().value();
1921         if (MapUtils.isNotEmpty(requirements)) {
1922             Either<GraphVertex, StorageOperationStatus> associateElementToData = topologyTemplateOperation
1923                 .associateElementToData(vertex, VertexTypeEnum.REQUIREMENTS, EdgeLabelEnum.REQUIREMENTS, requirements);
1924             if (associateElementToData.isRight()) {
1925                 return associateElementToData.right().value();
1926             }
1927         }
1928         return StorageOperationStatus.OK;
1929     }
1930
1931     public StorageOperationStatus associateDeploymentArtifactsToInstances(Map<String, Map<String, ArtifactDefinition>> instDeploymentArtifacts,
1932                                                                           Component component, User user) {
1933         Either<GraphVertex, JanusGraphOperationStatus> getVertexEither = janusGraphDao
1934             .getVertexById(component.getUniqueId(), JsonParseFlagEnum.NoParse);
1935         if (getVertexEither.isRight()) {
1936             log.debug(COULDNT_FETCH_COMPONENT_WITH_AND_UNIQUE_ID_ERROR, component.getUniqueId(), getVertexEither.right().value());
1937             return DaoStatusConverter.convertJanusGraphStatusToStorageStatus(getVertexEither.right().value());
1938         }
1939         GraphVertex vertex = getVertexEither.left().value();
1940         Map<String, MapArtifactDataDefinition> instArtMap = new HashMap<>();
1941         if (instDeploymentArtifacts != null) {
1942             MapArtifactDataDefinition artifactsMap;
1943             for (Entry<String, Map<String, ArtifactDefinition>> entry : instDeploymentArtifacts.entrySet()) {
1944                 Map<String, ArtifactDefinition> artList = entry.getValue();
1945                 Map<String, ArtifactDataDefinition> artifacts = artList.entrySet().stream()
1946                     .collect(Collectors.toMap(Map.Entry::getKey, e -> new ArtifactDataDefinition(e.getValue())));
1947                 artifactsMap = nodeTemplateOperation
1948                     .prepareInstDeploymentArtifactPerInstance(artifacts, entry.getKey(), user, NodeTemplateOperation.HEAT_VF_ENV_NAME);
1949                 instArtMap.put(entry.getKey(), artifactsMap);
1950             }
1951         }
1952         ModelConverter.setComponentInstancesDeploymentArtifactsToComponent(instArtMap, component);
1953         return topologyTemplateOperation.associateInstDeploymentArtifactsToComponent(vertex, instArtMap);
1954     }
1955
1956     public StorageOperationStatus associateArtifactsToInstances(Map<String, Map<String, ArtifactDefinition>> instArtifacts, Component component) {
1957         Either<GraphVertex, JanusGraphOperationStatus> getVertexEither = janusGraphDao
1958             .getVertexById(component.getUniqueId(), JsonParseFlagEnum.NoParse);
1959         if (getVertexEither.isRight()) {
1960             log.debug(COULDNT_FETCH_COMPONENT_WITH_AND_UNIQUE_ID_ERROR, component.getUniqueId(), getVertexEither.right().value());
1961             return DaoStatusConverter.convertJanusGraphStatusToStorageStatus(getVertexEither.right().value());
1962         }
1963         GraphVertex vertex = getVertexEither.left().value();
1964         Map<String, MapArtifactDataDefinition> instArtMap = new HashMap<>();
1965         if (instArtifacts != null) {
1966             MapArtifactDataDefinition artifactsMap;
1967             for (Entry<String, Map<String, ArtifactDefinition>> entry : instArtifacts.entrySet()) {
1968                 Map<String, ArtifactDefinition> artList = entry.getValue();
1969                 Map<String, ArtifactDataDefinition> artifacts = artList.entrySet().stream()
1970                     .collect(Collectors.toMap(Map.Entry::getKey, e -> new ArtifactDataDefinition(e.getValue())));
1971                 artifactsMap = new MapArtifactDataDefinition(artifacts);
1972                 instArtMap.put(entry.getKey(), artifactsMap);
1973             }
1974         }
1975         ModelConverter.setComponentInstancesInformationalArtifactsToComponent(instArtMap, component);
1976         return topologyTemplateOperation.associateInstArtifactsToComponent(vertex, instArtMap);
1977     }
1978
1979     public StorageOperationStatus associateInstAttributeToComponentToInstances(Map<String, List<AttributeDefinition>> instArttributes,
1980                                                                                Component component) {
1981         Either<GraphVertex, JanusGraphOperationStatus> getVertexEither = janusGraphDao
1982             .getVertexById(component.getUniqueId(), JsonParseFlagEnum.NoParse);
1983         if (getVertexEither.isRight()) {
1984             log.debug(COULDNT_FETCH_COMPONENT_WITH_AND_UNIQUE_ID_ERROR, component.getUniqueId(), getVertexEither.right().value());
1985             return DaoStatusConverter.convertJanusGraphStatusToStorageStatus(getVertexEither.right().value());
1986         }
1987         GraphVertex vertex = getVertexEither.left().value();
1988         Map<String, MapAttributesDataDefinition> instAttr = new HashMap<>();
1989         if (instArttributes != null) {
1990             MapAttributesDataDefinition attributesMap;
1991             for (Entry<String, List<AttributeDefinition>> entry : instArttributes.entrySet()) {
1992                 final List<AttributeDefinition> value = entry.getValue();
1993                 attributesMap = new MapAttributesDataDefinition();
1994                 attributesMap.setMapToscaDataDefinition(
1995                     value.stream().map(AttributeDefinition::new).collect(Collectors.toMap(AttributeDefinition::getName, e -> e)));
1996                 instAttr.put(entry.getKey(), attributesMap);
1997             }
1998         }
1999         setComponentInstanceAttributesOnComponent(component, instAttr);
2000         return topologyTemplateOperation.associateInstAttributeToComponent(vertex, instAttr);
2001     }
2002
2003     // endregion
2004     private void setComponentInstanceAttributesOnComponent(Component resource, Map<String, MapAttributesDataDefinition> instAttr) {
2005         Map<String, List<ComponentInstanceAttribute>> componentInstancesAttributes = resource.getComponentInstancesAttributes();
2006         if (componentInstancesAttributes == null) {
2007             componentInstancesAttributes = new HashMap<>();
2008         }
2009         componentInstancesAttributes.putAll(ModelConverter.getComponentInstancesAttributes(instAttr));
2010         resource.setComponentInstancesAttributes(componentInstancesAttributes);
2011     }
2012
2013     public StorageOperationStatus associateOrAddCalculatedCapReq(Map<ComponentInstance, Map<String, List<CapabilityDefinition>>> instCapabilties,
2014                                                                  Map<ComponentInstance, Map<String, List<RequirementDefinition>>> instReg,
2015                                                                  Component component) {
2016         Either<GraphVertex, JanusGraphOperationStatus> getVertexEither = janusGraphDao
2017             .getVertexById(component.getUniqueId(), JsonParseFlagEnum.NoParse);
2018         if (getVertexEither.isRight()) {
2019             log.debug(COULDNT_FETCH_COMPONENT_WITH_AND_UNIQUE_ID_ERROR, component.getUniqueId(), getVertexEither.right().value());
2020             return DaoStatusConverter.convertJanusGraphStatusToStorageStatus(getVertexEither.right().value());
2021         }
2022         GraphVertex vertex = getVertexEither.left().value();
2023         Map<String, MapListRequirementDataDefinition> calcRequirements = new HashMap<>();
2024         Map<String, MapListCapabilityDataDefinition> calcCapabilty = new HashMap<>();
2025         Map<String, MapCapabilityProperty> calculatedCapabilitiesProperties = new HashMap<>();
2026         if (instCapabilties != null) {
2027             for (Entry<ComponentInstance, Map<String, List<CapabilityDefinition>>> entry : instCapabilties.entrySet()) {
2028                 Map<String, List<CapabilityDefinition>> caps = entry.getValue();
2029                 Map<String, ListCapabilityDataDefinition> mapToscaDataDefinition = new HashMap<>();
2030                 for (Entry<String, List<CapabilityDefinition>> instCapability : caps.entrySet()) {
2031                     mapToscaDataDefinition.put(instCapability.getKey(), new ListCapabilityDataDefinition(
2032                         instCapability.getValue().stream().map(CapabilityDataDefinition::new).collect(Collectors.toList())));
2033                 }
2034                 ComponentInstanceDataDefinition componentInstance = new ComponentInstanceDataDefinition(entry.getKey());
2035                 MapListCapabilityDataDefinition capMap = nodeTemplateOperation
2036                     .prepareCalculatedCapabiltyForNodeType(mapToscaDataDefinition, componentInstance);
2037                 MapCapabilityProperty mapCapabilityProperty = ModelConverter
2038                     .convertToMapOfMapCapabiltyProperties(caps, componentInstance.getUniqueId(), true);
2039                 calcCapabilty.put(entry.getKey().getUniqueId(), capMap);
2040                 calculatedCapabilitiesProperties.put(entry.getKey().getUniqueId(), mapCapabilityProperty);
2041             }
2042         }
2043         if (instReg != null) {
2044             for (Entry<ComponentInstance, Map<String, List<RequirementDefinition>>> entry : instReg.entrySet()) {
2045                 Map<String, List<RequirementDefinition>> req = entry.getValue();
2046                 Map<String, ListRequirementDataDefinition> mapToscaDataDefinition = new HashMap<>();
2047                 for (Entry<String, List<RequirementDefinition>> instReq : req.entrySet()) {
2048                     mapToscaDataDefinition.put(instReq.getKey(), new ListRequirementDataDefinition(
2049                         instReq.getValue().stream().map(RequirementDataDefinition::new).collect(Collectors.toList())));
2050                 }
2051                 MapListRequirementDataDefinition reqMap = nodeTemplateOperation
2052                     .prepareCalculatedRequirementForNodeType(mapToscaDataDefinition, new ComponentInstanceDataDefinition(entry.getKey()));
2053                 String componentInstanceId = entry.getKey().getUniqueId();
2054                 calcRequirements.put(componentInstanceId, reqMap);
2055             }
2056         }
2057         StorageOperationStatus storageOperationStatus = topologyTemplateOperation
2058             .associateOrAddCalcCapReqToComponent(vertex, calcRequirements, calcCapabilty, calculatedCapabilitiesProperties);
2059         updateInstancesCapAndReqOnComponentFromDB(component);
2060         return storageOperationStatus;
2061     }
2062
2063     public StorageOperationStatus updateCalculatedCapabilitiesRequirements(
2064         final Map<ComponentInstance, Map<String, List<CapabilityDefinition>>> instCapabilties,
2065         final Map<ComponentInstance, Map<String, List<RequirementDefinition>>> instReg,
2066         final Component component) {
2067         StorageOperationStatus storageOperationStatus = StorageOperationStatus.OK;
2068         if (instCapabilties != null) {
2069             for (Entry<ComponentInstance, Map<String, List<CapabilityDefinition>>> entry : instCapabilties.entrySet()) {
2070                 final Map<String, List<CapabilityDefinition>> cap = entry.getValue();
2071                 for (List<CapabilityDefinition> capabilityList : cap.values()) {
2072                     for (CapabilityDefinition capability : capabilityList) {
2073                         nodeTemplateOperation.updateComponentInstanceCapabilities(component.getUniqueId(), entry.getKey().getUniqueId(), capability);
2074                     }
2075                 }
2076             }
2077         }
2078         if (instReg != null) {
2079             for (Entry<ComponentInstance, Map<String, List<RequirementDefinition>>> entry : instReg.entrySet()) {
2080                 final Map<String, List<RequirementDefinition>> req = entry.getValue();
2081                 for (List<RequirementDefinition> requirementList : req.values()) {
2082                     for (RequirementDefinition requirement : requirementList) {
2083                         storageOperationStatus = nodeTemplateOperation.updateComponentInstanceRequirement(component.getUniqueId(),
2084                             entry.getKey().getUniqueId(), requirement);
2085                         if (storageOperationStatus != StorageOperationStatus.OK) {
2086                             return storageOperationStatus;
2087                         }
2088                     }
2089                 }
2090             }
2091         }
2092         return storageOperationStatus;
2093     }
2094
2095     private void updateInstancesCapAndReqOnComponentFromDB(Component component) {
2096         ComponentParametersView componentParametersView = new ComponentParametersView(true);
2097         componentParametersView.setIgnoreCapabilities(false);
2098         componentParametersView.setIgnoreRequirements(false);
2099         componentParametersView.setIgnoreCapabiltyProperties(false);
2100         componentParametersView.setIgnoreComponentInstances(false);
2101         Either<Component, StorageOperationStatus> componentEither = getToscaElement(component.getUniqueId(), componentParametersView);
2102         if (componentEither.isRight()) {
2103             throw new StorageException(StorageOperationStatus.NOT_FOUND);
2104         }
2105         Component updatedComponent = componentEither.left().value();
2106         component.setCapabilities(updatedComponent.getCapabilities());
2107         component.setRequirements(updatedComponent.getRequirements());
2108         component.setComponentInstancesRelations(updatedComponent.getComponentInstancesRelations());
2109         component.setComponentInstances(updatedComponent.getComponentInstances());
2110     }
2111
2112     private Either<List<Service>, StorageOperationStatus> getLatestVersionNonCheckoutServicesMetadataOnly(Map<GraphPropertyEnum, Object> hasProps,
2113                                                                                                           Map<GraphPropertyEnum, Object> hasNotProps,
2114                                                                                                           String modelName) {
2115         List<Service> services = new ArrayList<>();
2116         List<LifecycleStateEnum> states = new ArrayList<>();
2117         // include props
2118         hasProps.put(GraphPropertyEnum.COMPONENT_TYPE, ComponentTypeEnum.SERVICE.name());
2119         hasProps.put(GraphPropertyEnum.IS_HIGHEST_VERSION, true);
2120         if (modelName != null) {
2121             hasProps.put(GraphPropertyEnum.MODEL, modelName);
2122         }
2123         // exclude props
2124         states.add(LifecycleStateEnum.NOT_CERTIFIED_CHECKOUT);
2125         hasNotProps.put(GraphPropertyEnum.STATE, states);
2126         hasNotProps.put(GraphPropertyEnum.IS_DELETED, true);
2127         hasNotProps.put(GraphPropertyEnum.IS_ARCHIVED, true);
2128         return fetchServicesByCriteria(services, hasProps, hasNotProps, modelName);
2129     }
2130
2131     private Either<List<Component>, StorageOperationStatus> getLatestVersionNotAbstractToscaElementsMetadataOnly(final boolean isAbstract,
2132                                                                                                                  final ComponentTypeEnum componentTypeEnum,
2133                                                                                                                  final String internalComponentType,
2134                                                                                                                  final VertexTypeEnum vertexType,
2135                                                                                                                  final String modelName,
2136                                                                                                                  final boolean includeNormativeExtensionModels) {
2137         List<Service> services = null;
2138         Map<GraphPropertyEnum, Object> hasProps = new EnumMap<>(GraphPropertyEnum.class);
2139         Map<GraphPropertyEnum, Object> hasNotProps = new EnumMap<>(GraphPropertyEnum.class);
2140         fillPropsMap(hasProps, hasNotProps, internalComponentType, componentTypeEnum, isAbstract, vertexType, modelName);
2141         Either<List<GraphVertex>, JanusGraphOperationStatus> getRes = janusGraphDao
2142             .getByCriteria(vertexType, hasProps, hasNotProps, JsonParseFlagEnum.ParseMetadata, modelName, includeNormativeExtensionModels);
2143         if (getRes.isRight() && !JanusGraphOperationStatus.NOT_FOUND.equals(getRes.right().value())) {
2144             return Either.right(DaoStatusConverter.convertJanusGraphStatusToStorageStatus(getRes.right().value()));
2145         }
2146         // region -> Fetch non checked-out services
2147         if (internalComponentType != null && internalComponentType.toLowerCase().trim().equals(SERVICE) && VertexTypeEnum.NODE_TYPE == vertexType) {
2148             Either<List<Service>, StorageOperationStatus> result = getLatestVersionNonCheckoutServicesMetadataOnly(
2149                 new EnumMap<>(GraphPropertyEnum.class), new EnumMap<>(GraphPropertyEnum.class), modelName);
2150             if (result.isRight()) {
2151                 log.debug("Failed to fetch services for");
2152                 return Either.right(result.right().value());
2153             }
2154             services = result.left().value();
2155             if (log.isTraceEnabled() && isEmpty(services)) {
2156                 log.trace("No relevant services available");
2157             }
2158         }
2159         // endregion
2160         List<Component> nonAbstractLatestComponents = new ArrayList<>();
2161         ComponentParametersView params = new ComponentParametersView(true);
2162         params.setIgnoreAllVersions(false);
2163         if (getRes.isLeft()) {
2164             for (GraphVertex vertexComponent : getRes.left().value()) {
2165                 Either<ToscaElement, StorageOperationStatus> componentRes = topologyTemplateOperation
2166                     .getLightComponent(vertexComponent, componentTypeEnum, params);
2167                 if (componentRes.isRight()) {
2168                     log.debug("Failed to fetch light element for {} error {}", vertexComponent.getUniqueId(), componentRes.right().value());
2169                     return Either.right(componentRes.right().value());
2170                 } else {
2171                     Component component = ModelConverter.convertFromToscaElement(componentRes.left().value());
2172                     nonAbstractLatestComponents.add(component);
2173                 }
2174             }
2175         }
2176         if (CollectionUtils.isNotEmpty(services)) {
2177             nonAbstractLatestComponents.addAll(services);
2178         }
2179         return Either.left(nonAbstractLatestComponents);
2180     }
2181
2182     public Either<ComponentMetadataData, StorageOperationStatus> getLatestComponentMetadataByUuid(String componentUuid, JsonParseFlagEnum parseFlag,
2183                                                                                                   Boolean isHighest) {
2184         Either<ComponentMetadataData, StorageOperationStatus> result;
2185         Map<GraphPropertyEnum, Object> hasProperties = new EnumMap<>(GraphPropertyEnum.class);
2186         hasProperties.put(GraphPropertyEnum.UUID, componentUuid);
2187         if (isHighest != null) {
2188             hasProperties.put(GraphPropertyEnum.IS_HIGHEST_VERSION, isHighest);
2189         }
2190         Map<GraphPropertyEnum, Object> propertiesNotToMatch = new EnumMap<>(GraphPropertyEnum.class);
2191         propertiesNotToMatch.put(GraphPropertyEnum.IS_DELETED, true);
2192         propertiesNotToMatch.put(GraphPropertyEnum.IS_ARCHIVED, true); //US382674, US382683
2193         Either<List<GraphVertex>, JanusGraphOperationStatus> getRes = janusGraphDao
2194             .getByCriteria(null, hasProperties, propertiesNotToMatch, parseFlag);
2195         if (getRes.isRight()) {
2196             result = Either.right(DaoStatusConverter.convertJanusGraphStatusToStorageStatus(getRes.right().value()));
2197         } else {
2198             List<ComponentMetadataData> latestVersionList = getRes.left().value().stream().map(ModelConverter::convertToComponentMetadata)
2199                 .collect(Collectors.toList());
2200             ComponentMetadataData latestVersion = latestVersionList.size() == 1 ? latestVersionList.get(0) : latestVersionList.stream().max(
2201                 (c1, c2) -> Double.compare(Double.parseDouble(c1.getMetadataDataDefinition().getVersion()),
2202                     Double.parseDouble(c2.getMetadataDataDefinition().getVersion()))).get();
2203             result = Either.left(latestVersion);
2204         }
2205         return result;
2206     }
2207
2208     public Either<ComponentMetadataData, StorageOperationStatus> getComponentMetadata(String componentId) {
2209         Either<ComponentMetadataData, StorageOperationStatus> result;
2210         Either<GraphVertex, JanusGraphOperationStatus> getRes = janusGraphDao.getVertexById(componentId, JsonParseFlagEnum.ParseMetadata);
2211         if (getRes.isRight()) {
2212             result = Either.right(DaoStatusConverter.convertJanusGraphStatusToStorageStatus(getRes.right().value()));
2213         } else {
2214             ComponentMetadataData componentMetadata = ModelConverter.convertToComponentMetadata(getRes.left().value());
2215             result = Either.left(componentMetadata);
2216         }
2217         return result;
2218     }
2219
2220     public Either<List<Component>, StorageOperationStatus> getLatestVersionNotAbstractComponents(boolean isAbstract,
2221                                                                                                  ComponentTypeEnum componentTypeEnum,
2222                                                                                                  String internalComponentType,
2223                                                                                                  List<String> componentUids) {
2224         List<Component> components = new ArrayList<>();
2225         if (componentUids == null) {
2226             Either<List<String>, StorageOperationStatus> componentUidsRes = getComponentUids(isAbstract, componentTypeEnum, internalComponentType);
2227             if (componentUidsRes.isRight()) {
2228                 return Either.right(componentUidsRes.right().value());
2229             }
2230             componentUids = componentUidsRes.left().value();
2231         }
2232         if (!isEmpty(componentUids)) {
2233             for (String componentUid : componentUids) {
2234                 ComponentParametersView componentParametersView = buildComponentViewForNotAbstract();
2235                 if ("vl".equalsIgnoreCase(internalComponentType)) {
2236                     componentParametersView.setIgnoreCapabilities(false);
2237                     componentParametersView.setIgnoreRequirements(false);
2238                 }
2239                 Either<ToscaElement, StorageOperationStatus> getToscaElementRes = nodeTemplateOperation.getToscaElementOperation(componentTypeEnum)
2240                     .getLightComponent(componentUid, componentTypeEnum, componentParametersView);
2241                 if (getToscaElementRes.isRight()) {
2242                     log.debug("Failed to fetch resource for error is {}", getToscaElementRes.right().value());
2243                     return Either.right(getToscaElementRes.right().value());
2244                 }
2245                 Component component = ModelConverter.convertFromToscaElement(getToscaElementRes.left().value());
2246                 nullifySomeComponentProperties(component);
2247                 components.add(component);
2248             }
2249         }
2250         return Either.left(components);
2251     }
2252
2253     public void nullifySomeComponentProperties(Component component) {
2254         component.setContactId(null);
2255         component.setCreationDate(null);
2256         component.setCreatorUserId(null);
2257         component.setCreatorFullName(null);
2258         component.setLastUpdateDate(null);
2259         component.setLastUpdaterUserId(null);
2260         component.setLastUpdaterFullName(null);
2261         component.setNormalizedName(null);
2262     }
2263
2264     private Either<List<String>, StorageOperationStatus> getComponentUids(boolean isAbstract, ComponentTypeEnum componentTypeEnum,
2265                                                                           String internalComponentType) {
2266         Either<List<Component>, StorageOperationStatus> getToscaElementsRes = getLatestVersionNotAbstractMetadataOnly(isAbstract, componentTypeEnum,
2267             internalComponentType, null, false);
2268         if (getToscaElementsRes.isRight()) {
2269             return Either.right(getToscaElementsRes.right().value());
2270         }
2271         List<Component> collection = getToscaElementsRes.left().value();
2272         List<String> componentUids;
2273         if (collection == null) {
2274             componentUids = new ArrayList<>();
2275         } else {
2276             componentUids = collection.stream().map(Component::getUniqueId).collect(Collectors.toList());
2277         }
2278         return Either.left(componentUids);
2279     }
2280
2281     private ComponentParametersView buildComponentViewForNotAbstract() {
2282         ComponentParametersView componentParametersView = new ComponentParametersView();
2283         componentParametersView.disableAll();
2284         componentParametersView.setIgnoreCategories(false);
2285         componentParametersView.setIgnoreAllVersions(false);
2286         return componentParametersView;
2287     }
2288
2289     public Either<Boolean, StorageOperationStatus> validateComponentNameExists(String name, ResourceTypeEnum resourceType,
2290                                                                                ComponentTypeEnum componentType) {
2291         Either<Boolean, StorageOperationStatus> result = validateComponentNameUniqueness(name, resourceType, componentType);
2292         if (result.isLeft()) {
2293             result = Either.left(!result.left().value());
2294         }
2295         return result;
2296     }
2297
2298     public Either<Boolean, StorageOperationStatus> validateComponentNameUniqueness(String name, ResourceTypeEnum resourceType,
2299                                                                                    ComponentTypeEnum componentType) {
2300         String normalizedName = ValidationUtils.normaliseComponentName(name);
2301         Either<List<GraphVertex>, JanusGraphOperationStatus> vertexEither = janusGraphDao
2302             .getByCriteria(getVertexTypeEnum(resourceType), propertiesToMatch(normalizedName, componentType), JsonParseFlagEnum.NoParse);
2303         if (vertexEither.isRight() && vertexEither.right().value() != JanusGraphOperationStatus.NOT_FOUND) {
2304             log.debug("failed to get vertex from graph with property normalizedName: {}", normalizedName);
2305             return Either.right(DaoStatusConverter.convertJanusGraphStatusToStorageStatus(vertexEither.right().value()));
2306         }
2307         return Either.left(CollectionUtils.isEmpty(vertexEither.isLeft() ? vertexEither.left().value() : null));
2308     }
2309
2310     public Either<Boolean, StorageOperationStatus> validateComponentNameAndModelExists(final String resourceName, final String model,
2311                                                                                        final ResourceTypeEnum resourceType,
2312                                                                                        final ComponentTypeEnum componentType) {
2313         Either<Boolean, StorageOperationStatus> result = validateComponentNameAndModelUniqueness(resourceName, model, resourceType, componentType);
2314         if (result.isLeft()) {
2315             result = Either.left(!result.left().value());
2316         }
2317         return result;
2318     }
2319
2320     private Either<Boolean, StorageOperationStatus> validateComponentNameAndModelUniqueness(final String resourceName, final String modelName,
2321                                                                                             final ResourceTypeEnum resourceType,
2322                                                                                             final ComponentTypeEnum componentType) {
2323         final String normalizedName = ValidationUtils.normaliseComponentName(resourceName);
2324         final Either<List<GraphVertex>, JanusGraphOperationStatus> vertexEither = janusGraphDao
2325             .getByCriteria(getVertexTypeEnum(resourceType), propertiesToMatch(normalizedName, componentType), null, null, JsonParseFlagEnum.NoParse,
2326                 modelName);
2327         if (vertexEither.isRight() && vertexEither.right().value() != JanusGraphOperationStatus.NOT_FOUND) {
2328             log.debug("failed to get vertex from graph with property normalizedName: {} and model: {}", normalizedName, modelName);
2329             return Either.right(DaoStatusConverter.convertJanusGraphStatusToStorageStatus(vertexEither.right().value()));
2330         }
2331         return Either.left(CollectionUtils.isEmpty(vertexEither.isLeft() ? vertexEither.left().value().stream()
2332             .collect(Collectors.toList()) : null));
2333     }
2334
2335     private VertexTypeEnum getVertexTypeEnum(final ResourceTypeEnum resourceType) {
2336         return ModelConverter.isAtomicComponent(resourceType) ? VertexTypeEnum.NODE_TYPE : VertexTypeEnum.TOPOLOGY_TEMPLATE;
2337     }
2338
2339     private Map<GraphPropertyEnum, Object> propertiesToMatch(final String normalizedName, final ComponentTypeEnum componentType) {
2340         final Map<GraphPropertyEnum, Object> properties = new EnumMap<>(GraphPropertyEnum.class);
2341         properties.put(GraphPropertyEnum.NORMALIZED_NAME, normalizedName);
2342         properties.put(GraphPropertyEnum.COMPONENT_TYPE, componentType.name());
2343         return properties;
2344     }
2345
2346     private void fillNodeTypePropsMap(final Map<GraphPropertyEnum, Object> hasProps, final Map<GraphPropertyEnum, Object> hasNotProps,
2347                                       final String internalComponentType, String modelName) {
2348         final Configuration configuration = ConfigurationManager.getConfigurationManager().getConfiguration();
2349         final List<String> allowedTypes;
2350         if (ComponentTypeEnum.SERVICE.getValue().equalsIgnoreCase(internalComponentType)) {
2351             allowedTypes = containerInstanceTypesData.getServiceAllowedList(modelName);
2352         } else {
2353             final ResourceTypeEnum resourceType = ResourceTypeEnum.getTypeIgnoreCase(internalComponentType);
2354             allowedTypes = containerInstanceTypesData.getComponentAllowedList(ComponentTypeEnum.RESOURCE, resourceType);
2355         }
2356         final List<String> allResourceTypes = configuration.getResourceTypes();
2357         if (allowedTypes == null) {
2358             hasNotProps.put(GraphPropertyEnum.RESOURCE_TYPE, allResourceTypes);
2359             return;
2360         }
2361         if (ResourceTypeEnum.VL.getValue().equalsIgnoreCase(internalComponentType)) {
2362             hasProps.put(GraphPropertyEnum.RESOURCE_TYPE, allowedTypes);
2363         } else {
2364             final List<String> notAllowedTypes = allResourceTypes.stream().filter(s -> !allowedTypes.contains(s)).collect(Collectors.toList());
2365             hasNotProps.put(GraphPropertyEnum.RESOURCE_TYPE, notAllowedTypes);
2366         }
2367     }
2368
2369     private void fillTopologyTemplatePropsMap(Map<GraphPropertyEnum, Object> hasProps, Map<GraphPropertyEnum, Object> hasNotProps,
2370                                               ComponentTypeEnum componentTypeEnum) {
2371         switch (componentTypeEnum) {
2372             case RESOURCE:
2373                 hasProps.put(GraphPropertyEnum.COMPONENT_TYPE, ComponentTypeEnum.RESOURCE.name());
2374                 break;
2375             case SERVICE:
2376                 hasProps.put(GraphPropertyEnum.COMPONENT_TYPE, ComponentTypeEnum.SERVICE.name());
2377                 break;
2378             default:
2379                 break;
2380         }
2381         hasNotProps.put(GraphPropertyEnum.RESOURCE_TYPE, ResourceTypeEnum.CVFC.name());
2382     }
2383
2384     private void fillPropsMap(Map<GraphPropertyEnum, Object> hasProps, Map<GraphPropertyEnum, Object> hasNotProps, String internalComponentType,
2385                               ComponentTypeEnum componentTypeEnum, boolean isAbstract, VertexTypeEnum internalVertexType, String modelName) {
2386         hasNotProps.put(GraphPropertyEnum.STATE, LifecycleStateEnum.NOT_CERTIFIED_CHECKOUT.name());
2387         hasNotProps.put(GraphPropertyEnum.IS_DELETED, true);
2388         hasNotProps.put(GraphPropertyEnum.IS_ARCHIVED, true);
2389         hasProps.put(GraphPropertyEnum.IS_HIGHEST_VERSION, true);
2390
2391         if (VertexTypeEnum.NODE_TYPE == internalVertexType) {
2392             hasProps.put(GraphPropertyEnum.IS_ABSTRACT, isAbstract);
2393             if (internalComponentType != null) {
2394                 fillNodeTypePropsMap(hasProps, hasNotProps, internalComponentType, modelName);
2395             }
2396         } else {
2397             fillTopologyTemplatePropsMap(hasProps, hasNotProps, componentTypeEnum);
2398         }
2399     }
2400
2401     private List<VertexTypeEnum> getInternalVertexTypes(ComponentTypeEnum componentTypeEnum, String internalComponentType) {
2402         List<VertexTypeEnum> internalVertexTypes = new ArrayList<>();
2403         if (ComponentTypeEnum.RESOURCE == componentTypeEnum) {
2404             internalVertexTypes.add(VertexTypeEnum.NODE_TYPE);
2405         }
2406         if (ComponentTypeEnum.SERVICE == componentTypeEnum || SERVICE.equalsIgnoreCase(internalComponentType) || VF.equalsIgnoreCase(
2407             internalComponentType)) {
2408             internalVertexTypes.add(VertexTypeEnum.TOPOLOGY_TEMPLATE);
2409         }
2410         return internalVertexTypes;
2411     }
2412
2413     public Either<List<Component>, StorageOperationStatus> getLatestVersionNotAbstractMetadataOnly(boolean isAbstract,
2414                                                                                                    final ComponentTypeEnum componentTypeEnum,
2415                                                                                                    final String internalComponentType,
2416                                                                                                    final String modelName,
2417                                                                                                    final boolean includeNormativeExtensionModels) {
2418         List<VertexTypeEnum> internalVertexTypes = getInternalVertexTypes(componentTypeEnum, internalComponentType);
2419         List<Component> result = new ArrayList<>();
2420         for (VertexTypeEnum vertexType : internalVertexTypes) {
2421             Either<List<Component>, StorageOperationStatus> listByVertexType = getLatestVersionNotAbstractToscaElementsMetadataOnly(isAbstract,
2422                 componentTypeEnum, internalComponentType, vertexType, modelName, includeNormativeExtensionModels);
2423             if (listByVertexType.isRight()) {
2424                 return listByVertexType;
2425             }
2426             result.addAll(listByVertexType.left().value());
2427         }
2428         return Either.left(result);
2429     }
2430
2431     private Either<List<Component>, StorageOperationStatus> getLatestComponentListByUuid(String componentUuid,
2432                                                                                          Map<GraphPropertyEnum, Object> additionalPropertiesToMatch) {
2433         Map<GraphPropertyEnum, Object> propertiesToMatch = new EnumMap<>(GraphPropertyEnum.class);
2434         if (additionalPropertiesToMatch != null) {
2435             propertiesToMatch.putAll(additionalPropertiesToMatch);
2436         }
2437         propertiesToMatch.put(GraphPropertyEnum.IS_HIGHEST_VERSION, true);
2438         return getComponentListByUuid(componentUuid, propertiesToMatch);
2439     }
2440
2441     public Either<Component, StorageOperationStatus> getComponentByUuidAndVersion(String componentUuid, String version) {
2442         Map<GraphPropertyEnum, Object> propertiesToMatch = new EnumMap<>(GraphPropertyEnum.class);
2443         propertiesToMatch.put(GraphPropertyEnum.UUID, componentUuid);
2444         propertiesToMatch.put(GraphPropertyEnum.VERSION, version);
2445         Map<GraphPropertyEnum, Object> propertiesNotToMatch = new EnumMap<>(GraphPropertyEnum.class);
2446         propertiesNotToMatch.put(GraphPropertyEnum.IS_DELETED, true);
2447         Either<List<GraphVertex>, JanusGraphOperationStatus> vertexEither = janusGraphDao
2448             .getByCriteria(null, propertiesToMatch, propertiesNotToMatch, JsonParseFlagEnum.ParseAll);
2449         if (vertexEither.isRight()) {
2450             return Either.right(DaoStatusConverter.convertJanusGraphStatusToStorageStatus(vertexEither.right().value()));
2451         }
2452         List<GraphVertex> vertexList = vertexEither.isLeft() ? vertexEither.left().value() : null;
2453         if (vertexList == null || vertexList.isEmpty() || vertexList.size() > 1) {
2454             return Either.right(StorageOperationStatus.NOT_FOUND);
2455         }
2456         return getToscaElementByOperation(vertexList.get(0));
2457     }
2458
2459     public Either<List<Component>, StorageOperationStatus> getComponentListByUuid(String componentUuid,
2460                                                                                   Map<GraphPropertyEnum, Object> additionalPropertiesToMatch) {
2461         Map<GraphPropertyEnum, Object> propertiesToMatch = new EnumMap<>(GraphPropertyEnum.class);
2462         if (additionalPropertiesToMatch != null) {
2463             propertiesToMatch.putAll(additionalPropertiesToMatch);
2464         }
2465         propertiesToMatch.put(GraphPropertyEnum.UUID, componentUuid);
2466         Map<GraphPropertyEnum, Object> propertiesNotToMatch = new EnumMap<>(GraphPropertyEnum.class);
2467         propertiesNotToMatch.put(GraphPropertyEnum.IS_DELETED, true);
2468         propertiesNotToMatch.put(GraphPropertyEnum.IS_ARCHIVED, true); //US382674, US382683
2469         Either<List<GraphVertex>, JanusGraphOperationStatus> vertexEither = janusGraphDao
2470             .getByCriteria(null, propertiesToMatch, propertiesNotToMatch, JsonParseFlagEnum.ParseAll);
2471         if (vertexEither.isRight()) {
2472             log.debug("Couldn't fetch metadata for component with uuid {}, error: {}", componentUuid, vertexEither.right().value());
2473             return Either.right(DaoStatusConverter.convertJanusGraphStatusToStorageStatus(vertexEither.right().value()));
2474         }
2475         List<GraphVertex> vertexList = vertexEither.isLeft() ? vertexEither.left().value() : null;
2476         if (vertexList == null || vertexList.isEmpty()) {
2477             log.debug("Component with uuid {} was not found", componentUuid);
2478             return Either.right(StorageOperationStatus.NOT_FOUND);
2479         }
2480         ArrayList<Component> latestComponents = new ArrayList<>();
2481         for (GraphVertex vertex : vertexList) {
2482             Either<Component, StorageOperationStatus> toscaElementByOperation = getToscaElementByOperation(vertex);
2483             if (toscaElementByOperation.isRight()) {
2484                 log.debug("Could not fetch the following Component by UUID {}", vertex.getUniqueId());
2485                 return Either.right(toscaElementByOperation.right().value());
2486             }
2487             latestComponents.add(toscaElementByOperation.left().value());
2488         }
2489         if (latestComponents.size() > 1) {
2490             for (Component component : latestComponents) {
2491                 if (Boolean.TRUE.equals(component.isHighestVersion())) {
2492                     LinkedList<Component> highestComponent = new LinkedList<>();
2493                     highestComponent.add(component);
2494                     return Either.left(highestComponent);
2495                 }
2496             }
2497         }
2498         return Either.left(latestComponents);
2499     }
2500
2501     public Either<Component, StorageOperationStatus> getLatestServiceByUuid(String serviceUuid) {
2502         Map<GraphPropertyEnum, Object> propertiesToMatch = new EnumMap<>(GraphPropertyEnum.class);
2503         propertiesToMatch.put(GraphPropertyEnum.COMPONENT_TYPE, ComponentTypeEnum.SERVICE.name());
2504         return getLatestComponentByUuid(serviceUuid, propertiesToMatch);
2505     }
2506
2507     public Either<Component, StorageOperationStatus> getLatestComponentByUuid(String componentUuid) {
2508         return getLatestComponentByUuid(componentUuid, null);
2509     }
2510
2511     public Either<Component, StorageOperationStatus> getLatestComponentByUuid(String componentUuid,
2512                                                                               Map<GraphPropertyEnum, Object> propertiesToMatch) {
2513         Either<List<Component>, StorageOperationStatus> latestVersionListEither = getLatestComponentListByUuid(componentUuid, propertiesToMatch);
2514         if (latestVersionListEither.isRight()) {
2515             return Either.right(latestVersionListEither.right().value());
2516         }
2517         List<Component> latestVersionList = latestVersionListEither.left().value();
2518         if (latestVersionList.isEmpty()) {
2519             return Either.right(StorageOperationStatus.NOT_FOUND);
2520         }
2521         Component component = latestVersionList.size() == 1 ? latestVersionList.get(0)
2522             : latestVersionList.stream().max((c1, c2) -> Double.compare(Double.parseDouble(c1.getVersion()), Double.parseDouble(c2.getVersion())))
2523                 .get();
2524         return Either.left(component);
2525     }
2526
2527     public Either<List<Resource>, StorageOperationStatus> getAllCertifiedResources(boolean isAbstract, Boolean isHighest) {
2528         List<Resource> resources = new ArrayList<>();
2529         Map<GraphPropertyEnum, Object> propertiesToMatch = new EnumMap<>(GraphPropertyEnum.class);
2530         Map<GraphPropertyEnum, Object> propertiesNotToMatch = new EnumMap<>(GraphPropertyEnum.class);
2531         propertiesToMatch.put(GraphPropertyEnum.IS_ABSTRACT, isAbstract);
2532         if (isHighest != null) {
2533             propertiesToMatch.put(GraphPropertyEnum.IS_HIGHEST_VERSION, isHighest);
2534         }
2535         propertiesToMatch.put(GraphPropertyEnum.STATE, LifecycleStateEnum.CERTIFIED.name());
2536         propertiesToMatch.put(GraphPropertyEnum.COMPONENT_TYPE, ComponentTypeEnum.RESOURCE.name());
2537         propertiesNotToMatch.put(GraphPropertyEnum.IS_DELETED, true);
2538         Either<List<GraphVertex>, JanusGraphOperationStatus> getResourcesRes = janusGraphDao
2539             .getByCriteria(null, propertiesToMatch, propertiesNotToMatch, JsonParseFlagEnum.ParseAll);
2540         if (getResourcesRes.isRight()) {
2541             log.debug("Failed to fetch all certified resources. Status is {}", getResourcesRes.right().value());
2542             return Either.right(DaoStatusConverter.convertJanusGraphStatusToStorageStatus(getResourcesRes.right().value()));
2543         }
2544         List<GraphVertex> resourceVerticies = getResourcesRes.left().value();
2545         for (GraphVertex resourceV : resourceVerticies) {
2546             Either<Resource, StorageOperationStatus> getResourceRes = getToscaElement(resourceV);
2547             if (getResourceRes.isRight()) {
2548                 return Either.right(getResourceRes.right().value());
2549             }
2550             resources.add(getResourceRes.left().value());
2551         }
2552         return Either.left(resources);
2553     }
2554
2555     public <T extends Component> Either<T, StorageOperationStatus> getLatestByNameAndVersion(String name, String version,
2556                                                                                              JsonParseFlagEnum parseFlag, String model) {
2557         Either<T, StorageOperationStatus> result;
2558         Map<GraphPropertyEnum, Object> hasProperties = new EnumMap<>(GraphPropertyEnum.class);
2559         Map<GraphPropertyEnum, Object> hasNotProperties = new EnumMap<>(GraphPropertyEnum.class);
2560         hasProperties.put(GraphPropertyEnum.NAME, name);
2561         hasProperties.put(GraphPropertyEnum.VERSION, version);
2562         hasProperties.put(GraphPropertyEnum.IS_HIGHEST_VERSION, true);
2563         hasNotProperties.put(GraphPropertyEnum.IS_DELETED, true);
2564         Either<List<GraphVertex>, JanusGraphOperationStatus> getResourceRes = janusGraphDao
2565             .getByCriteria(null, hasProperties, hasNotProperties, parseFlag, model);
2566         if (getResourceRes.isRight()) {
2567             JanusGraphOperationStatus status = getResourceRes.right().value();
2568             log.debug("failed to find resource with name {}, version {}. Status is {} ", name, version, status);
2569             result = Either.right(DaoStatusConverter.convertJanusGraphStatusToStorageStatus(status));
2570             return result;
2571         }
2572         return getToscaElementByOperation(getResourceRes.left().value().get(0));
2573     }
2574
2575     public Either<Resource, StorageOperationStatus> getLatestComponentByCsarOrName(ComponentTypeEnum componentType, String csarUUID,
2576                                                                                    String systemName) {
2577         return getLatestComponentByCsarOrName(componentType, csarUUID, systemName, JsonParseFlagEnum.ParseAll);
2578     }
2579
2580     public Either<Resource, StorageOperationStatus> getLatestComponentByCsarOrName(ComponentTypeEnum componentType, String csarUUID,
2581                                                                                    String systemName, JsonParseFlagEnum parseFlag) {
2582         Map<GraphPropertyEnum, Object> props = new EnumMap<>(GraphPropertyEnum.class);
2583         Map<GraphPropertyEnum, Object> propsHasNot = new EnumMap<>(GraphPropertyEnum.class);
2584         props.put(GraphPropertyEnum.CSAR_UUID, csarUUID);
2585         props.put(GraphPropertyEnum.IS_HIGHEST_VERSION, true);
2586         if (componentType != null) {
2587             props.put(GraphPropertyEnum.COMPONENT_TYPE, componentType.name());
2588         }
2589         propsHasNot.put(GraphPropertyEnum.IS_DELETED, true);
2590         GraphVertex resourceMetadataData = null;
2591         List<GraphVertex> resourceMetadataDataList = null;
2592         Either<List<GraphVertex>, JanusGraphOperationStatus> byCsar = janusGraphDao
2593             .getByCriteria(null, props, propsHasNot, JsonParseFlagEnum.ParseMetadata);
2594         if (byCsar.isRight()) {
2595             if (JanusGraphOperationStatus.NOT_FOUND == byCsar.right().value()) {
2596                 // Fix Defect DE256036
2597                 if (StringUtils.isEmpty(systemName)) {
2598                     return Either.right(DaoStatusConverter.convertJanusGraphStatusToStorageStatus(JanusGraphOperationStatus.NOT_FOUND));
2599                 }
2600                 props.clear();
2601                 props.put(GraphPropertyEnum.IS_HIGHEST_VERSION, true);
2602                 props.put(GraphPropertyEnum.SYSTEM_NAME, systemName);
2603                 Either<List<GraphVertex>, JanusGraphOperationStatus> bySystemname = janusGraphDao
2604                     .getByCriteria(null, props, JsonParseFlagEnum.ParseMetadata);
2605                 if (bySystemname.isRight()) {
2606                     log.debug("getLatestResourceByCsarOrName - Failed to find by system name {}  error {} ", systemName,
2607                         bySystemname.right().value());
2608                     return Either.right(DaoStatusConverter.convertJanusGraphStatusToStorageStatus(bySystemname.right().value()));
2609                 }
2610                 if (bySystemname.left().value().size() > 2) {
2611                     log.debug(
2612                         "getLatestResourceByCsarOrName - getByCriteria(by system name) must return only 2 latest version, but was returned - {}",
2613                         bySystemname.left().value().size());
2614                     return Either.right(StorageOperationStatus.GENERAL_ERROR);
2615                 }
2616                 resourceMetadataDataList = bySystemname.left().value();
2617                 if (resourceMetadataDataList.size() == 1) {
2618                     resourceMetadataData = resourceMetadataDataList.get(0);
2619                 } else {
2620                     for (GraphVertex curResource : resourceMetadataDataList) {
2621                         if (!((String) curResource.getJsonMetadataField(JsonPresentationFields.LIFECYCLE_STATE)).equals("CERTIFIED")) {
2622                             resourceMetadataData = curResource;
2623                             break;
2624                         }
2625                     }
2626                 }
2627                 if (resourceMetadataData == null) {
2628                     log.debug("getLatestResourceByCsarOrName - getByCriteria(by system name) returned 2 latest CERTIFIED versions");
2629                     return Either.right(StorageOperationStatus.GENERAL_ERROR);
2630                 }
2631                 final Object csarUuid = resourceMetadataData.getJsonMetadataField(JsonPresentationFields.CSAR_UUID);
2632                 if (csarUuid != null && !csarUuid.equals(csarUUID)) {
2633                     log.debug("getLatestResourceByCsarOrName - same system name {} but different csarUUID. exist {} and new {} ", systemName,
2634                         csarUuid, csarUUID);
2635                     // correct error will be returned from create flow. with all
2636
2637                     // correct audit records!!!!!
2638                     return Either.right(StorageOperationStatus.NOT_FOUND);
2639                 }
2640                 return getToscaElement(resourceMetadataData.getUniqueId());
2641             }
2642         } else {
2643             resourceMetadataDataList = byCsar.left().value();
2644             if (resourceMetadataDataList.size() > 2) {
2645                 log.debug("getLatestResourceByCsarOrName - getByCriteria(by csar) must return only 2 latest version, but was returned - {}",
2646                     byCsar.left().value().size());
2647                 return Either.right(StorageOperationStatus.GENERAL_ERROR);
2648             }
2649             if (resourceMetadataDataList.size() == 1) {
2650                 resourceMetadataData = resourceMetadataDataList.get(0);
2651             } else {
2652                 for (GraphVertex curResource : resourceMetadataDataList) {
2653                     if (!((String) curResource.getJsonMetadataField(JsonPresentationFields.LIFECYCLE_STATE)).equals("CERTIFIED")) {
2654                         resourceMetadataData = curResource;
2655                         break;
2656                     }
2657                 }
2658             }
2659             if (resourceMetadataData == null) {
2660                 log.debug("getLatestResourceByCsarOrName - getByCriteria(by csar) returned 2 latest CERTIFIED versions");
2661                 return Either.right(StorageOperationStatus.GENERAL_ERROR);
2662             }
2663             return getToscaElement((String) resourceMetadataData.getJsonMetadataField(JsonPresentationFields.UNIQUE_ID), parseFlag);
2664         }
2665         return null;
2666     }
2667
2668     public Either<Boolean, StorageOperationStatus> validateToscaResourceNameExtends(String templateNameCurrent, String templateNameExtends,
2669                                                                                     String model) {
2670         String currentTemplateNameChecked = templateNameExtends;
2671         while (currentTemplateNameChecked != null && !currentTemplateNameChecked.equalsIgnoreCase(templateNameCurrent)) {
2672             Either<Resource, StorageOperationStatus> latestByToscaResourceName = getLatestByToscaResourceName(currentTemplateNameChecked, model);
2673             if (latestByToscaResourceName.isRight()) {
2674                 return latestByToscaResourceName.right().value() == StorageOperationStatus.NOT_FOUND ? Either.left(false)
2675                     : Either.right(latestByToscaResourceName.right().value());
2676             }
2677             Resource value = latestByToscaResourceName.left().value();
2678             if (value.getDerivedFrom() != null) {
2679                 currentTemplateNameChecked = value.getDerivedFrom().get(0);
2680             } else {
2681                 currentTemplateNameChecked = null;
2682             }
2683         }
2684         return (currentTemplateNameChecked != null && currentTemplateNameChecked.equalsIgnoreCase(templateNameCurrent)) ? Either.left(true)
2685             : Either.left(false);
2686     }
2687
2688     public Either<List<Component>, StorageOperationStatus> fetchMetaDataByResourceType(String resourceType, ComponentParametersView filterBy) {
2689         Map<GraphPropertyEnum, Object> props = new EnumMap<>(GraphPropertyEnum.class);
2690         props.put(GraphPropertyEnum.RESOURCE_TYPE, resourceType);
2691         props.put(GraphPropertyEnum.IS_HIGHEST_VERSION, true);
2692         Map<GraphPropertyEnum, Object> propsHasNotToMatch = new EnumMap<>(GraphPropertyEnum.class);
2693         propsHasNotToMatch.put(GraphPropertyEnum.IS_DELETED, true);
2694         Either<List<GraphVertex>, JanusGraphOperationStatus> resourcesByTypeEither = janusGraphDao
2695             .getByCriteria(null, props, propsHasNotToMatch, JsonParseFlagEnum.ParseMetadata);
2696         if (resourcesByTypeEither.isRight()) {
2697             return Either.right(DaoStatusConverter.convertJanusGraphStatusToStorageStatus(resourcesByTypeEither.right().value()));
2698         }
2699         List<GraphVertex> vertexList = resourcesByTypeEither.left().value();
2700         List<Component> components = new ArrayList<>();
2701         for (GraphVertex vertex : vertexList) {
2702             components.add(getToscaElementByOperation(vertex, filterBy).left().value());
2703         }
2704         return Either.left(components);
2705     }
2706
2707     public void commit() {
2708         janusGraphDao.commit();
2709     }
2710
2711     public Either<Service, StorageOperationStatus> updateDistributionStatus(Service service, User user, DistributionStatusEnum distributionStatus) {
2712         Either<GraphVertex, StorageOperationStatus> updateDistributionStatus = topologyTemplateOperation
2713             .updateDistributionStatus(service.getUniqueId(), user, distributionStatus);
2714         if (updateDistributionStatus.isRight()) {
2715             return Either.right(updateDistributionStatus.right().value());
2716         }
2717         GraphVertex serviceV = updateDistributionStatus.left().value();
2718         service.setDistributionStatus(distributionStatus);
2719         service.setLastUpdateDate((Long) serviceV.getJsonMetadataField(JsonPresentationFields.LAST_UPDATE_DATE));
2720         return Either.left(service);
2721     }
2722
2723     public Either<ComponentMetadataData, StorageOperationStatus> updateComponentLastUpdateDateOnGraph(Component component) {
2724         Either<ComponentMetadataData, StorageOperationStatus> result = null;
2725         GraphVertex serviceVertex;
2726         Either<GraphVertex, JanusGraphOperationStatus> updateRes = null;
2727         Either<GraphVertex, JanusGraphOperationStatus> getRes = janusGraphDao.getVertexById(component.getUniqueId(), JsonParseFlagEnum.ParseMetadata);
2728         if (getRes.isRight()) {
2729             JanusGraphOperationStatus status = getRes.right().value();
2730             log.error("Failed to fetch component {}. status is {}", component.getUniqueId(), status);
2731             result = Either.right(DaoStatusConverter.convertJanusGraphStatusToStorageStatus(status));
2732         }
2733         if (result == null) {
2734             serviceVertex = getRes.left().value();
2735             long lastUpdateDate = System.currentTimeMillis();
2736             serviceVertex.setJsonMetadataField(JsonPresentationFields.LAST_UPDATE_DATE, lastUpdateDate);
2737             component.setLastUpdateDate(lastUpdateDate);
2738             updateRes = janusGraphDao.updateVertex(serviceVertex);
2739             if (updateRes.isRight()) {
2740                 result = Either.right(DaoStatusConverter.convertJanusGraphStatusToStorageStatus(updateRes.right().value()));
2741             }
2742         }
2743         if (result == null) {
2744             result = Either.left(ModelConverter.convertToComponentMetadata(updateRes.left().value()));
2745         }
2746         return result;
2747     }
2748
2749     public HealingJanusGraphDao getJanusGraphDao() {
2750         return janusGraphDao;
2751     }
2752
2753     public Either<List<Service>, StorageOperationStatus> getCertifiedServicesWithDistStatus(Set<DistributionStatusEnum> distStatus) {
2754         Map<GraphPropertyEnum, Object> propertiesToMatch = new EnumMap<>(GraphPropertyEnum.class);
2755         propertiesToMatch.put(GraphPropertyEnum.STATE, LifecycleStateEnum.CERTIFIED.name());
2756         return getServicesWithDistStatus(distStatus, propertiesToMatch);
2757     }
2758
2759     public Either<List<Service>, StorageOperationStatus> getServicesWithDistStatus(Set<DistributionStatusEnum> distStatus,
2760                                                                                    Map<GraphPropertyEnum, Object> additionalPropertiesToMatch) {
2761         List<Service> servicesAll = new ArrayList<>();
2762         Map<GraphPropertyEnum, Object> propertiesToMatch = new EnumMap<>(GraphPropertyEnum.class);
2763         Map<GraphPropertyEnum, Object> propertiesNotToMatch = new EnumMap<>(GraphPropertyEnum.class);
2764         if (additionalPropertiesToMatch != null && !additionalPropertiesToMatch.isEmpty()) {
2765             propertiesToMatch.putAll(additionalPropertiesToMatch);
2766         }
2767         propertiesToMatch.put(GraphPropertyEnum.COMPONENT_TYPE, ComponentTypeEnum.SERVICE.name());
2768         propertiesNotToMatch.put(GraphPropertyEnum.IS_DELETED, true);
2769         if (distStatus != null && !distStatus.isEmpty()) {
2770             for (DistributionStatusEnum state : distStatus) {
2771                 propertiesToMatch.put(GraphPropertyEnum.DISTRIBUTION_STATUS, state.name());
2772                 Either<List<Service>, StorageOperationStatus> fetchServicesByCriteria = fetchServicesByCriteria(servicesAll, propertiesToMatch,
2773                     propertiesNotToMatch, null);
2774                 if (fetchServicesByCriteria.isRight()) {
2775                     return fetchServicesByCriteria;
2776                 } else {
2777                     servicesAll = fetchServicesByCriteria.left().value();
2778                 }
2779             }
2780             return Either.left(servicesAll);
2781         } else {
2782             return fetchServicesByCriteria(servicesAll, propertiesToMatch, propertiesNotToMatch, null);
2783         }
2784     }
2785
2786     private Either<List<Service>, StorageOperationStatus> fetchServicesByCriteria(List<Service> servicesAll,
2787                                                                                   Map<GraphPropertyEnum, Object> propertiesToMatch,
2788                                                                                   Map<GraphPropertyEnum, Object> propertiesNotToMatch,
2789                                                                                   String modelName) {
2790         Either<List<GraphVertex>, JanusGraphOperationStatus> getRes = janusGraphDao
2791             .getByCriteria(VertexTypeEnum.TOPOLOGY_TEMPLATE, propertiesToMatch, propertiesNotToMatch, JsonParseFlagEnum.ParseAll, modelName);
2792         if (getRes.isRight()) {
2793             if (getRes.right().value() != JanusGraphOperationStatus.NOT_FOUND) {
2794                 CommonUtility.addRecordToLog(log, LogLevelEnum.DEBUG,
2795                     "Failed to fetch certified services by match properties {} not match properties {} . Status is {}. ", propertiesToMatch,
2796                     propertiesNotToMatch, getRes.right().value());
2797                 return Either.right(DaoStatusConverter.convertJanusGraphStatusToStorageStatus(getRes.right().value()));
2798             }
2799         } else {
2800             for (final GraphVertex vertex : getRes.left().value()) {
2801                 Either<ToscaElement, StorageOperationStatus> getServiceRes = topologyTemplateOperation
2802                     .getLightComponent(vertex, ComponentTypeEnum.SERVICE, new ComponentParametersView(true));
2803                 if (getServiceRes.isRight()) {
2804                     CommonUtility.addRecordToLog(log, LogLevelEnum.DEBUG, "Failed to fetch certified service {}. Status is {}. ",
2805                         vertex.getJsonMetadataField(JsonPresentationFields.NAME), getServiceRes.right().value());
2806                     return Either.right(getServiceRes.right().value());
2807                 } else {
2808                     servicesAll.add(ModelConverter.convertFromToscaElement(getServiceRes.left().value()));
2809                 }
2810             }
2811         }
2812         return Either.left(servicesAll);
2813     }
2814
2815     public void rollback() {
2816         janusGraphDao.rollback();
2817     }
2818
2819     public StorageOperationStatus addDeploymentArtifactsToInstance(String componentId, ComponentInstance componentInstance,
2820                                                                    Map<String, ArtifactDefinition> finalDeploymentArtifacts) {
2821         Map<String, ArtifactDataDefinition> instDeplArtifacts = finalDeploymentArtifacts.entrySet().stream()
2822             .collect(Collectors.toMap(Map.Entry::getKey, e -> new ArtifactDataDefinition(e.getValue())));
2823         return nodeTemplateOperation.addDeploymentArtifactsToInstance(componentId, componentInstance.getUniqueId(), instDeplArtifacts);
2824     }
2825
2826     public StorageOperationStatus addInformationalArtifactsToInstance(String componentId, ComponentInstance componentInstance,
2827                                                                       Map<String, ArtifactDefinition> artifacts) {
2828         StorageOperationStatus status = StorageOperationStatus.OK;
2829         if (MapUtils.isNotEmpty(artifacts)) {
2830             Map<String, ArtifactDataDefinition> instDeplArtifacts = artifacts.entrySet().stream()
2831                 .collect(Collectors.toMap(Map.Entry::getKey, e -> new ArtifactDataDefinition(e.getValue())));
2832             status = nodeTemplateOperation.addInformationalArtifactsToInstance(componentId, componentInstance.getUniqueId(), instDeplArtifacts);
2833         }
2834         return status;
2835     }
2836
2837     public StorageOperationStatus generateCustomizationUUIDOnInstance(String componentId, String instanceId) {
2838         return nodeTemplateOperation.generateCustomizationUUIDOnInstance(componentId, instanceId);
2839     }
2840
2841     public StorageOperationStatus generateCustomizationUUIDOnInstanceGroup(String componentId, String instanceId, List<String> groupInstances) {
2842         return nodeTemplateOperation.generateCustomizationUUIDOnInstanceGroup(componentId, instanceId, groupInstances);
2843     }
2844
2845     public Either<PropertyDefinition, StorageOperationStatus> addPropertyToComponent(PropertyDefinition newPropertyDefinition,
2846                                                                                      Component component) {
2847         final String propertyName = newPropertyDefinition.getName();
2848         StorageOperationStatus status = getToscaElementOperation(component)
2849             .addToscaDataToToscaElement(component.getUniqueId(), EdgeLabelEnum.PROPERTIES, VertexTypeEnum.PROPERTIES, newPropertyDefinition,
2850                 JsonPresentationFields.NAME);
2851         if (status != StorageOperationStatus.OK) {
2852             CommonUtility.addRecordToLog(log, LogLevelEnum.DEBUG, "Failed to add the property {} to the component {}. Status is {}. ", propertyName,
2853                 component.getName(), status);
2854             return Either.right(status);
2855         }
2856         ComponentParametersView filter = new ComponentParametersView(true);
2857         filter.setIgnoreProperties(false);
2858         filter.setIgnoreInputs(false);
2859         Either<Component, StorageOperationStatus> getUpdatedComponentRes = getToscaElement(component.getUniqueId(), filter);
2860         if (getUpdatedComponentRes.isRight()) {
2861             CommonUtility.addRecordToLog(log, LogLevelEnum.DEBUG, "Failed to get updated component {}. Status is {}. ", component.getUniqueId(),
2862                 getUpdatedComponentRes.right().value());
2863             return Either.right(status);
2864         }
2865         PropertyDefinition newProperty = null;
2866         List<PropertyDefinition> properties = (getUpdatedComponentRes.left().value()).getProperties();
2867         if (CollectionUtils.isNotEmpty(properties)) {
2868             Optional<PropertyDefinition> propertyOptional = properties.stream().filter(propertyEntry -> propertyEntry.getName().equals(propertyName))
2869                 .findAny();
2870             if (propertyOptional.isPresent()) {
2871                 newProperty = propertyOptional.get();
2872             }
2873         }
2874         if (newProperty == null) {
2875             CommonUtility.addRecordToLog(log, LogLevelEnum.DEBUG, "Failed to find recently added property {} on the component {}. Status is {}. ",
2876                 propertyName, component.getUniqueId(), StorageOperationStatus.NOT_FOUND);
2877             return Either.right(StorageOperationStatus.NOT_FOUND);
2878         }
2879         return Either.left(newProperty);
2880     }
2881
2882     public Either<InputDefinition, StorageOperationStatus> addInputToComponent(String inputName, InputDefinition newInputDefinition,
2883                                                                                Component component) {
2884         newInputDefinition.setName(inputName);
2885         StorageOperationStatus status = getToscaElementOperation(component)
2886             .addToscaDataToToscaElement(component.getUniqueId(), EdgeLabelEnum.INPUTS, VertexTypeEnum.INPUTS, newInputDefinition,
2887                 JsonPresentationFields.NAME);
2888         if (status != StorageOperationStatus.OK) {
2889             CommonUtility.addRecordToLog(log, LogLevelEnum.DEBUG, "Failed to add the input {} to the component {}. Status is {}. ", inputName,
2890                 component.getName(), status);
2891             return Either.right(status);
2892         }
2893         ComponentParametersView filter = new ComponentParametersView(true);
2894         filter.setIgnoreProperties(false);
2895         filter.setIgnoreInputs(false);
2896         Either<Component, StorageOperationStatus> getUpdatedComponentRes = getToscaElement(component.getUniqueId(), filter);
2897         if (getUpdatedComponentRes.isRight()) {
2898             CommonUtility.addRecordToLog(log, LogLevelEnum.DEBUG, "Failed to get updated component {}. Status is {}. ", component.getUniqueId(),
2899                 getUpdatedComponentRes.right().value());
2900             return Either.right(status);
2901         }
2902         InputDefinition newInput = null;
2903         List<InputDefinition> inputs = (getUpdatedComponentRes.left().value()).getInputs();
2904         if (CollectionUtils.isNotEmpty(inputs)) {
2905             Optional<InputDefinition> inputOptional = inputs.stream().filter(inputEntry -> inputEntry.getName().equals(inputName)).findAny();
2906             if (inputOptional.isPresent()) {
2907                 newInput = inputOptional.get();
2908             }
2909         }
2910         if (newInput == null) {
2911             CommonUtility
2912                 .addRecordToLog(log, LogLevelEnum.DEBUG, "Failed to find recently added input {} " + "on the component {}. Status is {}. ", inputs,
2913                     component.getUniqueId(), StorageOperationStatus.NOT_FOUND);
2914             return Either.right(StorageOperationStatus.NOT_FOUND);
2915         }
2916         return Either.left(newInput);
2917     }
2918
2919     public StorageOperationStatus deletePropertyOfComponent(Component component, String propertyName) {
2920         return getToscaElementOperation(component)
2921             .deleteToscaDataElement(component.getUniqueId(), EdgeLabelEnum.PROPERTIES, VertexTypeEnum.PROPERTIES, propertyName,
2922                 JsonPresentationFields.NAME);
2923     }
2924
2925     public StorageOperationStatus deleteAttributeOfResource(Component component, String attributeName) {
2926         return getToscaElementOperation(component)
2927             .deleteToscaDataElement(component.getUniqueId(), EdgeLabelEnum.ATTRIBUTES, VertexTypeEnum.ATTRIBUTES, attributeName,
2928                 JsonPresentationFields.NAME);
2929     }
2930
2931     public StorageOperationStatus deleteInputOfResource(Component resource, String inputName) {
2932         return getToscaElementOperation(resource)
2933             .deleteToscaDataElement(resource.getUniqueId(), EdgeLabelEnum.INPUTS, VertexTypeEnum.INPUTS, inputName, JsonPresentationFields.NAME);
2934     }
2935
2936     public StorageOperationStatus deleteOutputOfResource(final Component resource, final String outputName) {
2937         return getToscaElementOperation(resource)
2938             .deleteToscaDataElement(resource.getUniqueId(), EdgeLabelEnum.OUTPUTS, VertexTypeEnum.OUTPUTS, outputName, JsonPresentationFields.NAME);
2939     }
2940
2941     /**
2942      * Deletes a data type from a component.
2943      *
2944      * @param component    the container which has the data type
2945      * @param dataTypeName the data type name to be deleted
2946      * @return Operation result.
2947      */
2948     public StorageOperationStatus deleteDataTypeOfComponent(Component component, String dataTypeName) {
2949         return getToscaElementOperation(component)
2950             .deleteToscaDataElement(component.getUniqueId(), EdgeLabelEnum.DATA_TYPES, VertexTypeEnum.DATA_TYPES, dataTypeName,
2951                 JsonPresentationFields.NAME);
2952     }
2953
2954     public Either<PropertyDefinition, StorageOperationStatus> updatePropertyOfComponent(Component component,
2955                                                                                         PropertyDefinition newPropertyDefinition) {
2956         Either<Component, StorageOperationStatus> getUpdatedComponentRes = null;
2957         Either<PropertyDefinition, StorageOperationStatus> result = null;
2958         StorageOperationStatus status = getToscaElementOperation(component)
2959             .updateToscaDataOfToscaElement(component.getUniqueId(), EdgeLabelEnum.PROPERTIES, VertexTypeEnum.PROPERTIES, newPropertyDefinition,
2960                 JsonPresentationFields.NAME);
2961         if (status != StorageOperationStatus.OK) {
2962             CommonUtility
2963                 .addRecordToLog(log, LogLevelEnum.DEBUG, FAILED_TO_ADD_THE_PROPERTY_TO_THE_RESOURCE_STATUS_IS, newPropertyDefinition.getName(),
2964                     component.getName(), status);
2965             result = Either.right(status);
2966         }
2967         if (result == null) {
2968             ComponentParametersView filter = new ComponentParametersView(true);
2969             filter.setIgnoreProperties(false);
2970             getUpdatedComponentRes = getToscaElement(component.getUniqueId(), filter);
2971             if (getUpdatedComponentRes.isRight()) {
2972                 CommonUtility.addRecordToLog(log, LogLevelEnum.DEBUG, FAILED_TO_GET_UPDATED_RESOURCE_STATUS_IS, component.getUniqueId(),
2973                     getUpdatedComponentRes.right().value());
2974                 result = Either.right(status);
2975             }
2976         }
2977         if (result == null) {
2978             Optional<PropertyDefinition> newProperty = (getUpdatedComponentRes.left().value()).getProperties().stream()
2979                 .filter(p -> p.getName().equals(newPropertyDefinition.getName())).findAny();
2980             if (newProperty.isPresent()) {
2981                 result = Either.left(newProperty.get());
2982             } else {
2983                 CommonUtility.addRecordToLog(log, LogLevelEnum.DEBUG, FAILED_TO_FIND_RECENTLY_ADDED_PROPERTY_ON_THE_RESOURCE_STATUS_IS,
2984                     newPropertyDefinition.getName(), component.getUniqueId(), StorageOperationStatus.NOT_FOUND);
2985                 result = Either.right(StorageOperationStatus.NOT_FOUND);
2986             }
2987         }
2988         return result;
2989     }
2990
2991     public Either<AttributeDefinition, StorageOperationStatus> updateAttributeOfComponent(Component component,
2992                                                                                           AttributeDefinition newPropertyDefinition) {
2993         Either<Component, StorageOperationStatus> getUpdatedComponentRes = null;
2994         Either<AttributeDefinition, StorageOperationStatus> result = null;
2995         StorageOperationStatus status = getToscaElementOperation(component)
2996             .updateToscaDataOfToscaElement(component.getUniqueId(), EdgeLabelEnum.ATTRIBUTES, VertexTypeEnum.ATTRIBUTES, newPropertyDefinition,
2997                 JsonPresentationFields.NAME);
2998         if (status != StorageOperationStatus.OK) {
2999             CommonUtility
3000                 .addRecordToLog(log, LogLevelEnum.DEBUG, FAILED_TO_ADD_THE_PROPERTY_TO_THE_RESOURCE_STATUS_IS, newPropertyDefinition.getName(),
3001                     component.getName(), status);
3002             result = Either.right(status);
3003         }
3004         if (result == null) {
3005             ComponentParametersView filter = new ComponentParametersView(true);
3006             filter.setIgnoreProperties(false);
3007             getUpdatedComponentRes = getToscaElement(component.getUniqueId(), filter);
3008             if (getUpdatedComponentRes.isRight()) {
3009                 CommonUtility.addRecordToLog(log, LogLevelEnum.DEBUG, FAILED_TO_GET_UPDATED_RESOURCE_STATUS_IS, component.getUniqueId(),
3010                     getUpdatedComponentRes.right().value());
3011                 result = Either.right(status);
3012             }
3013         }
3014         if (result == null) {
3015             Optional<AttributeDefinition> newProperty = (getUpdatedComponentRes.left().value()).getAttributes().stream()
3016                 .filter(p -> p.getName().equals(newPropertyDefinition.getName())).findAny();
3017             if (newProperty.isPresent()) {
3018                 result = Either.left(newProperty.get());
3019             } else {
3020                 CommonUtility.addRecordToLog(log, LogLevelEnum.DEBUG, FAILED_TO_FIND_RECENTLY_ADDED_PROPERTY_ON_THE_RESOURCE_STATUS_IS,
3021                     newPropertyDefinition.getName(), component.getUniqueId(), StorageOperationStatus.NOT_FOUND);
3022                 result = Either.right(StorageOperationStatus.NOT_FOUND);
3023             }
3024         }
3025         return result;
3026     }
3027
3028     public Either<AttributeDefinition, StorageOperationStatus> addAttributeOfResource(Component component, AttributeDefinition newAttributeDef) {
3029         Either<Component, StorageOperationStatus> getUpdatedComponentRes = null;
3030         Either<AttributeDefinition, StorageOperationStatus> result = null;
3031         if (newAttributeDef.getUniqueId() == null || newAttributeDef.getUniqueId().isEmpty()) {
3032             String attUniqueId = UniqueIdBuilder.buildAttributeUid(component.getUniqueId(), newAttributeDef.getName());
3033             newAttributeDef.setUniqueId(attUniqueId);
3034             newAttributeDef.setOwnerId(component.getUniqueId());
3035         }
3036         StorageOperationStatus status = getToscaElementOperation(component)
3037             .addToscaDataToToscaElement(component.getUniqueId(), EdgeLabelEnum.ATTRIBUTES, VertexTypeEnum.ATTRIBUTES, newAttributeDef,
3038                 JsonPresentationFields.NAME);
3039         if (status != StorageOperationStatus.OK) {
3040             CommonUtility.addRecordToLog(log, LogLevelEnum.DEBUG, FAILED_TO_ADD_THE_PROPERTY_TO_THE_RESOURCE_STATUS_IS, newAttributeDef.getName(),
3041                 component.getName(), status);
3042             result = Either.right(status);
3043         }
3044         if (result == null) {
3045             ComponentParametersView filter = new ComponentParametersView(true);
3046             filter.setIgnoreAttributes(false);
3047             getUpdatedComponentRes = getToscaElement(component.getUniqueId(), filter);
3048             if (getUpdatedComponentRes.isRight()) {
3049                 CommonUtility.addRecordToLog(log, LogLevelEnum.DEBUG, FAILED_TO_GET_UPDATED_RESOURCE_STATUS_IS, component.getUniqueId(),
3050                     getUpdatedComponentRes.right().value());
3051                 result = Either.right(status);
3052             }
3053         }
3054         if (result == null) {
3055             Optional<AttributeDefinition> newAttribute = ((Resource) getUpdatedComponentRes.left().value()).getAttributes().stream()
3056                 .filter(p -> p.getName().equals(newAttributeDef.getName())).findAny();
3057             if (newAttribute.isPresent()) {
3058                 result = Either.left(newAttribute.get());
3059             } else {
3060                 CommonUtility.addRecordToLog(log, LogLevelEnum.DEBUG, FAILED_TO_FIND_RECENTLY_ADDED_PROPERTY_ON_THE_RESOURCE_STATUS_IS,
3061                     newAttributeDef.getName(), component.getUniqueId(), StorageOperationStatus.NOT_FOUND);
3062                 result = Either.right(StorageOperationStatus.NOT_FOUND);
3063             }
3064         }
3065         return result;
3066     }
3067
3068     public Either<AttributeDefinition, StorageOperationStatus> updateAttributeOfResource(Component component, AttributeDefinition newAttributeDef) {
3069         Either<Component, StorageOperationStatus> getUpdatedComponentRes = null;
3070         Either<AttributeDefinition, StorageOperationStatus> result = null;
3071         StorageOperationStatus status = getToscaElementOperation(component)
3072             .updateToscaDataOfToscaElement(component.getUniqueId(), EdgeLabelEnum.ATTRIBUTES, VertexTypeEnum.ATTRIBUTES, newAttributeDef,
3073                 JsonPresentationFields.NAME);
3074         if (status != StorageOperationStatus.OK) {
3075             CommonUtility.addRecordToLog(log, LogLevelEnum.DEBUG, FAILED_TO_ADD_THE_PROPERTY_TO_THE_RESOURCE_STATUS_IS, newAttributeDef.getName(),
3076                 component.getName(), status);
3077             result = Either.right(status);
3078         }
3079         if (result == null) {
3080             ComponentParametersView filter = new ComponentParametersView(true);
3081             filter.setIgnoreAttributes(false);
3082             getUpdatedComponentRes = getToscaElement(component.getUniqueId(), filter);
3083             if (getUpdatedComponentRes.isRight()) {
3084                 CommonUtility.addRecordToLog(log, LogLevelEnum.DEBUG, FAILED_TO_GET_UPDATED_RESOURCE_STATUS_IS, component.getUniqueId(),
3085                     getUpdatedComponentRes.right().value());
3086                 result = Either.right(status);
3087             }
3088         }
3089         if (result == null) {
3090             Optional<AttributeDefinition> newProperty = ((Resource) getUpdatedComponentRes.left().value()).getAttributes().stream()
3091                 .filter(p -> p.getName().equals(newAttributeDef.getName())).findAny();
3092             if (newProperty.isPresent()) {
3093                 result = Either.left(newProperty.get());
3094             } else {
3095                 CommonUtility.addRecordToLog(log, LogLevelEnum.DEBUG, FAILED_TO_FIND_RECENTLY_ADDED_PROPERTY_ON_THE_RESOURCE_STATUS_IS,
3096                     newAttributeDef.getName(), component.getUniqueId(), StorageOperationStatus.NOT_FOUND);
3097                 result = Either.right(StorageOperationStatus.NOT_FOUND);
3098             }
3099         }
3100         return result;
3101     }
3102
3103     public Either<InputDefinition, StorageOperationStatus> updateInputOfComponent(Component component, InputDefinition newInputDefinition) {
3104         Either<Component, StorageOperationStatus> getUpdatedComponentRes = null;
3105         Either<InputDefinition, StorageOperationStatus> result = null;
3106         StorageOperationStatus status = getToscaElementOperation(component)
3107             .updateToscaDataOfToscaElement(component.getUniqueId(), EdgeLabelEnum.INPUTS, VertexTypeEnum.INPUTS, newInputDefinition,
3108                 JsonPresentationFields.NAME);
3109         if (status != StorageOperationStatus.OK) {
3110             CommonUtility.addRecordToLog(log, LogLevelEnum.DEBUG, "Failed to update the input {} to the component {}. Status is {}. ",
3111                 newInputDefinition.getName(), component.getName(), status);
3112             result = Either.right(status);
3113         }
3114         if (result == null) {
3115             ComponentParametersView filter = new ComponentParametersView(true);
3116             filter.setIgnoreInputs(false);
3117             getUpdatedComponentRes = getToscaElement(component.getUniqueId(), filter);
3118             if (getUpdatedComponentRes.isRight()) {
3119                 CommonUtility.addRecordToLog(log, LogLevelEnum.DEBUG, FAILED_TO_GET_UPDATED_RESOURCE_STATUS_IS, component.getUniqueId(),
3120                     getUpdatedComponentRes.right().value());
3121                 result = Either.right(status);
3122             }
3123         }
3124         if (result == null) {
3125             Optional<InputDefinition> updatedInput = getUpdatedComponentRes.left().value().getInputs().stream()
3126                 .filter(p -> p.getName().equals(newInputDefinition.getName())).findAny();
3127             if (updatedInput.isPresent()) {
3128                 result = Either.left(updatedInput.get());
3129             } else {
3130                 CommonUtility.addRecordToLog(log, LogLevelEnum.DEBUG, "Failed to find recently updated inputs {} on the resource {}. Status is {}. ",
3131                     newInputDefinition.getName(), component.getUniqueId(), StorageOperationStatus.NOT_FOUND);
3132                 result = Either.right(StorageOperationStatus.NOT_FOUND);
3133             }
3134         }
3135         return result;
3136     }
3137
3138     /**
3139      * method - ename the group instances after referenced container name renamed flow - VF rename -(triggers)-> Group rename
3140      *
3141      * @param containerComponent  - container such as service
3142      * @param componentInstance   - context component
3143      * @param componentInstanceId - id
3144      * @return - successfull/failed status
3145      **/
3146     public Either<StorageOperationStatus, StorageOperationStatus> cleanAndAddGroupInstancesToComponentInstance(Component containerComponent,
3147                                                                                                                ComponentInstance componentInstance,
3148                                                                                                                String componentInstanceId) {
3149         String uniqueId = componentInstance.getUniqueId();
3150         StorageOperationStatus status = nodeTemplateOperation
3151             .deleteToscaDataDeepElementsBlockOfToscaElement(containerComponent.getUniqueId(), EdgeLabelEnum.INST_GROUPS,
3152                 uniqueId);
3153         if (status != StorageOperationStatus.OK && status != StorageOperationStatus.NOT_FOUND) {
3154             CommonUtility
3155                 .addRecordToLog(log, LogLevelEnum.DEBUG, "Failed to delete group instances for container {}. error {] ", componentInstanceId, status);
3156             return Either.right(status);
3157         }
3158         if (componentInstance.getGroupInstances() != null) {
3159             status = addGroupInstancesToComponentInstance(containerComponent, componentInstance, componentInstance.getGroupInstances());
3160             if (status != StorageOperationStatus.OK && status != StorageOperationStatus.NOT_FOUND) {
3161                 CommonUtility
3162                     .addRecordToLog(log, LogLevelEnum.DEBUG, "Failed to add group instances for container {}. error {] ", componentInstanceId,
3163                         status);
3164                 return Either.right(status);
3165             }
3166         }
3167         return Either.left(status);
3168     }
3169
3170     public StorageOperationStatus addGroupInstancesToComponentInstance(Component containerComponent, ComponentInstance componentInstance,
3171                                                                        List<GroupDefinition> groups,
3172                                                                        Map<String, List<ArtifactDefinition>> groupInstancesArtifacts) {
3173         return nodeTemplateOperation.addGroupInstancesToComponentInstance(containerComponent, componentInstance, groups, groupInstancesArtifacts);
3174     }
3175
3176     public Either<List<GroupDefinition>, StorageOperationStatus> updateGroupsOnComponent(Component component,
3177                                                                                          List<GroupDataDefinition> updatedGroups) {
3178         return groupsOperation.updateGroups(component, updatedGroups, PromoteVersionEnum.MINOR);
3179     }
3180
3181     public Either<List<GroupInstance>, StorageOperationStatus> updateGroupInstancesOnComponent(Component component, String instanceId,
3182                                                                                                List<GroupInstance> updatedGroupInstances) {
3183         return groupsOperation.updateGroupInstances(component, instanceId, updatedGroupInstances);
3184     }
3185
3186     public StorageOperationStatus addGroupInstancesToComponentInstance(Component containerComponent, ComponentInstance componentInstance,
3187                                                                        List<GroupInstance> groupInstances) {
3188         return nodeTemplateOperation.addGroupInstancesToComponentInstance(containerComponent, componentInstance, groupInstances);
3189     }
3190
3191     public StorageOperationStatus addDeploymentArtifactsToComponentInstance(Component containerComponent, ComponentInstance componentInstance,
3192                                                                             Map<String, ArtifactDefinition> deploymentArtifacts) {
3193         return nodeTemplateOperation.addDeploymentArtifactsToComponentInstance(containerComponent, componentInstance, deploymentArtifacts);
3194     }
3195
3196     public StorageOperationStatus updateComponentInstanceProperty(Component containerComponent, String componentInstanceId,
3197                                                                   ComponentInstanceProperty property) {
3198         return nodeTemplateOperation.updateComponentInstanceProperty(containerComponent, componentInstanceId, property);
3199     }
3200
3201     public StorageOperationStatus updateComponentInstanceProperties(Component containerComponent, String componentInstanceId,
3202                                                                     List<ComponentInstanceProperty> properties) {
3203         return nodeTemplateOperation.updateComponentInstanceProperties(containerComponent, componentInstanceId, properties);
3204     }
3205
3206     public StorageOperationStatus updateComponentInstanceAttributes(final Component containerComponent, final String componentInstanceId,
3207                                                                     final List<ComponentInstanceAttribute> attributes) {
3208         return nodeTemplateOperation.updateComponentInstanceAttributes(containerComponent, componentInstanceId, attributes);
3209     }
3210
3211     public StorageOperationStatus addComponentInstanceProperty(Component containerComponent, String componentInstanceId,
3212                                                                ComponentInstanceProperty property) {
3213         return nodeTemplateOperation.addComponentInstanceProperty(containerComponent, componentInstanceId, property);
3214     }
3215
3216     public StorageOperationStatus updateComponentInstanceAttribute(final Component containerComponent, final String componentInstanceId,
3217                                                                    final ComponentInstanceAttribute attribute) {
3218         return nodeTemplateOperation.updateComponentInstanceAttribute(containerComponent, componentInstanceId, attribute);
3219     }
3220
3221     public StorageOperationStatus addComponentInstanceAttribute(Component containerComponent, String componentInstanceId,
3222                                                                 ComponentInstanceAttribute attribute) {
3223         return nodeTemplateOperation.addComponentInstanceAttribute(containerComponent, componentInstanceId, attribute);
3224     }
3225
3226     public StorageOperationStatus updateComponentInstanceInput(Component containerComponent, String componentInstanceId,
3227                                                                ComponentInstanceInput property) {
3228         return nodeTemplateOperation.updateComponentInstanceInput(containerComponent, componentInstanceId, property);
3229     }
3230
3231     public StorageOperationStatus updateComponentInstanceOutput(Component containerComponent, String componentInstanceId,
3232                                                                 ComponentInstanceOutput property) {
3233         return nodeTemplateOperation.updateComponentInstanceOutput(containerComponent, componentInstanceId, property);
3234     }
3235
3236     public StorageOperationStatus updateComponentInstanceInputs(Component containerComponent, String componentInstanceId,
3237                                                                 List<ComponentInstanceInput> instanceInputs) {
3238         return nodeTemplateOperation.updateComponentInstanceInputs(containerComponent, componentInstanceId, instanceInputs);
3239     }
3240
3241     public StorageOperationStatus updateComponentInstanceOutputs(Component containerComponent, String componentInstanceId,
3242                                                                  List<ComponentInstanceOutput> instanceInputs) {
3243         return nodeTemplateOperation.updateComponentInstanceOutputs(containerComponent, componentInstanceId, instanceInputs);
3244     }
3245
3246     public StorageOperationStatus addComponentInstanceInput(Component containerComponent, String componentInstanceId,
3247                                                             ComponentInstanceInput property) {
3248         return nodeTemplateOperation.addComponentInstanceInput(containerComponent, componentInstanceId, property);
3249     }
3250
3251     public StorageOperationStatus addComponentInstanceOutput(Component containerComponent, String componentInstanceId,
3252                                                              ComponentInstanceOutput property) {
3253         return nodeTemplateOperation.addComponentInstanceOutput(containerComponent, componentInstanceId, property);
3254     }
3255
3256     public void setNodeTypeOperation(NodeTypeOperation nodeTypeOperation) {
3257         this.nodeTypeOperation = nodeTypeOperation;
3258     }
3259
3260     public void setTopologyTemplateOperation(TopologyTemplateOperation topologyTemplateOperation) {
3261         this.topologyTemplateOperation = topologyTemplateOperation;
3262     }
3263
3264     public StorageOperationStatus deleteComponentInstanceInputsFromTopologyTemplate(Component containerComponent,
3265                                                                                     List<InputDefinition> inputsToDelete) {
3266         return topologyTemplateOperation.deleteToscaDataElements(containerComponent.getUniqueId(), EdgeLabelEnum.INPUTS,
3267             inputsToDelete.stream().map(PropertyDataDefinition::getName).collect(Collectors.toList()));
3268     }
3269
3270     public StorageOperationStatus deleteComponentInstanceOutputsFromTopologyTemplate(final Component containerComponent,
3271                                                                                      final List<OutputDefinition> outputsToDelete) {
3272         return topologyTemplateOperation.deleteToscaDataElements(containerComponent.getUniqueId(), EdgeLabelEnum.OUTPUTS,
3273             outputsToDelete.stream().map(AttributeDataDefinition::getName).collect(Collectors.toList()));
3274     }
3275
3276     public StorageOperationStatus updateComponentInstanceCapabiltyProperty(Component containerComponent, String componentInstanceUniqueId,
3277                                                                            String capabilityPropertyKey, ComponentInstanceProperty property) {
3278         return nodeTemplateOperation
3279             .updateComponentInstanceCapabilityProperty(containerComponent, componentInstanceUniqueId, capabilityPropertyKey, property);
3280     }
3281
3282     public StorageOperationStatus updateComponentInstanceCapabilityProperties(Component containerComponent, String componentInstanceUniqueId) {
3283         return convertComponentInstanceProperties(containerComponent, componentInstanceUniqueId).map(instanceCapProps -> topologyTemplateOperation
3284                 .updateComponentInstanceCapabilityProperties(containerComponent, componentInstanceUniqueId, instanceCapProps))
3285             .orElse(StorageOperationStatus.NOT_FOUND);
3286     }
3287
3288     public StorageOperationStatus updateComponentInstanceRequirement(String containerComponentId, String componentInstanceUniqueId,
3289                                                                      RequirementDataDefinition requirementDataDefinition) {
3290         return nodeTemplateOperation.updateComponentInstanceRequirement(containerComponentId, componentInstanceUniqueId, requirementDataDefinition);
3291     }
3292
3293     public CapabilityDataDefinition updateComponentInstanceCapability(final String containerComponentId, final String componentInstanceUniqueId,
3294                                                                       final CapabilityDataDefinition capabilityDataDefinition) {
3295
3296         return nodeTemplateOperation.updateComponentInstanceCapabilities(containerComponentId, componentInstanceUniqueId, capabilityDataDefinition);
3297     }
3298
3299     public StorageOperationStatus updateComponentInstanceInterfaces(Component containerComponent, String componentInstanceUniqueId) {
3300         MapInterfaceDataDefinition mapInterfaceDataDefinition = convertComponentInstanceInterfaces(containerComponent, componentInstanceUniqueId);
3301         return topologyTemplateOperation.updateComponentInstanceInterfaces(containerComponent, componentInstanceUniqueId, mapInterfaceDataDefinition);
3302     }
3303
3304     public StorageOperationStatus updateComponentInterfaces(final Component component, final String componentInterfaceUpdatedKey) {
3305         MapInterfaceDataDefinition mapInterfaceDataDefinition = convertComponentInterfaces(component.getInterfaces());
3306         return topologyTemplateOperation.updateComponentInterfaces(component.getUniqueId(), mapInterfaceDataDefinition, componentInterfaceUpdatedKey);
3307     }
3308
3309     public Either<InterfaceDefinition, StorageOperationStatus> addInterfaceToComponent(final String interfaceName,
3310                                                                                        final InterfaceDefinition interfaceDefinition,
3311                                                                                        final Component component) {
3312
3313         final boolean match = component.getInterfaces().keySet().stream().anyMatch(s -> s.equals(interfaceName));
3314         StorageOperationStatus status;
3315         final ToscaElementOperation toscaElementOperation = getToscaElementOperation(component);
3316         if (match) {
3317             status = toscaElementOperation.updateToscaDataOfToscaElement(component.getUniqueId(), EdgeLabelEnum.INTERFACE_ARTIFACTS,
3318                 VertexTypeEnum.INTERFACE_ARTIFACTS, interfaceDefinition, JsonPresentationFields.TYPE);
3319         } else {
3320             status = toscaElementOperation.addToscaDataToToscaElement(component.getUniqueId(), EdgeLabelEnum.INTERFACE_ARTIFACTS,
3321                 VertexTypeEnum.INTERFACE_ARTIFACTS, interfaceDefinition, JsonPresentationFields.TYPE);
3322         }
3323
3324         if (status != StorageOperationStatus.OK) {
3325             CommonUtility.addRecordToLog(log, LogLevelEnum.DEBUG, "Failed to add the interface {} to the component {}. Status is {}. ",
3326                 interfaceName, component.getName(), status);
3327             return Either.right(status);
3328         }
3329         final ComponentParametersView filter = new ComponentParametersView(true);
3330         filter.setIgnoreInterfaces(false);
3331         filter.setIgnoreInterfaceInstances(false);
3332         final Either<Component, StorageOperationStatus> getUpdatedComponentRes = getToscaElement(component.getUniqueId(), filter);
3333         if (getUpdatedComponentRes.isRight()) {
3334             CommonUtility.addRecordToLog(log, LogLevelEnum.DEBUG, "Failed to get updated component {}. Status is {}. ",
3335                 component.getUniqueId(), getUpdatedComponentRes.right().value());
3336             return Either.right(getUpdatedComponentRes.right().value());
3337         }
3338         InterfaceDefinition newInterfaceDefinition = null;
3339         final Map<String, InterfaceDefinition> interfaces = (getUpdatedComponentRes.left().value()).getInterfaces();
3340         if (MapUtils.isNotEmpty(interfaces)) {
3341             final Optional<String> interfaceNameOptional = interfaces.keySet().stream().filter(key -> key.equals(interfaceName)).findAny();
3342             if (interfaceNameOptional.isPresent()) {
3343                 newInterfaceDefinition = interfaces.get(interfaceNameOptional.get());
3344             }
3345         }
3346         if (newInterfaceDefinition == null) {
3347             CommonUtility.addRecordToLog(log, LogLevelEnum.DEBUG, "Failed to find recently added interface {} on the component {}. Status is {}. ",
3348                 interfaceName, component.getUniqueId(), StorageOperationStatus.NOT_FOUND);
3349             return Either.right(StorageOperationStatus.NOT_FOUND);
3350         }
3351         return Either.left(newInterfaceDefinition);
3352     }
3353
3354     public StorageOperationStatus updateComponentCalculatedCapabilitiesProperties(Component containerComponent) {
3355         Map<String, MapCapabilityProperty> mapCapabiltyPropertyMap = convertComponentCapabilitiesProperties(containerComponent);
3356         return nodeTemplateOperation.overrideComponentCapabilitiesProperties(containerComponent, mapCapabiltyPropertyMap);
3357     }
3358
3359     public StorageOperationStatus deleteAllCalculatedCapabilitiesRequirements(String topologyTemplateId) {
3360         StorageOperationStatus status = topologyTemplateOperation
3361             .removeToscaData(topologyTemplateId, EdgeLabelEnum.CALCULATED_CAPABILITIES);
3362         if (status == StorageOperationStatus.OK) {
3363             status = topologyTemplateOperation
3364                 .removeToscaData(topologyTemplateId, EdgeLabelEnum.CALCULATED_REQUIREMENTS);
3365         }
3366         if (status == StorageOperationStatus.OK) {
3367             status = topologyTemplateOperation
3368                 .removeToscaData(topologyTemplateId, EdgeLabelEnum.CALCULATED_CAP_PROPERTIES);
3369         }
3370         return status;
3371     }
3372
3373     public Either<Component, StorageOperationStatus> shouldUpgradeToLatestDerived(Resource clonedResource) {
3374         String componentId = clonedResource.getUniqueId();
3375         Either<GraphVertex, JanusGraphOperationStatus> getVertexEither = janusGraphDao.getVertexById(componentId, JsonParseFlagEnum.NoParse);
3376         if (getVertexEither.isRight()) {
3377             log.debug(COULDNT_FETCH_COMPONENT_WITH_AND_UNIQUE_ID_ERROR, componentId, getVertexEither.right().value());
3378             return Either.right(DaoStatusConverter.convertJanusGraphStatusToStorageStatus(getVertexEither.right().value()));
3379         }
3380         GraphVertex nodeTypeV = getVertexEither.left().value();
3381         ToscaElement toscaElementToUpdate = ModelConverter.convertToToscaElement(clonedResource);
3382         Either<ToscaElement, StorageOperationStatus> shouldUpdateDerivedVersion = nodeTypeOperation
3383             .shouldUpdateDerivedVersion(toscaElementToUpdate, nodeTypeV);
3384         if (shouldUpdateDerivedVersion.isRight() && StorageOperationStatus.OK != shouldUpdateDerivedVersion.right().value()) {
3385             log.debug("Failed to update derived version for node type {} derived {}, error: {}", componentId, clonedResource.getDerivedFrom().get(0),
3386                 shouldUpdateDerivedVersion.right().value());
3387             return Either.right(shouldUpdateDerivedVersion.right().value());
3388         }
3389         if (shouldUpdateDerivedVersion.isLeft()) {
3390             return Either.left(ModelConverter.convertFromToscaElement(shouldUpdateDerivedVersion.left().value()));
3391         }
3392         return Either.left(clonedResource);
3393     }
3394
3395     /**
3396      * Returns list of ComponentInstanceProperty belonging to component instance capability specified by name, type and ownerId
3397      */
3398     public Either<List<ComponentInstanceProperty>, StorageOperationStatus> getComponentInstanceCapabilityProperties(String componentId,
3399                                                                                                                     String instanceId,
3400                                                                                                                     String capabilityName,
3401                                                                                                                     String capabilityType,
3402                                                                                                                     String ownerId) {
3403         return topologyTemplateOperation.getComponentInstanceCapabilityProperties(componentId, instanceId, capabilityName, capabilityType, ownerId);
3404     }
3405
3406     private MapInterfaceDataDefinition convertComponentInstanceInterfaces(Component currComponent, String componentInstanceId) {
3407         MapInterfaceDataDefinition mapInterfaceDataDefinition = new MapInterfaceDataDefinition();
3408         List<ComponentInstanceInterface> componentInterface = currComponent.getComponentInstancesInterfaces().get(componentInstanceId);
3409         if (CollectionUtils.isNotEmpty(componentInterface)) {
3410             componentInterface.stream().forEach(interfaceDef -> mapInterfaceDataDefinition.put(interfaceDef.getUniqueId(), interfaceDef));
3411         }
3412         return mapInterfaceDataDefinition;
3413     }
3414
3415     private MapInterfaceDataDefinition convertComponentInterfaces(final Map<String, InterfaceDefinition> interfaces) {
3416         final MapInterfaceDataDefinition mapInterfaceDataDefinition = new MapInterfaceDataDefinition();
3417         if (MapUtils.isNotEmpty(interfaces)) {
3418             interfaces.values().stream().forEach(interfaceDef -> mapInterfaceDataDefinition.put(interfaceDef.getType(), interfaceDef));
3419         }
3420         return mapInterfaceDataDefinition;
3421     }
3422
3423     private Map<String, MapCapabilityProperty> convertComponentCapabilitiesProperties(Component currComponent) {
3424         Map<String, MapCapabilityProperty> map = ModelConverter.extractCapabilityPropertiesFromGroups(currComponent.getGroups(), true);
3425         map.putAll(ModelConverter.extractCapabilityProperteisFromInstances(currComponent.getComponentInstances(), true));
3426         return map;
3427     }
3428
3429     private Optional<MapCapabilityProperty> convertComponentInstanceProperties(Component component, String instanceId) {
3430         return component.fetchInstanceById(instanceId)
3431             .map(ci -> ModelConverter.convertToMapOfMapCapabilityProperties(ci.getCapabilities(), instanceId, ci.getOriginType().isAtomicType()));
3432     }
3433
3434     public Either<PolicyDefinition, StorageOperationStatus> associatePolicyToComponent(String componentId, PolicyDefinition policyDefinition,
3435                                                                                        int counter) {
3436         Either<PolicyDefinition, StorageOperationStatus> result = null;
3437         Either<GraphVertex, JanusGraphOperationStatus> getVertexEither;
3438         getVertexEither = janusGraphDao.getVertexById(componentId, JsonParseFlagEnum.ParseMetadata);
3439         if (getVertexEither.isRight()) {
3440             log.error(COULDNT_FETCH_A_COMPONENT_WITH_AND_UNIQUE_ID_ERROR, componentId, getVertexEither.right().value());
3441             result = Either.right(DaoStatusConverter.convertJanusGraphStatusToStorageStatus(getVertexEither.right().value()));
3442         } else {
3443             if (getVertexEither.left().value().getLabel() != VertexTypeEnum.TOPOLOGY_TEMPLATE) {
3444                 log.error("Policy association to component of Tosca type {} is not allowed. ", getVertexEither.left().value().getLabel());
3445                 result = Either.right(StorageOperationStatus.BAD_REQUEST);
3446             }
3447         }
3448         if (result == null) {
3449             StorageOperationStatus status = topologyTemplateOperation
3450                 .addPolicyToToscaElement(getVertexEither.left().value(), policyDefinition, counter);
3451             if (status != StorageOperationStatus.OK) {
3452                 return Either.right(status);
3453             }
3454         }
3455         if (result == null) {
3456             result = Either.left(policyDefinition);
3457         }
3458         return result;
3459     }
3460
3461     public StorageOperationStatus associatePoliciesToComponent(String componentId, List<PolicyDefinition> policies) {
3462         log.debug("#associatePoliciesToComponent - associating policies for component {}.", componentId);
3463         return janusGraphDao.getVertexById(componentId, JsonParseFlagEnum.ParseMetadata)
3464             .either(containerVertex -> topologyTemplateOperation.addPoliciesToToscaElement(containerVertex, policies),
3465                 DaoStatusConverter::convertJanusGraphStatusToStorageStatus);
3466     }
3467
3468     public Either<PolicyDefinition, StorageOperationStatus> updatePolicyOfComponent(String componentId, PolicyDefinition policyDefinition,
3469                                                                                     PromoteVersionEnum promoteVersionEnum) {
3470         Either<PolicyDefinition, StorageOperationStatus> result = null;
3471         Either<GraphVertex, JanusGraphOperationStatus> getVertexEither;
3472         getVertexEither = janusGraphDao.getVertexById(componentId, JsonParseFlagEnum.NoParse);
3473         if (getVertexEither.isRight()) {
3474             log.error(COULDNT_FETCH_A_COMPONENT_WITH_AND_UNIQUE_ID_ERROR, componentId, getVertexEither.right().value());
3475             result = Either.right(DaoStatusConverter.convertJanusGraphStatusToStorageStatus(getVertexEither.right().value()));
3476         }
3477         if (result == null) {
3478             policyDefinition.setVersion(GroupUtils.updateVersion(promoteVersionEnum, policyDefinition.getVersion()));
3479             StorageOperationStatus status = topologyTemplateOperation.updatePolicyOfToscaElement(getVertexEither.left().value(), policyDefinition);
3480             if (status != StorageOperationStatus.OK) {
3481                 return Either.right(status);
3482             }
3483         }
3484         if (result == null) {
3485             result = Either.left(policyDefinition);
3486         }
3487         return result;
3488     }
3489
3490     public StorageOperationStatus updatePoliciesOfComponent(String componentId, List<PolicyDefinition> policyDefinition) {
3491         log.debug("#updatePoliciesOfComponent - updating policies for component {}", componentId);
3492         return janusGraphDao.getVertexById(componentId, JsonParseFlagEnum.NoParse).right()
3493             .map(DaoStatusConverter::convertJanusGraphStatusToStorageStatus)
3494             .either(containerVertex -> topologyTemplateOperation.updatePoliciesOfToscaElement(containerVertex, policyDefinition), err -> err);
3495     }
3496
3497     public StorageOperationStatus removePolicyFromComponent(String componentId, String policyId) {
3498         StorageOperationStatus status = null;
3499         Either<GraphVertex, JanusGraphOperationStatus> getVertexEither = janusGraphDao.getVertexById(componentId, JsonParseFlagEnum.NoParse);
3500         if (getVertexEither.isRight()) {
3501             log.error(COULDNT_FETCH_A_COMPONENT_WITH_AND_UNIQUE_ID_ERROR, componentId, getVertexEither.right().value());
3502             status = DaoStatusConverter.convertJanusGraphStatusToStorageStatus(getVertexEither.right().value());
3503         }
3504         if (status == null) {
3505             status = topologyTemplateOperation.removePolicyFromToscaElement(getVertexEither.left().value(), policyId);
3506         }
3507         return status;
3508     }
3509
3510     public boolean canAddGroups(String componentId) {
3511         GraphVertex vertex = janusGraphDao.getVertexById(componentId).left().on(this::onJanusGraphError);
3512         return topologyTemplateOperation.hasEdgeOfType(vertex, EdgeLabelEnum.GROUPS);
3513     }
3514
3515     GraphVertex onJanusGraphError(JanusGraphOperationStatus toe) {
3516         throw new StorageException(DaoStatusConverter.convertJanusGraphStatusToStorageStatus(toe));
3517     }
3518
3519     public CatalogUpdateTimestamp updateCatalogTimes() {
3520         long now = System.currentTimeMillis();
3521         GraphVertex catalogRoot = janusGraphDao.getVertexByLabel(VertexTypeEnum.CATALOG_ROOT).left().on(this::onJanusGraphError);
3522         Long currentTime = (Long) catalogRoot.getMetadataProperty(GraphPropertyEnum.CURRENT_CATALOG_UPDATE_TIME);
3523         catalogRoot.addMetadataProperty(GraphPropertyEnum.PREV_CATALOG_UPDATE_TIME, currentTime);
3524         catalogRoot.addMetadataProperty(GraphPropertyEnum.CURRENT_CATALOG_UPDATE_TIME, now);
3525         janusGraphDao.updateVertex(catalogRoot).left().on(this::onJanusGraphError);
3526         return new CatalogUpdateTimestamp(currentTime, now);
3527     }
3528
3529     public CatalogUpdateTimestamp getCatalogTimes() {
3530         GraphVertex catalogRoot = janusGraphDao.getVertexByLabel(VertexTypeEnum.CATALOG_ROOT).left().on(this::onJanusGraphError);
3531         Long currentTime = (Long) catalogRoot.getMetadataProperty(GraphPropertyEnum.CURRENT_CATALOG_UPDATE_TIME);
3532         Long prevTime = (Long) catalogRoot.getMetadataProperty(GraphPropertyEnum.PREV_CATALOG_UPDATE_TIME);
3533         return new CatalogUpdateTimestamp(prevTime == null ? 0 : prevTime.longValue(), currentTime == null ? 0 : currentTime.longValue());
3534     }
3535
3536     public void updateNamesOfCalculatedCapabilitiesRequirements(String componentId) {
3537         topologyTemplateOperation.updateNamesOfCalculatedCapabilitiesRequirements(componentId, getTopologyTemplate(componentId));
3538     }
3539
3540     public void revertNamesOfCalculatedCapabilitiesRequirements(String componentId) {
3541         topologyTemplateOperation.revertNamesOfCalculatedCapabilitiesRequirements(componentId, getTopologyTemplate(componentId));
3542     }
3543
3544     private TopologyTemplate getTopologyTemplate(String componentId) {
3545         return (TopologyTemplate) topologyTemplateOperation.getToscaElement(componentId, getFilterComponentWithCapProperties()).left()
3546             .on(this::throwStorageException);
3547     }
3548
3549     private ComponentParametersView getFilterComponentWithCapProperties() {
3550         ComponentParametersView filter = new ComponentParametersView();
3551         filter.setIgnoreCapabiltyProperties(false);
3552         return filter;
3553     }
3554
3555     private ToscaElement throwStorageException(StorageOperationStatus status) {
3556         throw new StorageException(status);
3557     }
3558
3559     public Either<Boolean, StorageOperationStatus> isComponentInUse(String componentId) {
3560         final List<EdgeLabelEnum> forbiddenEdgeLabelEnums = Arrays
3561             .asList(EdgeLabelEnum.INSTANCE_OF, EdgeLabelEnum.PROXY_OF, EdgeLabelEnum.ALLOTTED_OF);
3562         Either<GraphVertex, JanusGraphOperationStatus> vertexById = janusGraphDao.getVertexById(componentId);
3563         if (vertexById.isLeft()) {
3564             for (EdgeLabelEnum edgeLabelEnum : forbiddenEdgeLabelEnums) {
3565                 Iterator<Edge> edgeItr = vertexById.left().value().getVertex().edges(Direction.IN, edgeLabelEnum.name());
3566                 if (edgeItr != null && edgeItr.hasNext()) {
3567                     return Either.left(true);
3568                 }
3569             }
3570         }
3571         return Either.left(false);
3572     }
3573
3574     public Either<List<Component>, StorageOperationStatus> getComponentListByInvariantUuid(String componentInvariantUuid,
3575                                                                                            Map<GraphPropertyEnum, Object> additionalPropertiesToMatch) {
3576         Map<GraphPropertyEnum, Object> propertiesToMatch = new EnumMap<>(GraphPropertyEnum.class);
3577         if (MapUtils.isNotEmpty(additionalPropertiesToMatch)) {
3578             propertiesToMatch.putAll(additionalPropertiesToMatch);
3579         }
3580         propertiesToMatch.put(GraphPropertyEnum.INVARIANT_UUID, componentInvariantUuid);
3581         Either<List<GraphVertex>, JanusGraphOperationStatus> vertexEither = janusGraphDao
3582             .getByCriteria(null, propertiesToMatch, JsonParseFlagEnum.ParseMetadata);
3583         if (vertexEither.isRight()) {
3584             log.debug("Couldn't fetch metadata for component with type {} and invariantUUId {}, error: {}", componentInvariantUuid,
3585                 vertexEither.right().value());
3586             return Either.right(DaoStatusConverter.convertJanusGraphStatusToStorageStatus(vertexEither.right().value()));
3587         }
3588         List<GraphVertex> vertexList = vertexEither.isLeft() ? vertexEither.left().value() : null;
3589         if (vertexList == null || vertexList.isEmpty()) {
3590             log.debug("Component with invariantUUId {} was not found", componentInvariantUuid);
3591             return Either.right(StorageOperationStatus.NOT_FOUND);
3592         }
3593         ArrayList<Component> components = new ArrayList<>();
3594         for (GraphVertex vertex : vertexList) {
3595             Either<Component, StorageOperationStatus> toscaElementByOperation = getToscaElementByOperation(vertex);
3596             if (toscaElementByOperation.isRight()) {
3597                 log.debug("Could not fetch the following Component by Invariant UUID {}", vertex.getUniqueId());
3598                 return Either.right(toscaElementByOperation.right().value());
3599             }
3600             components.add(toscaElementByOperation.left().value());
3601         }
3602         return Either.left(components);
3603     }
3604
3605     public Either<List<Component>, StorageOperationStatus> getParentComponents(String componentId) {
3606         List<Component> parentComponents = new ArrayList<>();
3607         final List<EdgeLabelEnum> relationEdgeLabelEnums = Arrays.asList(EdgeLabelEnum.INSTANCE_OF, EdgeLabelEnum.PROXY_OF);
3608         Either<GraphVertex, JanusGraphOperationStatus> vertexById = janusGraphDao.getVertexById(componentId);
3609         if (vertexById.isLeft()) {
3610             for (EdgeLabelEnum edgeLabelEnum : relationEdgeLabelEnums) {
3611                 Either<GraphVertex, JanusGraphOperationStatus> parentVertexEither = janusGraphDao
3612                     .getParentVertex(vertexById.left().value(), edgeLabelEnum, JsonParseFlagEnum.ParseJson);
3613                 if (parentVertexEither.isLeft()) {
3614                     Either<Component, StorageOperationStatus> componentEither = getToscaElement(parentVertexEither.left().value().getUniqueId());
3615                     if (componentEither.isLeft()) {
3616                         parentComponents.add(componentEither.left().value());
3617                     }
3618                 }
3619             }
3620         }
3621         return Either.left(parentComponents);
3622     }
3623
3624     public void updateCapReqPropertiesOwnerId(String componentId) {
3625         topologyTemplateOperation.updateCapReqPropertiesOwnerId(componentId, getTopologyTemplate(componentId));
3626     }
3627
3628     public <T extends Component> Either<T, StorageOperationStatus> getLatestByServiceName(String serviceName) {
3629         return getLatestByName(GraphPropertyEnum.NAME, serviceName, null);
3630     }
3631 }