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