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