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