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