2 * ============LICENSE_START=======================================================
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
11 * http://www.apache.org/licenses/LICENSE-2.0
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=========================================================
21 package org.openecomp.sdc.be.model.jsontitan.operations;
23 import java.util.ArrayList;
24 import java.util.Arrays;
25 import java.util.Collections;
26 import java.util.EnumMap;
27 import java.util.HashMap;
28 import java.util.HashSet;
29 import java.util.LinkedList;
30 import java.util.List;
32 import java.util.Map.Entry;
33 import java.util.Optional;
35 import java.util.function.BiPredicate;
36 import java.util.stream.Collectors;
38 import org.apache.commons.collections.CollectionUtils;
39 import org.apache.commons.collections.MapUtils;
40 import org.apache.commons.lang3.StringUtils;
41 import org.apache.commons.lang3.tuple.ImmutablePair;
42 import org.openecomp.sdc.be.dao.jsongraph.GraphVertex;
43 import org.openecomp.sdc.be.dao.jsongraph.TitanDao;
44 import org.openecomp.sdc.be.dao.jsongraph.types.EdgeLabelEnum;
45 import org.openecomp.sdc.be.dao.jsongraph.types.JsonParseFlagEnum;
46 import org.openecomp.sdc.be.dao.jsongraph.types.VertexTypeEnum;
47 import org.openecomp.sdc.be.dao.titan.TitanOperationStatus;
48 import org.openecomp.sdc.be.datatypes.elements.ArtifactDataDefinition;
49 import org.openecomp.sdc.be.datatypes.elements.CapabilityDataDefinition;
50 import org.openecomp.sdc.be.datatypes.elements.ComponentInstanceDataDefinition;
51 import org.openecomp.sdc.be.datatypes.elements.GroupDataDefinition;
52 import org.openecomp.sdc.be.datatypes.elements.ListCapabilityDataDefinition;
53 import org.openecomp.sdc.be.datatypes.elements.ListRequirementDataDefinition;
54 import org.openecomp.sdc.be.datatypes.elements.MapArtifactDataDefinition;
55 import org.openecomp.sdc.be.datatypes.elements.MapCapabiltyProperty;
56 import org.openecomp.sdc.be.datatypes.elements.MapListCapabiltyDataDefinition;
57 import org.openecomp.sdc.be.datatypes.elements.MapListRequirementDataDefinition;
58 import org.openecomp.sdc.be.datatypes.elements.MapPropertiesDataDefinition;
59 import org.openecomp.sdc.be.datatypes.elements.PropertyDataDefinition;
60 import org.openecomp.sdc.be.datatypes.elements.RequirementDataDefinition;
61 import org.openecomp.sdc.be.datatypes.enums.ComponentTypeEnum;
62 import org.openecomp.sdc.be.datatypes.enums.GraphPropertyEnum;
63 import org.openecomp.sdc.be.datatypes.enums.JsonPresentationFields;
64 import org.openecomp.sdc.be.datatypes.enums.OriginTypeEnum;
65 import org.openecomp.sdc.be.datatypes.enums.ResourceTypeEnum;
66 import org.openecomp.sdc.be.model.ArtifactDefinition;
67 import org.openecomp.sdc.be.model.CapabilityDefinition;
68 import org.openecomp.sdc.be.model.Component;
69 import org.openecomp.sdc.be.model.ComponentInstance;
70 import org.openecomp.sdc.be.model.ComponentInstanceInput;
71 import org.openecomp.sdc.be.model.ComponentInstanceProperty;
72 import org.openecomp.sdc.be.model.ComponentParametersView;
73 import org.openecomp.sdc.be.model.DistributionStatusEnum;
74 import org.openecomp.sdc.be.model.GroupDefinition;
75 import org.openecomp.sdc.be.model.GroupInstance;
76 import org.openecomp.sdc.be.model.InputDefinition;
77 import org.openecomp.sdc.be.model.LifecycleStateEnum;
78 import org.openecomp.sdc.be.model.PolicyDefinition;
79 import org.openecomp.sdc.be.model.PropertyDefinition;
80 import org.openecomp.sdc.be.model.RelationshipInfo;
81 import org.openecomp.sdc.be.model.RequirementCapabilityRelDef;
82 import org.openecomp.sdc.be.model.RequirementDefinition;
83 import org.openecomp.sdc.be.model.Resource;
84 import org.openecomp.sdc.be.model.Service;
85 import org.openecomp.sdc.be.model.User;
86 import org.openecomp.sdc.be.model.catalog.CatalogComponent;
87 import org.openecomp.sdc.be.model.jsontitan.datamodel.TopologyTemplate;
88 import org.openecomp.sdc.be.model.jsontitan.datamodel.ToscaElement;
89 import org.openecomp.sdc.be.model.jsontitan.utils.ModelConverter;
90 import org.openecomp.sdc.be.model.operations.api.StorageOperationStatus;
91 import org.openecomp.sdc.be.model.operations.impl.DaoStatusConverter;
92 import org.openecomp.sdc.be.model.operations.impl.UniqueIdBuilder;
93 import org.openecomp.sdc.be.resources.data.ComponentMetadataData;
94 import org.openecomp.sdc.common.jsongraph.util.CommonUtility;
95 import org.openecomp.sdc.common.jsongraph.util.CommonUtility.LogLevelEnum;
96 import org.openecomp.sdc.common.util.ValidationUtils;
97 import org.slf4j.Logger;
98 import org.slf4j.LoggerFactory;
99 import org.springframework.beans.factory.annotation.Autowired;
101 import fj.data.Either;
103 @org.springframework.stereotype.Component("tosca-operation-facade")
104 public class ToscaOperationFacade {
109 private NodeTypeOperation nodeTypeOperation;
111 private TopologyTemplateOperation topologyTemplateOperation;
113 private NodeTemplateOperation nodeTemplateOperation;
115 private GroupsOperation groupsOperation;
117 private TitanDao titanDao;
118 private static Logger log = LoggerFactory.getLogger(ToscaOperationFacade.class.getName());
121 // region - ToscaElement - GetById
122 public static final String PROXY_SUFFIX = "_proxy";
124 public <T extends Component> Either<T, StorageOperationStatus> getToscaElement(String componentId) {
126 return getToscaElement(componentId, JsonParseFlagEnum.ParseAll);
130 public <T extends Component> Either<T, StorageOperationStatus> getToscaFullElement(String componentId) {
131 ComponentParametersView filters = new ComponentParametersView();
132 filters.setIgnoreCapabiltyProperties(false);
133 filters.setIgnoreForwardingPath(false);
134 return getToscaElement(componentId, filters);
137 public <T extends Component> Either<T, StorageOperationStatus> getToscaElement(String componentId, ComponentParametersView filters) {
139 Either<GraphVertex, TitanOperationStatus> getVertexEither = titanDao.getVertexById(componentId, filters.detectParseFlag());
140 if (getVertexEither.isRight()) {
141 log.debug("Couldn't fetch component with and unique id {}, error: {}", componentId, getVertexEither.right().value());
142 return Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(getVertexEither.right().value()));
145 return getToscaElementByOperation(getVertexEither.left().value(), filters);
148 public <T extends Component> Either<T, StorageOperationStatus> getToscaElement(String componentId, JsonParseFlagEnum parseFlag) {
150 Either<GraphVertex, TitanOperationStatus> getVertexEither = titanDao.getVertexById(componentId, parseFlag);
151 if (getVertexEither.isRight()) {
152 log.debug("Couldn't fetch component with and unique id {}, error: {}", componentId, getVertexEither.right().value());
153 return Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(getVertexEither.right().value()));
156 return getToscaElementByOperation(getVertexEither.left().value());
159 public <T extends Component> Either<T, StorageOperationStatus> getToscaElement(GraphVertex componentVertex) {
160 return getToscaElementByOperation(componentVertex);
163 public Either<Boolean, StorageOperationStatus> validateComponentExists(String componentId) {
165 Either<GraphVertex, TitanOperationStatus> getVertexEither = titanDao.getVertexById(componentId, JsonParseFlagEnum.NoParse);
166 if (getVertexEither.isRight()) {
167 TitanOperationStatus status = getVertexEither.right().value();
168 if (status == TitanOperationStatus.NOT_FOUND) {
169 return Either.left(false);
171 log.debug("Couldn't fetch component with and unique id {}, error: {}", componentId, getVertexEither.right().value());
172 return Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(getVertexEither.right().value()));
175 return Either.left(true);
178 public <T extends Component> Either<T, StorageOperationStatus> findLastCertifiedToscaElementByUUID(T component) {
179 Map<GraphPropertyEnum, Object> props = new HashMap<>();
180 props.put(GraphPropertyEnum.UUID, component.getUUID());
181 props.put(GraphPropertyEnum.STATE, LifecycleStateEnum.CERTIFIED.name());
182 props.put(GraphPropertyEnum.IS_HIGHEST_VERSION, true);
184 Either<List<GraphVertex>, TitanOperationStatus> getVertexEither = titanDao.getByCriteria(ModelConverter.getVertexType(component), props);
185 if (getVertexEither.isRight()) {
186 log.debug("Couldn't fetch component with and unique id {}, error: {}", component.getUniqueId(), getVertexEither.right().value());
187 return Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(getVertexEither.right().value()));
190 return getToscaElementByOperation(getVertexEither.left().value().get(0));
194 // region - ToscaElement - GetByOperation
195 private <T extends Component> Either<T, StorageOperationStatus> getToscaElementByOperation(GraphVertex componentV) {
196 return getToscaElementByOperation(componentV, new ComponentParametersView());
199 private <T extends Component> Either<T, StorageOperationStatus> getToscaElementByOperation(GraphVertex componentV, ComponentParametersView filters) {
200 VertexTypeEnum label = componentV.getLabel();
202 ToscaElementOperation toscaOperation = getToscaElementOperation(componentV);
203 Either<ToscaElement, StorageOperationStatus> toscaElement;
204 String componentId = componentV.getUniqueId();
205 if (toscaOperation != null) {
206 log.debug("Need to fetch tosca element for id {}", componentId);
207 toscaElement = toscaOperation.getToscaElement(componentV, filters);
209 log.debug("not supported tosca type {} for id {}", label, componentId);
210 toscaElement = Either.right(StorageOperationStatus.BAD_REQUEST);
212 if (toscaElement.isRight()) {
213 return Either.right(toscaElement.right().value());
215 return Either.left(ModelConverter.convertFromToscaElement(toscaElement.left().value()));
219 private ToscaElementOperation getToscaElementOperation(GraphVertex componentV) {
220 VertexTypeEnum label = componentV.getLabel();
223 return nodeTypeOperation;
224 case TOPOLOGY_TEMPLATE:
225 return topologyTemplateOperation;
236 public <T extends Component> Either<T, StorageOperationStatus> createToscaComponent(T resource) {
237 ToscaElement toscaElement = ModelConverter.convertToToscaElement(resource);
239 ToscaElementOperation toscaElementOperation = getToscaElementOperation(resource);
240 Either<ToscaElement, StorageOperationStatus> createToscaElement = toscaElementOperation.createToscaElement(toscaElement);
241 if (createToscaElement.isLeft()) {
242 log.debug("Component created successfully!!!");
243 T dataModel = ModelConverter.convertFromToscaElement(createToscaElement.left().value());
244 return Either.left(dataModel);
246 return Either.right(createToscaElement.right().value());
249 // region - ToscaElement Delete
252 * @param componentToDelete
255 public StorageOperationStatus markComponentToDelete(Component componentToDelete) {
257 if ((componentToDelete.getIsDeleted() != null) && componentToDelete.getIsDeleted() && !componentToDelete.isHighestVersion()) {
258 // component already marked for delete
259 return StorageOperationStatus.OK;
262 Either<GraphVertex, TitanOperationStatus> getResponse = titanDao.getVertexById(componentToDelete.getUniqueId(), JsonParseFlagEnum.ParseAll);
263 if (getResponse.isRight()) {
264 log.debug("Couldn't fetch component with and unique id {}, error: {}", componentToDelete.getUniqueId(), getResponse.right().value());
265 return DaoStatusConverter.convertTitanStatusToStorageStatus(getResponse.right().value());
268 GraphVertex componentV = getResponse.left().value();
270 // same operation for node type and topology template operations
271 Either<GraphVertex, StorageOperationStatus> result = nodeTypeOperation.markComponentToDelete(componentV);
272 if (result.isRight()) {
273 return result.right().value();
275 return StorageOperationStatus.OK;
284 public <T extends Component> Either<T, StorageOperationStatus> deleteToscaComponent(String componentId) {
286 Either<GraphVertex, TitanOperationStatus> getVertexEither = titanDao.getVertexById(componentId, JsonParseFlagEnum.ParseAll);
287 if (getVertexEither.isRight()) {
288 log.debug("Couldn't fetch component vertex with and unique id {}, error: {}", componentId, getVertexEither.right().value());
289 return Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(getVertexEither.right().value()));
292 Either<ToscaElement, StorageOperationStatus> deleteElement = deleteToscaElement(getVertexEither.left().value());
293 if (deleteElement.isRight()) {
294 log.debug("Failed to delete component with and unique id {}, error: {}", componentId, deleteElement.right().value());
295 return Either.right(deleteElement.right().value());
297 T dataModel = ModelConverter.convertFromToscaElement(deleteElement.left().value());
299 return Either.left(dataModel);
302 private Either<ToscaElement, StorageOperationStatus> deleteToscaElement(GraphVertex componentV) {
303 VertexTypeEnum label = componentV.getLabel();
304 Either<ToscaElement, StorageOperationStatus> toscaElement;
305 Object componentId = componentV.getUniqueId();
308 log.debug("Need to fetch node type for id {}", componentId);
309 toscaElement = nodeTypeOperation.deleteToscaElement(componentV);
311 case TOPOLOGY_TEMPLATE:
312 log.debug("Need to fetch topology template for id {}", componentId);
313 toscaElement = topologyTemplateOperation.deleteToscaElement(componentV);
316 log.debug("not supported tosca type {} for id {}", label, componentId);
317 toscaElement = Either.right(StorageOperationStatus.BAD_REQUEST);
324 private ToscaElementOperation getToscaElementOperation(Component component) {
325 return ModelConverter.isAtomicComponent(component) ? nodeTypeOperation : topologyTemplateOperation;
328 public <T extends Component> Either<T, StorageOperationStatus> getLatestByToscaResourceName(String toscaResourceName) {
329 return getLatestByName(GraphPropertyEnum.TOSCA_RESOURCE_NAME, toscaResourceName);
332 public <T extends Component> Either<T, StorageOperationStatus> getFullLatestComponentByToscaResourceName(String toscaResourceName) {
333 ComponentParametersView fetchAllFilter = new ComponentParametersView();
334 fetchAllFilter.setIgnoreForwardingPath(true);
335 fetchAllFilter.setIgnoreCapabiltyProperties(false);
336 return getLatestByName(GraphPropertyEnum.TOSCA_RESOURCE_NAME, toscaResourceName, JsonParseFlagEnum.ParseAll, fetchAllFilter);
339 public <T extends Component> Either<T, StorageOperationStatus> getLatestByName(String resourceName) {
340 return getLatestByName(GraphPropertyEnum.NAME, resourceName);
344 public Either<Integer, StorageOperationStatus> validateCsarUuidUniqueness(String csarUUID) {
346 Map<GraphPropertyEnum, Object> properties = new HashMap<GraphPropertyEnum, Object>();
347 properties.put(GraphPropertyEnum.CSAR_UUID, csarUUID);
349 Either<List<GraphVertex>, TitanOperationStatus> resources = titanDao.getByCriteria(null, properties, JsonParseFlagEnum.ParseMetadata);
351 if (resources.isRight()) {
352 if (resources.right().value() == TitanOperationStatus.NOT_FOUND) {
353 return Either.left(new Integer(0));
355 log.debug("failed to get resources from graph with property name: {}", csarUUID);
356 return Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(resources.right().value()));
360 List<GraphVertex> resourceList = (resources.isLeft() ? resources.left().value() : null);
362 return Either.left(new Integer(resourceList.size()));
366 public <T extends Component> Either<Set<T>, StorageOperationStatus> getFollowed(String userId, Set<LifecycleStateEnum> lifecycleStates, Set<LifecycleStateEnum> lastStateStates, ComponentTypeEnum componentType) {
367 Either<List<ToscaElement>, StorageOperationStatus> followedResources;
368 if (componentType == ComponentTypeEnum.RESOURCE) {
369 followedResources = nodeTypeOperation.getFollowedComponent(userId, lifecycleStates, lastStateStates, componentType);
371 followedResources = topologyTemplateOperation.getFollowedComponent(userId, lifecycleStates, lastStateStates, componentType);
374 Set<T> components = new HashSet<>();
375 if (followedResources.isRight() && followedResources.right().value() != StorageOperationStatus.NOT_FOUND) {
376 return Either.right(followedResources.right().value());
378 if (followedResources.isLeft()) {
379 List<ToscaElement> toscaElements = followedResources.left().value();
380 toscaElements.forEach(te -> {
381 T component = ModelConverter.convertFromToscaElement(te);
382 components.add(component);
385 return Either.left(components);
388 public Either<Resource, StorageOperationStatus> getLatestCertifiedNodeTypeByToscaResourceName(String toscaResourceName) {
390 return getLatestCertifiedByToscaResourceName(toscaResourceName, VertexTypeEnum.NODE_TYPE, JsonParseFlagEnum.ParseMetadata);
393 public Either<Resource, StorageOperationStatus> getLatestCertifiedByToscaResourceName(String toscaResourceName, VertexTypeEnum vertexType, JsonParseFlagEnum parseFlag) {
395 Either<Resource, StorageOperationStatus> result = null;
396 Map<GraphPropertyEnum, Object> props = new HashMap<GraphPropertyEnum, Object>();
397 props.put(GraphPropertyEnum.TOSCA_RESOURCE_NAME, toscaResourceName);
398 props.put(GraphPropertyEnum.IS_HIGHEST_VERSION, true);
399 props.put(GraphPropertyEnum.STATE, LifecycleStateEnum.CERTIFIED.name());
400 Either<List<GraphVertex>, TitanOperationStatus> getLatestRes = titanDao.getByCriteria(vertexType, props, parseFlag);
402 if (getLatestRes.isRight()) {
403 TitanOperationStatus status = getLatestRes.right().value();
404 CommonUtility.addRecordToLog(log, LogLevelEnum.DEBUG, "Failed to fetch {} with name {}. status={} ", vertexType, toscaResourceName, status);
405 result = Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(status));
407 if (result == null) {
408 List<GraphVertex> resources = getLatestRes.left().value();
409 double version = 0.0;
410 GraphVertex highestResource = null;
411 for (GraphVertex resource : resources) {
412 double resourceVersion = Double.parseDouble((String) resource.getJsonMetadataField(JsonPresentationFields.VERSION));
413 if (resourceVersion > version) {
414 version = resourceVersion;
415 highestResource = resource;
418 result = getToscaFullElement(highestResource.getUniqueId());
423 public Either<Boolean, StorageOperationStatus> validateToscaResourceNameExists(String templateName) {
424 Either<Boolean, StorageOperationStatus> validateUniquenessRes = validateToscaResourceNameUniqueness(templateName);
425 if (validateUniquenessRes.isLeft()) {
426 return Either.left(!validateUniquenessRes.left().value());
428 return validateUniquenessRes;
431 public Either<RequirementCapabilityRelDef, StorageOperationStatus> dissociateResourceInstances(String componentId, RequirementCapabilityRelDef requirementDef) {
432 return nodeTemplateOperation.dissociateResourceInstances(componentId, requirementDef);
435 * Allows to get fulfilled requirement by relation and received predicate
442 public Either<RequirementDataDefinition, StorageOperationStatus> getFulfilledRequirementByRelation(String componentId, String instanceId, RequirementCapabilityRelDef relation, BiPredicate<RelationshipInfo, RequirementDataDefinition> predicate) {
443 return nodeTemplateOperation.getFulfilledRequirementByRelation(componentId, instanceId, relation, predicate);
446 * Allows to get fulfilled capability by relation and received predicate
453 public Either<CapabilityDataDefinition, StorageOperationStatus> getFulfilledCapabilityByRelation(String componentId, String instanceId, RequirementCapabilityRelDef relation, BiPredicate<RelationshipInfo, CapabilityDataDefinition> predicate) {
454 return nodeTemplateOperation.getFulfilledCapabilityByRelation(componentId, instanceId, relation, predicate);
457 public StorageOperationStatus associateResourceInstances(String componentId, List<RequirementCapabilityRelDef> relations) {
458 Either<List<RequirementCapabilityRelDef>, StorageOperationStatus> status = nodeTemplateOperation.associateResourceInstances(componentId, relations);
459 if (status.isRight()) {
460 return status.right().value();
462 return StorageOperationStatus.OK;
465 protected Either<Boolean, StorageOperationStatus> validateToscaResourceNameUniqueness(String name) {
467 Map<GraphPropertyEnum, Object> properties = new HashMap<GraphPropertyEnum, Object>();
468 properties.put(GraphPropertyEnum.TOSCA_RESOURCE_NAME, name);
470 Either<List<GraphVertex>, TitanOperationStatus> resources = titanDao.getByCriteria(null, properties, JsonParseFlagEnum.ParseMetadata);
472 if (resources.isRight() && resources.right().value() != TitanOperationStatus.NOT_FOUND) {
473 log.debug("failed to get resources from graph with property name: {}", name);
474 return Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(resources.right().value()));
476 List<GraphVertex> resourceList = (resources.isLeft() ? resources.left().value() : null);
477 if (resourceList != null && resourceList.size() > 0) {
478 if (log.isDebugEnabled()) {
479 StringBuilder builder = new StringBuilder();
480 for (GraphVertex resourceData : resourceList) {
481 builder.append(resourceData.getUniqueId() + "|");
483 log.debug("resources with property name:{} exists in graph. found {}", name, builder.toString());
485 return Either.left(false);
487 log.debug("resources with property name:{} does not exists in graph", name);
488 return Either.left(true);
493 // region - Component Update
496 * @param newComponent
497 * @param oldComponent
500 public Either<Resource, StorageOperationStatus> overrideComponent(Resource newComponent, Resource oldComponent) {
503 // newComponent.setInterfaces(oldComponent.getInterfaces);
504 newComponent.setArtifacts(oldComponent.getArtifacts());
505 newComponent.setDeploymentArtifacts(oldComponent.getDeploymentArtifacts());
506 newComponent.setGroups(oldComponent.getGroups());
507 newComponent.setLastUpdateDate(null);
508 newComponent.setHighestVersion(true);
510 Either<GraphVertex, TitanOperationStatus> componentVEither = titanDao.getVertexById(oldComponent.getUniqueId(), JsonParseFlagEnum.NoParse);
511 if (componentVEither.isRight()) {
512 log.debug("Falied to fetch component {} error {}", oldComponent.getUniqueId(), componentVEither.right().value());
513 return Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(componentVEither.right().value()));
515 GraphVertex componentv = componentVEither.left().value();
516 Either<GraphVertex, TitanOperationStatus> parentVertexEither = titanDao.getParentVertex(componentv, EdgeLabelEnum.VERSION, JsonParseFlagEnum.NoParse);
517 if (parentVertexEither.isRight() && parentVertexEither.right().value() != TitanOperationStatus.NOT_FOUND) {
518 log.debug("Falied to fetch parent version for component {} error {}", oldComponent.getUniqueId(), parentVertexEither.right().value());
519 return Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(parentVertexEither.right().value()));
522 Either<ToscaElement, StorageOperationStatus> deleteToscaComponent = deleteToscaElement(componentv);
523 if (deleteToscaComponent.isRight()) {
524 log.debug("Falied to remove old component {} error {}", oldComponent.getUniqueId(), deleteToscaComponent.right().value());
525 return Either.right(deleteToscaComponent.right().value());
527 Either<Resource, StorageOperationStatus> createToscaComponent = createToscaComponent(newComponent);
528 if (createToscaComponent.isRight()) {
529 log.debug("Falied to create tosca element component {} error {}", newComponent.getUniqueId(), createToscaComponent.right().value());
530 return Either.right(createToscaComponent.right().value());
532 Resource newElement = createToscaComponent.left().value();
533 Either<GraphVertex, TitanOperationStatus> newVersionEither = titanDao.getVertexById(newElement.getUniqueId(), JsonParseFlagEnum.NoParse);
534 if (newVersionEither.isRight()) {
535 log.debug("Falied to fetch new tosca element component {} error {}", newComponent.getUniqueId(), newVersionEither.right().value());
536 return Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(newVersionEither.right().value()));
538 if (parentVertexEither.isLeft()) {
539 GraphVertex previousVersionV = parentVertexEither.left().value();
540 TitanOperationStatus createEdge = titanDao.createEdge(previousVersionV, newVersionEither.left().value(), EdgeLabelEnum.VERSION, null);
541 if (createEdge != TitanOperationStatus.OK) {
542 log.debug("Falied to associate to previous version {} new version {} error {}", previousVersionV.getUniqueId(), newVersionEither.right().value(), createEdge);
543 return Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(createEdge));
546 return Either.left(newElement);
551 * @param componentToUpdate
554 public <T extends Component> Either<T, StorageOperationStatus> updateToscaElement(T componentToUpdate) {
555 return updateToscaElement(componentToUpdate, new ComponentParametersView());
560 * @param componentToUpdate
562 * @param filterResult
565 public <T extends Component> Either<T, StorageOperationStatus> updateToscaElement(T componentToUpdate, ComponentParametersView filterResult) {
566 String componentId = componentToUpdate.getUniqueId();
567 Either<GraphVertex, TitanOperationStatus> getVertexEither = titanDao.getVertexById(componentId, JsonParseFlagEnum.ParseAll);
568 if (getVertexEither.isRight()) {
569 log.debug("Couldn't fetch component with and unique id {}, error: {}", componentId, getVertexEither.right().value());
570 return Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(getVertexEither.right().value()));
572 GraphVertex elementV = getVertexEither.left().value();
573 ToscaElementOperation toscaElementOperation = getToscaElementOperation(elementV);
575 ToscaElement toscaElementToUpdate = ModelConverter.convertToToscaElement(componentToUpdate);
576 Either<ToscaElement, StorageOperationStatus> updateToscaElement = toscaElementOperation.updateToscaElement(toscaElementToUpdate, elementV, filterResult);
577 if (updateToscaElement.isRight()) {
578 log.debug("Failed to update tosca element {} error {}", componentId, updateToscaElement.right().value());
579 return Either.right(updateToscaElement.right().value());
581 return Either.left(ModelConverter.convertFromToscaElement(updateToscaElement.left().value()));
584 private <T extends Component> Either<T, StorageOperationStatus> getLatestByName(GraphPropertyEnum property, String nodeName, JsonParseFlagEnum parseFlag) {
585 return getLatestByName(property, nodeName, parseFlag, new ComponentParametersView());
588 private <T extends Component> Either<T, StorageOperationStatus> getLatestByName(GraphPropertyEnum property, String nodeName, JsonParseFlagEnum parseFlag, ComponentParametersView filter) {
589 Either<T, StorageOperationStatus> result;
591 Map<GraphPropertyEnum, Object> propertiesToMatch = new EnumMap<>(GraphPropertyEnum.class);
592 Map<GraphPropertyEnum, Object> propertiesNotToMatch = new EnumMap<>(GraphPropertyEnum.class);
594 propertiesToMatch.put(property, nodeName);
595 propertiesToMatch.put(GraphPropertyEnum.IS_HIGHEST_VERSION, true);
597 propertiesNotToMatch.put(GraphPropertyEnum.IS_DELETED, true);
599 Either<List<GraphVertex>, TitanOperationStatus> highestResources = titanDao.getByCriteria(null, propertiesToMatch, propertiesNotToMatch, parseFlag);
600 if (highestResources.isRight()) {
601 TitanOperationStatus status = highestResources.right().value();
602 log.debug("failed to find resource with name {}. status={} ", nodeName, status);
603 result = Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(status));
607 List<GraphVertex> resources = highestResources.left().value();
608 double version = 0.0;
609 GraphVertex highestResource = null;
610 for (GraphVertex vertex : resources) {
611 Object versionObj = vertex.getMetadataProperty(GraphPropertyEnum.VERSION);
612 double resourceVersion = Double.valueOf((String) versionObj);
613 if (resourceVersion > version) {
614 version = resourceVersion;
615 highestResource = vertex;
618 return getToscaElementByOperation(highestResource, filter);
622 // region - Component Get By ..
623 private <T extends Component> Either<T, StorageOperationStatus> getLatestByName(GraphPropertyEnum property, String nodeName) {
624 return getLatestByName(property, nodeName, JsonParseFlagEnum.ParseMetadata);
627 public <T extends Component> Either<List<T>, StorageOperationStatus> getBySystemName(ComponentTypeEnum componentType, String systemName) {
629 Either<List<T>, StorageOperationStatus> result = null;
630 Either<T, StorageOperationStatus> getComponentRes;
631 List<T> components = new ArrayList<>();
632 List<GraphVertex> componentVertices;
633 Map<GraphPropertyEnum, Object> propertiesToMatch = new EnumMap<>(GraphPropertyEnum.class);
634 Map<GraphPropertyEnum, Object> propertiesNotToMatch = new EnumMap<>(GraphPropertyEnum.class);
636 propertiesToMatch.put(GraphPropertyEnum.SYSTEM_NAME, systemName);
637 if (componentType != null)
638 propertiesToMatch.put(GraphPropertyEnum.COMPONENT_TYPE, componentType.name());
640 propertiesNotToMatch.put(GraphPropertyEnum.IS_DELETED, true);
642 Either<List<GraphVertex>, TitanOperationStatus> getComponentsRes = titanDao.getByCriteria(null, propertiesToMatch, propertiesNotToMatch, JsonParseFlagEnum.ParseAll);
643 if (getComponentsRes.isRight()) {
644 TitanOperationStatus status = getComponentsRes.right().value();
645 log.debug("Failed to fetch the component with system name {}. Status is {} ", systemName, status);
646 result = Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(status));
648 if (result == null) {
649 componentVertices = getComponentsRes.left().value();
650 for (GraphVertex componentVertex : componentVertices) {
651 getComponentRes = getToscaElementByOperation(componentVertex);
652 if (getComponentRes.isRight()) {
653 log.debug("Failed to get the component {}. Status is {} ", componentVertex.getJsonMetadataField(JsonPresentationFields.NAME), getComponentRes.right().value());
654 result = Either.right(getComponentRes.right().value());
657 T componentBySystemName = getComponentRes.left().value();
658 log.debug("Found component, id: {}", componentBySystemName.getUniqueId());
659 components.add(componentBySystemName);
662 if (result == null) {
663 result = Either.left(components);
668 public <T extends Component> Either<T, StorageOperationStatus> getComponentByNameAndVersion(ComponentTypeEnum componentType, String name, String version) {
669 return getComponentByNameAndVersion(componentType, name, version, JsonParseFlagEnum.ParseAll);
672 public <T extends Component> Either<T, StorageOperationStatus> getComponentByNameAndVersion(ComponentTypeEnum componentType, String name, String version, JsonParseFlagEnum parseFlag) {
673 Either<T, StorageOperationStatus> result;
675 Map<GraphPropertyEnum, Object> hasProperties = new EnumMap<>(GraphPropertyEnum.class);
676 Map<GraphPropertyEnum, Object> hasNotProperties = new EnumMap<>(GraphPropertyEnum.class);
678 hasProperties.put(GraphPropertyEnum.NAME, name);
679 hasProperties.put(GraphPropertyEnum.VERSION, version);
680 hasNotProperties.put(GraphPropertyEnum.IS_DELETED, true);
681 if (componentType != null) {
682 hasProperties.put(GraphPropertyEnum.COMPONENT_TYPE, componentType.name());
684 Either<List<GraphVertex>, TitanOperationStatus> getResourceRes = titanDao.getByCriteria(null, hasProperties, hasNotProperties, parseFlag);
685 if (getResourceRes.isRight()) {
686 TitanOperationStatus status = getResourceRes.right().value();
687 log.debug("failed to find resource with name {}, version {}. Status is {} ", name, version, status);
688 result = Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(status));
691 return getToscaElementByOperation(getResourceRes.left().value().get(0));
693 public Either<List<CatalogComponent>, StorageOperationStatus> getCatalogComponents() {
694 return topologyTemplateOperation.getElementCatalogData();
698 public <T extends Component> Either<List<T>, StorageOperationStatus> getCatalogComponents(ComponentTypeEnum componentType, List<OriginTypeEnum> excludeTypes, boolean isHighestVersions) {
699 List<T> components = new ArrayList<>();
700 Either<List<ToscaElement>, StorageOperationStatus> catalogDataResult;
701 List<ToscaElement> toscaElements = new ArrayList<>();
702 List<ResourceTypeEnum> excludedResourceTypes = Optional.ofNullable(excludeTypes).orElse(Collections.emptyList()).stream().filter(type -> !type.equals(OriginTypeEnum.SERVICE)).map(type -> ResourceTypeEnum.getTypeByName(type.name()))
703 .collect(Collectors.toList());
705 switch (componentType) {
707 catalogDataResult = nodeTypeOperation.getElementCatalogData(ComponentTypeEnum.RESOURCE, excludedResourceTypes, isHighestVersions);
708 if (catalogDataResult.isRight()) {
709 return Either.right(catalogDataResult.right().value());
711 toscaElements = catalogDataResult.left().value();
714 if (excludeTypes != null && excludeTypes.contains(OriginTypeEnum.SERVICE)) {
717 catalogDataResult = topologyTemplateOperation.getElementCatalogData(ComponentTypeEnum.SERVICE, null, isHighestVersions);
718 if (catalogDataResult.isRight()) {
719 return Either.right(catalogDataResult.right().value());
721 toscaElements = catalogDataResult.left().value();
724 log.debug("Not supported component type {}", componentType);
725 return Either.right(StorageOperationStatus.BAD_REQUEST);
727 toscaElements.forEach(te -> {
728 T component = ModelConverter.convertFromToscaElement(te);
729 components.add(component);
731 return Either.left(components);
734 public Either<List<String>, StorageOperationStatus> deleteMarkedElements(ComponentTypeEnum componentType) {
735 Either<List<GraphVertex>, StorageOperationStatus> allComponentsMarkedForDeletion;
736 List<String> deleted = new ArrayList<>();
737 switch (componentType) {
739 allComponentsMarkedForDeletion = nodeTypeOperation.getAllComponentsMarkedForDeletion(componentType);
743 allComponentsMarkedForDeletion = topologyTemplateOperation.getAllComponentsMarkedForDeletion(componentType);
746 log.debug("Not supported component type {}", componentType);
747 return Either.right(StorageOperationStatus.BAD_REQUEST);
749 if (allComponentsMarkedForDeletion.isRight()) {
750 return Either.right(allComponentsMarkedForDeletion.right().value());
752 List<GraphVertex> allMarked = allComponentsMarkedForDeletion.left().value();
754 Either<List<GraphVertex>, TitanOperationStatus> allNotDeletedElements = topologyTemplateOperation.getAllNotDeletedElements();
755 if (allNotDeletedElements.isRight()) {
756 return Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(allNotDeletedElements.right().value()));
758 List<GraphVertex> allNonMarked = allNotDeletedElements.left().value();
759 for (GraphVertex elementV : allMarked) {
760 if (topologyTemplateOperation.isInUse(elementV, allNonMarked) == false) {
761 Either<ToscaElement, StorageOperationStatus> deleteToscaElement = deleteToscaElement(elementV);
762 if (deleteToscaElement.isRight()) {
763 log.debug("Failed to delete marked element {} error {}", elementV.getUniqueId(), deleteToscaElement.right().value());
766 deleted.add(elementV.getUniqueId());
767 log.debug("Marked element {} in use. don't delete it", elementV.getUniqueId());
770 return Either.left(deleted);
773 public Either<List<String>, StorageOperationStatus> getAllComponentsMarkedForDeletion(ComponentTypeEnum componentType) {
774 Either<List<GraphVertex>, StorageOperationStatus> allComponentsMarkedForDeletion;
775 switch (componentType) {
777 allComponentsMarkedForDeletion = nodeTypeOperation.getAllComponentsMarkedForDeletion(componentType);
781 allComponentsMarkedForDeletion = topologyTemplateOperation.getAllComponentsMarkedForDeletion(componentType);
784 log.debug("Not supported component type {}", componentType);
785 return Either.right(StorageOperationStatus.BAD_REQUEST);
787 if (allComponentsMarkedForDeletion.isRight()) {
788 return Either.right(allComponentsMarkedForDeletion.right().value());
790 return Either.left(allComponentsMarkedForDeletion.left().value().stream().map(v -> v.getUniqueId()).collect(Collectors.toList()));
793 public Either<Boolean, StorageOperationStatus> isComponentInUse(String componentId) {
794 Either<Boolean, StorageOperationStatus> result;
795 Either<List<GraphVertex>, TitanOperationStatus> allNotDeletedElements = topologyTemplateOperation.getAllNotDeletedElements();
796 if (allNotDeletedElements.isRight()) {
797 result = Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(allNotDeletedElements.right().value()));
799 result = Either.left(topologyTemplateOperation.isInUse(componentId, allNotDeletedElements.left().value()));
804 // region - Component Update
805 public Either<ImmutablePair<Component, String>, StorageOperationStatus> addComponentInstanceToTopologyTemplate(Component containerComponent, Component origComponent, ComponentInstance componentInstance, boolean allowDeleted, User user) {
807 Either<ImmutablePair<Component, String>, StorageOperationStatus> result = null;
808 Either<ToscaElement, StorageOperationStatus> updateContainerComponentRes = null;
809 if (StringUtils.isEmpty(componentInstance.getIcon())) {
810 componentInstance.setIcon(origComponent.getIcon());
812 String nameToFindForCounter = componentInstance.getOriginType() == OriginTypeEnum.ServiceProxy ? componentInstance.getSourceModelName() + PROXY_SUFFIX : origComponent.getName();
813 String nextComponentInstanceCounter = getNextComponentInstanceCounter(containerComponent, nameToFindForCounter);
814 Either<ImmutablePair<TopologyTemplate, String>, StorageOperationStatus> addResult = nodeTemplateOperation.addComponentInstanceToTopologyTemplate(ModelConverter.convertToToscaElement(containerComponent),
815 ModelConverter.convertToToscaElement(origComponent), nextComponentInstanceCounter, componentInstance, allowDeleted, user);
817 if (addResult.isRight()) {
818 CommonUtility.addRecordToLog(log, LogLevelEnum.DEBUG, "Failed to add the component instance {} to container component {}. ", componentInstance.getName(), containerComponent.getName());
819 result = Either.right(addResult.right().value());
821 if (result == null) {
822 updateContainerComponentRes = topologyTemplateOperation.getToscaElement(containerComponent.getUniqueId());
823 if (updateContainerComponentRes.isRight()) {
824 CommonUtility.addRecordToLog(log, LogLevelEnum.DEBUG, "Failed to fetch updated topology template {} with updated component instance {}. ", containerComponent.getName(), componentInstance.getName());
825 result = Either.right(updateContainerComponentRes.right().value());
828 if (result == null) {
829 Component updatedComponent = ModelConverter.convertFromToscaElement(updateContainerComponentRes.left().value());
830 String createdInstanceId = addResult.left().value().getRight();
831 CommonUtility.addRecordToLog(log, LogLevelEnum.TRACE, "The component instance {} has been added to container component {}. ", createdInstanceId, updatedComponent.getName());
832 result = Either.left(new ImmutablePair<>(updatedComponent, createdInstanceId));
837 public StorageOperationStatus associateComponentInstancesToComponent(Component containerComponent, Map<ComponentInstance, Resource> resourcesInstancesMap, boolean allowDeleted) {
839 StorageOperationStatus result = null;
840 CommonUtility.addRecordToLog(log, LogLevelEnum.DEBUG, "Going to add component instances to component {}", containerComponent.getUniqueId());
842 Either<GraphVertex, TitanOperationStatus> metadataVertex = titanDao.getVertexById(containerComponent.getUniqueId(), JsonParseFlagEnum.ParseAll);
843 if (metadataVertex.isRight()) {
844 TitanOperationStatus status = metadataVertex.right().value();
845 if (status == TitanOperationStatus.NOT_FOUND) {
846 status = TitanOperationStatus.INVALID_ID;
848 result = DaoStatusConverter.convertTitanStatusToStorageStatus(status);
850 if (result == null) {
851 result = nodeTemplateOperation.associateComponentInstancesToComponent(containerComponent, resourcesInstancesMap, metadataVertex.left().value(), allowDeleted);
856 public Either<ImmutablePair<Component, String>, StorageOperationStatus> updateComponentInstanceMetadataOfTopologyTemplate(Component containerComponent, Component origComponent, ComponentInstance componentInstance) {
858 Either<ImmutablePair<Component, String>, StorageOperationStatus> result = null;
860 CommonUtility.addRecordToLog(log, LogLevelEnum.TRACE, "Going to update the metadata of the component instance {} belonging to container component {}. ", componentInstance.getName(), containerComponent.getName());
861 componentInstance.setIcon(origComponent.getIcon());
862 Either<ImmutablePair<TopologyTemplate, String>, StorageOperationStatus> updateResult = nodeTemplateOperation.updateComponentInstanceMetadataOfTopologyTemplate(ModelConverter.convertToToscaElement(containerComponent),
863 ModelConverter.convertToToscaElement(origComponent), componentInstance);
864 if (updateResult.isRight()) {
865 CommonUtility.addRecordToLog(log, LogLevelEnum.DEBUG, "Failed to update the metadata of the component instance {} belonging to container component {}. ", componentInstance.getName(), containerComponent.getName());
866 result = Either.right(updateResult.right().value());
868 if (result == null) {
869 Component updatedComponent = ModelConverter.convertFromToscaElement(updateResult.left().value().getLeft());
870 String createdInstanceId = updateResult.left().value().getRight();
871 CommonUtility.addRecordToLog(log, LogLevelEnum.TRACE, "The metadata of the component instance {} has been updated to container component {}. ", createdInstanceId, updatedComponent.getName());
872 result = Either.left(new ImmutablePair<>(updatedComponent, createdInstanceId));
877 public Either<Component, StorageOperationStatus> updateComponentInstanceMetadataOfTopologyTemplate(Component containerComponent) {
878 return updateComponentInstanceMetadataOfTopologyTemplate(containerComponent, new ComponentParametersView());
881 public Either<Component, StorageOperationStatus> updateComponentInstanceMetadataOfTopologyTemplate(Component containerComponent, ComponentParametersView filter) {
883 Either<Component, StorageOperationStatus> result = null;
885 CommonUtility.addRecordToLog(log, LogLevelEnum.TRACE, "Going to update the metadata belonging to container component {}. ", containerComponent.getName());
887 Either<TopologyTemplate, StorageOperationStatus> updateResult = nodeTemplateOperation.updateComponentInstanceMetadataOfTopologyTemplate(ModelConverter.convertToToscaElement(containerComponent), filter);
888 if (updateResult.isRight()) {
889 CommonUtility.addRecordToLog(log, LogLevelEnum.DEBUG, "Failed to update the metadata belonging to container component {}. ", containerComponent.getName());
890 result = Either.right(updateResult.right().value());
892 if (result == null) {
893 Component updatedComponent = ModelConverter.convertFromToscaElement(updateResult.left().value());
894 CommonUtility.addRecordToLog(log, LogLevelEnum.TRACE, "The metadata has been updated to container component {}. ", updatedComponent.getName());
895 result = Either.left(updatedComponent);
901 public Either<ImmutablePair<Component, String>, StorageOperationStatus> deleteComponentInstanceFromTopologyTemplate(Component containerComponent, String resourceInstanceId) {
903 Either<ImmutablePair<Component, String>, StorageOperationStatus> result = null;
905 CommonUtility.addRecordToLog(log, LogLevelEnum.TRACE, "Going to delete the component instance {} belonging to container component {}. ", resourceInstanceId, containerComponent.getName());
907 Either<ImmutablePair<TopologyTemplate, String>, StorageOperationStatus> updateResult = nodeTemplateOperation.deleteComponentInstanceFromTopologyTemplate(ModelConverter.convertToToscaElement(containerComponent), resourceInstanceId);
908 if (updateResult.isRight()) {
909 CommonUtility.addRecordToLog(log, LogLevelEnum.DEBUG, "Failed to delete the component instance {} belonging to container component {}. ", resourceInstanceId, containerComponent.getName());
910 result = Either.right(updateResult.right().value());
912 if (result == null) {
913 Component updatedComponent = ModelConverter.convertFromToscaElement(updateResult.left().value().getLeft());
914 String deletedInstanceId = updateResult.left().value().getRight();
915 CommonUtility.addRecordToLog(log, LogLevelEnum.TRACE, "The component instance {} has been deleted from container component {}. ", deletedInstanceId, updatedComponent.getName());
916 result = Either.left(new ImmutablePair<>(updatedComponent, deletedInstanceId));
921 private String getNextComponentInstanceCounter(Component containerComponent, String originResourceName) {
923 Integer nextCounter = 0;
925 if (CollectionUtils.isNotEmpty(containerComponent.getComponentInstances())) {
927 String normalizedName = ValidationUtils.normalizeComponentInstanceName(originResourceName);
928 Integer maxCounterFromNames = getMaxCounterFromNames(containerComponent, normalizedName);
929 Integer maxCounterFromIds = getMaxCounterFromIds(containerComponent, normalizedName);
931 if (maxCounterFromNames == null && maxCounterFromIds != null) {
932 nextCounter = maxCounterFromIds + 1;
933 } else if (maxCounterFromIds == null && maxCounterFromNames != null) {
934 nextCounter = maxCounterFromNames + 1;
935 } else if (maxCounterFromIds != null && maxCounterFromNames != null) {
936 nextCounter = maxCounterFromNames > maxCounterFromIds ? maxCounterFromNames + 1 : maxCounterFromIds + 1;
939 return nextCounter.toString();
942 private Integer getMaxCounterFromNames(Component containerComponent, String normalizedName) {
944 Integer maxCounter = 0;
945 List<String> countersStr = containerComponent.getComponentInstances().stream().filter(ci -> ci.getNormalizedName() != null && ci.getNormalizedName().startsWith(normalizedName)).map(ci -> ci.getNormalizedName().split(normalizedName)[1])
946 .collect(Collectors.toList());
948 if (CollectionUtils.isEmpty(countersStr)) {
951 Integer currCounter = null;
952 for (String counter : countersStr) {
953 if (StringUtils.isEmpty(counter)) {
957 currCounter = Integer.parseInt(counter);
958 } catch (Exception e) {
961 maxCounter = maxCounter < currCounter ? currCounter : maxCounter;
963 if (currCounter == null) {
969 private Integer getMaxCounterFromIds(Component containerComponent, String normalizedName) {
971 Integer maxCounter = 0;
972 List<String> countersStr = containerComponent.getComponentInstances().stream().filter(ci -> ci.getUniqueId() != null && ci.getUniqueId().contains(normalizedName)).map(ci -> ci.getUniqueId().split(normalizedName)[1])
973 .collect(Collectors.toList());
975 if (CollectionUtils.isEmpty(countersStr)) {
978 Integer currCounter = null;
979 for (String counter : countersStr) {
980 if (StringUtils.isEmpty(counter)) {
984 currCounter = Integer.parseInt(counter);
985 } catch (Exception e) {
988 maxCounter = maxCounter < currCounter ? currCounter : maxCounter;
990 if (currCounter == null) {
996 public Either<RequirementCapabilityRelDef, StorageOperationStatus> associateResourceInstances(String componentId, RequirementCapabilityRelDef requirementDef) {
997 return nodeTemplateOperation.associateResourceInstances(componentId, requirementDef);
1001 public Either<List<InputDefinition>, StorageOperationStatus> createAndAssociateInputs(Map<String, InputDefinition> inputs, String componentId) {
1003 Either<GraphVertex, TitanOperationStatus> getVertexEither = titanDao.getVertexById(componentId, JsonParseFlagEnum.NoParse);
1004 if (getVertexEither.isRight()) {
1005 log.debug("Couldn't fetch component with and unique id {}, error: {}", componentId, getVertexEither.right().value());
1006 return Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(getVertexEither.right().value()));
1010 GraphVertex vertex = getVertexEither.left().value();
1011 Map<String, PropertyDataDefinition> inputsMap = inputs.entrySet().stream().collect(Collectors.toMap(Map.Entry::getKey, e -> new PropertyDataDefinition(e.getValue())));
1013 StorageOperationStatus status = topologyTemplateOperation.associateInputsToComponent(vertex, inputsMap, componentId);
1015 if (StorageOperationStatus.OK == status) {
1016 log.debug("Component created successfully!!!");
1017 List<InputDefinition> inputsResList = null;
1018 if (inputsMap != null && !inputsMap.isEmpty()) {
1019 inputsResList = inputsMap.values().stream().map(i -> new InputDefinition(i)).collect(Collectors.toList());
1021 return Either.left(inputsResList);
1023 return Either.right(status);
1027 public Either<List<InputDefinition>, StorageOperationStatus> addInputsToComponent(Map<String, InputDefinition> inputs, String componentId) {
1029 Either<GraphVertex, TitanOperationStatus> getVertexEither = titanDao.getVertexById(componentId, JsonParseFlagEnum.NoParse);
1030 if (getVertexEither.isRight()) {
1031 log.debug("Couldn't fetch component with and unique id {}, error: {}", componentId, getVertexEither.right().value());
1032 return Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(getVertexEither.right().value()));
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())));
1039 StorageOperationStatus status = topologyTemplateOperation.addToscaDataToToscaElement(vertex, EdgeLabelEnum.INPUTS, VertexTypeEnum.INPUTS, inputsMap, JsonPresentationFields.NAME);
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().map(i -> new InputDefinition(i)).collect(Collectors.toList());
1047 return Either.left(inputsResList);
1049 return Either.right(status);
1053 public Either<List<InputDefinition>, StorageOperationStatus> updateInputsToComponent(List<InputDefinition> inputs, String componentId) {
1055 Either<GraphVertex, TitanOperationStatus> getVertexEither = titanDao.getVertexById(componentId, JsonParseFlagEnum.NoParse);
1056 if (getVertexEither.isRight()) {
1057 log.debug("Couldn't fetch component with and unique id {}, error: {}", componentId, getVertexEither.right().value());
1058 return Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(getVertexEither.right().value()));
1062 GraphVertex vertex = getVertexEither.left().value();
1063 List<PropertyDataDefinition> inputsAsDataDef = inputs.stream().map(PropertyDataDefinition::new).collect(Collectors.toList());
1065 StorageOperationStatus status = topologyTemplateOperation.updateToscaDataOfToscaElement(vertex, EdgeLabelEnum.INPUTS, VertexTypeEnum.INPUTS, inputsAsDataDef, JsonPresentationFields.NAME);
1067 if (StorageOperationStatus.OK == status) {
1068 log.debug("Component created successfully!!!");
1069 List<InputDefinition> inputsResList = null;
1070 if (inputsAsDataDef != null && !inputsAsDataDef.isEmpty()) {
1071 inputsResList = inputsAsDataDef.stream().map(InputDefinition::new).collect(Collectors.toList());
1073 return Either.left(inputsResList);
1075 return Either.right(status);
1079 // region - ComponentInstance
1080 public Either<Map<String, List<ComponentInstanceProperty>>, StorageOperationStatus> associateComponentInstancePropertiesToComponent(Map<String, List<ComponentInstanceProperty>> instProperties, String componentId) {
1082 Either<GraphVertex, TitanOperationStatus> getVertexEither = titanDao.getVertexById(componentId, JsonParseFlagEnum.NoParse);
1083 if (getVertexEither.isRight()) {
1084 log.debug("Couldn't fetch component with and unique id {}, error: {}", componentId, getVertexEither.right().value());
1085 return Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(getVertexEither.right().value()));
1089 GraphVertex vertex = getVertexEither.left().value();
1090 Map<String, MapPropertiesDataDefinition> instPropsMap = new HashMap<>();
1091 if (instProperties != null) {
1093 MapPropertiesDataDefinition propertiesMap;
1094 for (Entry<String, List<ComponentInstanceProperty>> entry : instProperties.entrySet()) {
1095 propertiesMap = new MapPropertiesDataDefinition();
1097 propertiesMap.setMapToscaDataDefinition(entry.getValue().stream().map(e -> new PropertyDataDefinition(e)).collect(Collectors.toMap(e -> e.getName(), e -> e)));
1099 instPropsMap.put(entry.getKey(), propertiesMap);
1103 StorageOperationStatus status = topologyTemplateOperation.associateInstPropertiesToComponent(vertex, instPropsMap);
1105 if (StorageOperationStatus.OK == status) {
1106 log.debug("Component created successfully!!!");
1107 return Either.left(instProperties);
1109 return Either.right(status);
1114 * saves the instInputs as the updated instance inputs of the component container in DB
1116 * @param componentId
1119 public Either<Map<String, List<ComponentInstanceInput>>, StorageOperationStatus> updateComponentInstanceInputsToComponent(Map<String, List<ComponentInstanceInput>> instInputs, String componentId) {
1120 if (instInputs == null || instInputs.isEmpty()) {
1121 return Either.left(instInputs);
1123 StorageOperationStatus status;
1124 for ( Entry<String, List<ComponentInstanceInput>> inputsPerIntance : instInputs.entrySet() ) {
1125 List<ComponentInstanceInput> toscaDataListPerInst = inputsPerIntance.getValue();
1126 List<String> pathKeysPerInst = new ArrayList<>();
1127 pathKeysPerInst.add(inputsPerIntance.getKey());
1128 status = topologyTemplateOperation.updateToscaDataDeepElementsOfToscaElement(componentId, EdgeLabelEnum.INST_INPUTS, VertexTypeEnum.INST_INPUTS, toscaDataListPerInst, pathKeysPerInst, JsonPresentationFields.NAME);
1129 if ( status != StorageOperationStatus.OK) {
1130 log.debug("Failed to update component instance inputs for instance {} in component {} edge type {} error {}", inputsPerIntance.getKey(), componentId, EdgeLabelEnum.INST_INPUTS, status);
1131 return Either.right(status);
1135 return Either.left(instInputs);
1139 * saves the instProps as the updated instance properties of the component container in DB
1141 * @param componentId
1144 public Either<Map<String, List<ComponentInstanceProperty>>, StorageOperationStatus> updateComponentInstancePropsToComponent(Map<String, List<ComponentInstanceProperty>> instProps, String componentId) {
1145 if (instProps == null || instProps.isEmpty()) {
1146 return Either.left(instProps);
1148 StorageOperationStatus status;
1149 for ( Entry<String, List<ComponentInstanceProperty>> propsPerIntance : instProps.entrySet() ) {
1150 List<ComponentInstanceProperty> toscaDataListPerInst = propsPerIntance.getValue();
1151 List<String> pathKeysPerInst = new ArrayList<>();
1152 pathKeysPerInst.add(propsPerIntance.getKey());
1153 status = topologyTemplateOperation.updateToscaDataDeepElementsOfToscaElement(componentId, EdgeLabelEnum.INST_PROPERTIES, VertexTypeEnum.INST_PROPERTIES, toscaDataListPerInst, pathKeysPerInst, JsonPresentationFields.NAME);
1154 if ( status != StorageOperationStatus.OK) {
1155 log.debug("Failed to update component instance inputs for instance {} in component {} edge type {} error {}", propsPerIntance.getKey(), componentId, EdgeLabelEnum.INST_PROPERTIES, status);
1156 return Either.right(status);
1160 return Either.left(instProps);
1163 public Either<Map<String, List<ComponentInstanceInput>>, StorageOperationStatus> associateComponentInstanceInputsToComponent(Map<String, List<ComponentInstanceInput>> instInputs, String componentId) {
1165 Either<GraphVertex, TitanOperationStatus> getVertexEither = titanDao.getVertexById(componentId, JsonParseFlagEnum.NoParse);
1166 if (getVertexEither.isRight()) {
1167 log.debug("Couldn't fetch component with and unique id {}, error: {}", componentId, getVertexEither.right().value());
1168 return Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(getVertexEither.right().value()));
1171 GraphVertex vertex = getVertexEither.left().value();
1172 Map<String, MapPropertiesDataDefinition> instPropsMap = new HashMap<>();
1173 if (instInputs != null) {
1175 MapPropertiesDataDefinition propertiesMap;
1176 for (Entry<String, List<ComponentInstanceInput>> entry : instInputs.entrySet()) {
1177 propertiesMap = new MapPropertiesDataDefinition();
1179 propertiesMap.setMapToscaDataDefinition(entry.getValue().stream().map(e -> new PropertyDataDefinition(e)).collect(Collectors.toMap(e -> e.getName(), e -> e)));
1181 instPropsMap.put(entry.getKey(), propertiesMap);
1185 StorageOperationStatus status = topologyTemplateOperation.associateInstInputsToComponent(vertex, instPropsMap);
1187 if (StorageOperationStatus.OK == status) {
1188 log.debug("Component created successfully!!!");
1189 return Either.left(instInputs);
1191 return Either.right(status);
1195 public Either<Map<String, List<ComponentInstanceInput>>, StorageOperationStatus> addComponentInstanceInputsToComponent(Component containerComponent, Map<String, List<ComponentInstanceInput>> instProperties) {
1197 StorageOperationStatus status = StorageOperationStatus.OK;
1198 if (instProperties != null) {
1200 for (Entry<String, List<ComponentInstanceInput>> entry : instProperties.entrySet()) {
1201 List<ComponentInstanceInput> props = entry.getValue();
1202 String componentInstanseId = entry.getKey();
1203 if (props != null && !props.isEmpty()) {
1204 for (ComponentInstanceInput property : props) {
1205 List<ComponentInstanceInput> componentInstancesInputs = containerComponent.getComponentInstancesInputs().get(componentInstanseId);
1206 Optional<ComponentInstanceInput> instanceProperty = componentInstancesInputs.stream().filter(p -> p.getName().equals(property.getName())).findAny();
1207 if (instanceProperty.isPresent()) {
1208 status = updateComponentInstanceInput(containerComponent, componentInstanseId, property);
1210 status = addComponentInstanceInput(containerComponent, componentInstanseId, property);
1212 if (status != StorageOperationStatus.OK) {
1213 log.debug("Failed to update instance input {} for instance {} error {} ", property, componentInstanseId, status);
1214 return Either.right(status);
1216 log.trace("instance input {} for instance {} updated", property, componentInstanseId);
1222 return Either.left(instProperties);
1225 public Either<Map<String, List<ComponentInstanceProperty>>, StorageOperationStatus> addComponentInstancePropertiesToComponent(Component containerComponent, Map<String, List<ComponentInstanceProperty>> instProperties, String componentId) {
1227 if (instProperties != null) {
1229 for (Entry<String, List<ComponentInstanceProperty>> entry : instProperties.entrySet()) {
1230 List<ComponentInstanceProperty> props = entry.getValue();
1231 String componentInstanseId = entry.getKey();
1232 List<ComponentInstanceProperty> instanceProperties = containerComponent.getComponentInstancesProperties().get(componentInstanseId);
1233 if (props != null && !props.isEmpty()) {
1234 for (ComponentInstanceProperty property : props) {
1235 Optional<ComponentInstanceProperty> instanceProperty = instanceProperties.stream().filter(p -> p.getUniqueId().equals(property.getUniqueId())).findAny();
1236 if (instanceProperty.isPresent()) {
1237 updateComponentInstanceProperty(containerComponent, componentInstanseId, property);
1239 addComponentInstanceProperty(containerComponent, componentInstanseId, property);
1247 return Either.left(instProperties);
1251 public StorageOperationStatus associateDeploymentArtifactsToInstances(Map<String, Map<String, ArtifactDefinition>> instDeploymentArtifacts, String componentId, User user) {
1253 Either<GraphVertex, TitanOperationStatus> getVertexEither = titanDao.getVertexById(componentId, JsonParseFlagEnum.NoParse);
1254 if (getVertexEither.isRight()) {
1255 log.debug("Couldn't fetch component with and unique id {}, error: {}", componentId, getVertexEither.right().value());
1256 return DaoStatusConverter.convertTitanStatusToStorageStatus(getVertexEither.right().value());
1260 GraphVertex vertex = getVertexEither.left().value();
1261 Map<String, MapArtifactDataDefinition> instArtMap = new HashMap<>();
1262 if (instDeploymentArtifacts != null) {
1264 MapArtifactDataDefinition artifactsMap;
1265 for (Entry<String, Map<String, ArtifactDefinition>> entry : instDeploymentArtifacts.entrySet()) {
1266 Map<String, ArtifactDefinition> artList = entry.getValue();
1267 Map<String, ArtifactDataDefinition> artifacts = artList.entrySet().stream().collect(Collectors.toMap(Map.Entry::getKey, e -> new ArtifactDataDefinition(e.getValue())));
1268 artifactsMap = nodeTemplateOperation.prepareInstDeploymentArtifactPerInstance(artifacts, entry.getKey(), user, NodeTemplateOperation.HEAT_VF_ENV_NAME);
1270 instArtMap.put(entry.getKey(), artifactsMap);
1274 return topologyTemplateOperation.associateInstDeploymentArtifactsToComponent(vertex, instArtMap);
1278 public StorageOperationStatus associateArtifactsToInstances(Map<String, Map<String, ArtifactDefinition>> instArtifacts, String componentId, User user) {
1280 Either<GraphVertex, TitanOperationStatus> getVertexEither = titanDao.getVertexById(componentId, JsonParseFlagEnum.NoParse);
1281 if (getVertexEither.isRight()) {
1282 log.debug("Couldn't fetch component with and unique id {}, error: {}", componentId, getVertexEither.right().value());
1283 return DaoStatusConverter.convertTitanStatusToStorageStatus(getVertexEither.right().value());
1287 GraphVertex vertex = getVertexEither.left().value();
1288 Map<String, MapArtifactDataDefinition> instArtMap = new HashMap<>();
1289 if (instArtifacts != null) {
1291 MapArtifactDataDefinition artifactsMap;
1292 for (Entry<String, Map<String, ArtifactDefinition>> entry : instArtifacts.entrySet()) {
1293 Map<String, ArtifactDefinition> artList = entry.getValue();
1294 Map<String, ArtifactDataDefinition> artifacts = artList.entrySet().stream().collect(Collectors.toMap(Map.Entry::getKey, e -> new ArtifactDataDefinition(e.getValue())));
1295 artifactsMap = new MapArtifactDataDefinition(artifacts);
1297 instArtMap.put(entry.getKey(), artifactsMap);
1301 return topologyTemplateOperation.associateInstArtifactsToComponent(vertex, instArtMap);
1305 public StorageOperationStatus associateInstAttributeToComponentToInstances(Map<String, List<PropertyDefinition>> instArttributes, String componentId) {
1307 Either<GraphVertex, TitanOperationStatus> getVertexEither = titanDao.getVertexById(componentId, JsonParseFlagEnum.NoParse);
1308 if (getVertexEither.isRight()) {
1309 log.debug("Couldn't fetch component with and unique id {}, error: {}", componentId, getVertexEither.right().value());
1310 return DaoStatusConverter.convertTitanStatusToStorageStatus(getVertexEither.right().value());
1314 GraphVertex vertex = getVertexEither.left().value();
1315 Map<String, MapPropertiesDataDefinition> instAttr = new HashMap<>();
1316 if (instArttributes != null) {
1318 MapPropertiesDataDefinition attributesMap;
1319 for (Entry<String, List<PropertyDefinition>> entry : instArttributes.entrySet()) {
1320 attributesMap = new MapPropertiesDataDefinition();
1321 attributesMap.setMapToscaDataDefinition(entry.getValue().stream().map(e -> new PropertyDataDefinition(e)).collect(Collectors.toMap(e -> e.getName(), e -> e)));
1322 instAttr.put(entry.getKey(), attributesMap);
1326 return topologyTemplateOperation.associateInstAttributeToComponent(vertex, instAttr);
1331 public StorageOperationStatus associateCalculatedCapReq(Map<ComponentInstance, Map<String, List<CapabilityDefinition>>> instCapabilties, Map<ComponentInstance, Map<String, List<RequirementDefinition>>> instReg, String componentId) {
1332 Either<GraphVertex, TitanOperationStatus> getVertexEither = titanDao.getVertexById(componentId, JsonParseFlagEnum.NoParse);
1333 if (getVertexEither.isRight()) {
1334 log.debug("Couldn't fetch component with and unique id {}, error: {}", componentId, getVertexEither.right().value());
1335 return DaoStatusConverter.convertTitanStatusToStorageStatus(getVertexEither.right().value());
1339 GraphVertex vertex = getVertexEither.left().value();
1341 Map<String, MapListRequirementDataDefinition> calcRequirements = new HashMap<>();
1343 Map<String, MapListCapabiltyDataDefinition> calcCapabilty = new HashMap<>();
1344 Map<String, MapCapabiltyProperty> calculatedCapabilitiesProperties = new HashMap<>();
1346 if (instCapabilties != null) {
1347 for (Entry<ComponentInstance, Map<String, List<CapabilityDefinition>>> entry : instCapabilties.entrySet()) {
1349 Map<String, List<CapabilityDefinition>> caps = entry.getValue();
1350 Map<String, ListCapabilityDataDefinition> mapToscaDataDefinition = new HashMap<>();
1351 for (Entry<String, List<CapabilityDefinition>> instCapability : caps.entrySet()) {
1352 mapToscaDataDefinition.put(instCapability.getKey(), new ListCapabilityDataDefinition(instCapability.getValue().stream().map(iCap -> new CapabilityDataDefinition(iCap)).collect(Collectors.toList())));
1355 ComponentInstanceDataDefinition componentInstance = new ComponentInstanceDataDefinition(entry.getKey());
1356 MapListCapabiltyDataDefinition capMap = nodeTemplateOperation.prepareCalculatedCapabiltyForNodeType(mapToscaDataDefinition, componentInstance);
1358 MapCapabiltyProperty mapCapabiltyProperty = ModelConverter.convertToMapOfMapCapabiltyProperties(caps, componentInstance.getUniqueId(), true);
1360 calcCapabilty.put(entry.getKey().getUniqueId(), capMap);
1361 calculatedCapabilitiesProperties.put(entry.getKey().getUniqueId(), mapCapabiltyProperty);
1365 if (instReg != null) {
1366 for (Entry<ComponentInstance, Map<String, List<RequirementDefinition>>> entry : instReg.entrySet()) {
1368 Map<String, List<RequirementDefinition>> req = entry.getValue();
1369 Map<String, ListRequirementDataDefinition> mapToscaDataDefinition = new HashMap<>();
1370 for (Entry<String, List<RequirementDefinition>> instReq : req.entrySet()) {
1371 mapToscaDataDefinition.put(instReq.getKey(), new ListRequirementDataDefinition(instReq.getValue().stream().map(iCap -> new RequirementDataDefinition(iCap)).collect(Collectors.toList())));
1374 MapListRequirementDataDefinition capMap = nodeTemplateOperation.prepareCalculatedRequirementForNodeType(mapToscaDataDefinition, new ComponentInstanceDataDefinition(entry.getKey()));
1376 calcRequirements.put(entry.getKey().getUniqueId(), capMap);
1380 StorageOperationStatus status = topologyTemplateOperation.associateCalcCapReqToComponent(vertex, calcRequirements, calcCapabilty, calculatedCapabilitiesProperties);
1385 private Either<List<Service>, StorageOperationStatus> getLatestVersionNonCheckoutServicesMetadataOnly(Map<GraphPropertyEnum, Object> hasProps, Map<GraphPropertyEnum, Object> hasNotProps) {
1386 List<Service> services = new ArrayList<>();
1387 List<LifecycleStateEnum> states = new ArrayList<>();
1389 hasProps.put(GraphPropertyEnum.COMPONENT_TYPE, ComponentTypeEnum.SERVICE.name());
1390 hasProps.put(GraphPropertyEnum.IS_HIGHEST_VERSION, true);
1393 states.add(LifecycleStateEnum.NOT_CERTIFIED_CHECKOUT);
1394 hasNotProps.put(GraphPropertyEnum.STATE, states);
1395 hasNotProps.put(GraphPropertyEnum.IS_DELETED, true);
1396 return fetchServicesByCriteria(services, hasProps, hasNotProps);
1399 private Either<List<Component>, StorageOperationStatus> getLatestVersionNotAbstractToscaElementsMetadataOnly(boolean isAbstract, Boolean isHighest, ComponentTypeEnum componentTypeEnum, String internalComponentType, VertexTypeEnum vertexType) {
1400 List<Service> services = null;
1401 Map<GraphPropertyEnum, Object> hasProps = new EnumMap<>(GraphPropertyEnum.class);
1402 Map<GraphPropertyEnum, Object> hasNotProps = new EnumMap<>(GraphPropertyEnum.class);
1403 fillPropsMap(hasProps, hasNotProps, internalComponentType, componentTypeEnum, isAbstract, vertexType);
1404 Either<List<GraphVertex>, TitanOperationStatus> getRes = titanDao.getByCriteria(vertexType, hasProps, hasNotProps, JsonParseFlagEnum.ParseMetadata);
1405 if (getRes.isRight()) {
1406 if (getRes.right().value().equals(TitanOperationStatus.NOT_FOUND)) {
1407 return Either.left(new ArrayList<>());
1409 return Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(getRes.right().value()));
1412 // region -> Fetch non checked-out services
1413 if (internalComponentType != null && internalComponentType.toLowerCase().trim().equals("service") && VertexTypeEnum.NODE_TYPE == vertexType) { // and NODE_TYPE==vertextype
1414 Either<List<Service>, StorageOperationStatus> result = getLatestVersionNonCheckoutServicesMetadataOnly(new EnumMap<>(GraphPropertyEnum.class), new EnumMap<>(GraphPropertyEnum.class));
1415 if (result.isRight()) {
1416 log.debug("Failed to fetch services for");
1417 return Either.right(result.right().value());
1419 services = result.left().value();
1420 if (CollectionUtils.isEmpty(services) && log.isTraceEnabled())
1421 log.trace("No relevant services available");
1424 List<Component> nonAbstractLatestComponents = new ArrayList<>();
1425 ComponentParametersView params = new ComponentParametersView(true);
1426 params.setIgnoreAllVersions(false);
1427 for (GraphVertex vertexComponent : getRes.left().value()) {
1428 Either<ToscaElement, StorageOperationStatus> componentRes = topologyTemplateOperation.getLightComponent(vertexComponent, componentTypeEnum, params);
1429 if (componentRes.isRight()) {
1430 log.debug("Failed to fetch ligth element for {} error {}", vertexComponent.getUniqueId(), componentRes.right().value());
1431 return Either.right(componentRes.right().value());
1433 Component component = ModelConverter.convertFromToscaElement(componentRes.left().value());
1434 nonAbstractLatestComponents.add(component);
1437 if (CollectionUtils.isNotEmpty(services))
1438 nonAbstractLatestComponents.addAll(services);
1439 return Either.left(nonAbstractLatestComponents);
1443 public Either<ComponentMetadataData, StorageOperationStatus> getLatestComponentMetadataByUuid(String componentUuid, JsonParseFlagEnum parseFlag, Boolean isHighest) {
1445 Either<ComponentMetadataData, StorageOperationStatus> result;
1447 Map<GraphPropertyEnum, Object> hasProperties = new EnumMap<>(GraphPropertyEnum.class);
1449 hasProperties.put(GraphPropertyEnum.UUID, componentUuid);
1450 if (isHighest != null) {
1451 hasProperties.put(GraphPropertyEnum.IS_HIGHEST_VERSION, isHighest.booleanValue());
1454 Map<GraphPropertyEnum, Object> propertiesNotToMatch = new EnumMap<>(GraphPropertyEnum.class);
1455 propertiesNotToMatch.put(GraphPropertyEnum.IS_DELETED, true);
1457 Either<List<GraphVertex>, TitanOperationStatus> getRes = titanDao.getByCriteria(null, hasProperties, propertiesNotToMatch, parseFlag);
1458 if (getRes.isRight()) {
1459 result = Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(getRes.right().value()));
1461 List<ComponentMetadataData> latestVersionList = getRes.left().value().stream().map(ModelConverter::convertToComponentMetadata).collect(Collectors.toList());
1462 ComponentMetadataData latestVersion = latestVersionList.size() == 1 ? latestVersionList.get(0)
1463 : latestVersionList.stream().max((c1, c2) -> Double.compare(Double.parseDouble(c1.getMetadataDataDefinition().getVersion()), Double.parseDouble(c2.getMetadataDataDefinition().getVersion()))).get();
1464 result = Either.left(latestVersion);
1469 public Either<ComponentMetadataData, StorageOperationStatus> getComponentMetadata(String componentId) {
1471 Either<ComponentMetadataData, StorageOperationStatus> result;
1472 Either<GraphVertex, TitanOperationStatus> getRes = titanDao.getVertexById(componentId, JsonParseFlagEnum.ParseMetadata);
1473 if (getRes.isRight()) {
1474 result = Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(getRes.right().value()));
1476 ComponentMetadataData componentMetadata = ModelConverter.convertToComponentMetadata(getRes.left().value());
1477 result = Either.left(componentMetadata);
1482 public Either<List<Component>, StorageOperationStatus> getLatestVersionNotAbstractComponents(boolean isAbstract, Boolean isHighest, ComponentTypeEnum componentTypeEnum, String internalComponentType, List<String> componentUids) {
1484 Either<List<Component>, StorageOperationStatus> result = null;
1485 List<Component> components = new ArrayList<>();
1486 if (componentUids == null) {
1487 Either<List<String>, StorageOperationStatus> componentUidsRes = getComponentUids(isAbstract, isHighest, componentTypeEnum, internalComponentType, componentUids);
1488 if (componentUidsRes.isRight()) {
1489 result = Either.right(componentUidsRes.right().value());
1491 componentUids = componentUidsRes.left().value();
1494 if (!componentUids.isEmpty()) {
1495 for (String componentUid : componentUids) {
1496 ComponentParametersView componentParametersView = buildComponentViewForNotAbstract();
1497 if (internalComponentType != null && "vl".equalsIgnoreCase(internalComponentType)) {
1498 componentParametersView.setIgnoreCapabilities(false);
1499 componentParametersView.setIgnoreRequirements(false);
1501 Either<ToscaElement, StorageOperationStatus> getToscaElementRes = nodeTemplateOperation.getToscaElementOperation(componentTypeEnum).getLightComponent(componentUid, componentTypeEnum, componentParametersView);
1502 if (getToscaElementRes.isRight()) {
1503 if (log.isDebugEnabled())
1504 log.debug("Failed to fetch resource for error is {}", getToscaElementRes.right().value());
1505 result = Either.right(getToscaElementRes.right().value());
1508 Component component = ModelConverter.convertFromToscaElement(getToscaElementRes.left().value());
1509 component.setContactId(null);
1510 component.setCreationDate(null);
1511 component.setCreatorUserId(null);
1512 component.setCreatorFullName(null);
1513 component.setLastUpdateDate(null);
1514 component.setLastUpdaterUserId(null);
1515 component.setLastUpdaterFullName(null);
1516 component.setNormalizedName(null);
1517 components.add(component);
1520 if (result == null) {
1521 result = Either.left(components);
1526 private Either<List<String>, StorageOperationStatus> getComponentUids(boolean isAbstract, Boolean isHighest, ComponentTypeEnum componentTypeEnum, String internalComponentType, List<String> componentUids) {
1528 Either<List<String>, StorageOperationStatus> result = null;
1529 Either<List<Component>, StorageOperationStatus> getToscaElementsRes = getLatestVersionNotAbstractMetadataOnly(isAbstract, isHighest, componentTypeEnum, internalComponentType);
1530 if (getToscaElementsRes.isRight()) {
1531 result = Either.right(getToscaElementsRes.right().value());
1533 List<Component> collection = getToscaElementsRes.left().value();
1534 if (collection == null) {
1535 componentUids = new ArrayList<>();
1537 componentUids = collection.stream().map(p -> p.getUniqueId()).collect(Collectors.toList());
1540 if (result == null) {
1541 result = Either.left(componentUids);
1546 private ComponentParametersView buildComponentViewForNotAbstract() {
1547 ComponentParametersView componentParametersView = new ComponentParametersView();
1548 componentParametersView.disableAll();
1549 componentParametersView.setIgnoreCategories(false);
1550 componentParametersView.setIgnoreAllVersions(false);
1551 return componentParametersView;
1554 public Either<Boolean, StorageOperationStatus> validateComponentNameExists(String name, ResourceTypeEnum resourceType, ComponentTypeEnum componentType) {
1555 Either<Boolean, StorageOperationStatus> result = validateComponentNameUniqueness(name, resourceType, componentType);
1556 if (result.isLeft()) {
1557 result = Either.left(!result.left().value());
1562 public Either<Boolean, StorageOperationStatus> validateComponentNameUniqueness(String name, ResourceTypeEnum resourceType, ComponentTypeEnum componentType) {
1563 VertexTypeEnum vertexType = ModelConverter.isAtomicComponent(resourceType) ? VertexTypeEnum.NODE_TYPE : VertexTypeEnum.TOPOLOGY_TEMPLATE;
1564 String normalizedName = ValidationUtils.normaliseComponentName(name);
1565 Map<GraphPropertyEnum, Object> properties = new EnumMap<>(GraphPropertyEnum.class);
1566 properties.put(GraphPropertyEnum.NORMALIZED_NAME, normalizedName);
1567 properties.put(GraphPropertyEnum.COMPONENT_TYPE, componentType.name());
1569 Either<List<GraphVertex>, TitanOperationStatus> vertexEither = titanDao.getByCriteria(vertexType, properties, JsonParseFlagEnum.NoParse);
1570 if (vertexEither.isRight() && vertexEither.right().value() != TitanOperationStatus.NOT_FOUND) {
1571 log.debug("failed to get vertex from graph with property normalizedName: {}", normalizedName);
1572 return Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(vertexEither.right().value()));
1574 List<GraphVertex> vertexList = vertexEither.isLeft() ? vertexEither.left().value() : null;
1575 if (vertexList != null && !vertexList.isEmpty()) {
1576 return Either.left(false);
1578 return Either.left(true);
1582 private void fillNodeTypePropsMap(Map<GraphPropertyEnum, Object> hasProps, Map<GraphPropertyEnum, Object> hasNotProps, String internalComponentType) {
1583 switch (internalComponentType.toLowerCase()) {
1586 hasNotProps.put(GraphPropertyEnum.RESOURCE_TYPE, Arrays.asList(ResourceTypeEnum.VFCMT.name(), ResourceTypeEnum.Configuration.name()));
1591 hasNotProps.put(GraphPropertyEnum.RESOURCE_TYPE, Arrays.asList(ResourceTypeEnum.VFC.name(), ResourceTypeEnum.VFCMT.name()));
1594 hasProps.put(GraphPropertyEnum.RESOURCE_TYPE, ResourceTypeEnum.VL.name());
1601 private void fillTopologyTemplatePropsMap(Map<GraphPropertyEnum, Object> hasProps, Map<GraphPropertyEnum, Object> hasNotProps, ComponentTypeEnum componentTypeEnum, String internalComponentType) {
1602 switch (componentTypeEnum) {
1604 hasProps.put(GraphPropertyEnum.COMPONENT_TYPE, ComponentTypeEnum.RESOURCE.name());
1607 hasProps.put(GraphPropertyEnum.COMPONENT_TYPE, ComponentTypeEnum.SERVICE.name());
1612 switch (internalComponentType.toLowerCase()) {
1615 hasProps.put(GraphPropertyEnum.RESOURCE_TYPE, ResourceTypeEnum.CVFC.name());
1618 hasNotProps.put(GraphPropertyEnum.RESOURCE_TYPE, ResourceTypeEnum.CVFC.name());
1625 private void fillPropsMap(Map<GraphPropertyEnum, Object> hasProps, Map<GraphPropertyEnum, Object> hasNotProps, String internalComponentType, ComponentTypeEnum componentTypeEnum, boolean isAbstract, VertexTypeEnum internalVertexType) {
1626 hasNotProps.put(GraphPropertyEnum.STATE, LifecycleStateEnum.NOT_CERTIFIED_CHECKOUT.name());
1628 hasNotProps.put(GraphPropertyEnum.IS_DELETED, true);
1629 hasProps.put(GraphPropertyEnum.IS_HIGHEST_VERSION, true);
1630 if (VertexTypeEnum.NODE_TYPE == internalVertexType) {
1631 hasProps.put(GraphPropertyEnum.IS_ABSTRACT, isAbstract);
1632 if (internalComponentType != null) {
1633 fillNodeTypePropsMap(hasProps, hasNotProps, internalComponentType);
1636 fillTopologyTemplatePropsMap(hasProps, hasNotProps, componentTypeEnum, internalComponentType);
1640 private List<VertexTypeEnum> getInternalVertexTypes(ComponentTypeEnum componentTypeEnum, String internalComponentType) {
1641 List<VertexTypeEnum> internalVertexTypes = new ArrayList<>();
1642 if (ComponentTypeEnum.RESOURCE == componentTypeEnum) {
1643 internalVertexTypes.add(VertexTypeEnum.NODE_TYPE);
1645 if (ComponentTypeEnum.SERVICE == componentTypeEnum || "service".equalsIgnoreCase(internalComponentType) || "vf".equalsIgnoreCase(internalComponentType)) {
1646 internalVertexTypes.add(VertexTypeEnum.TOPOLOGY_TEMPLATE);
1648 return internalVertexTypes;
1651 public Either<List<Component>, StorageOperationStatus> getLatestVersionNotAbstractMetadataOnly(boolean isAbstract, Boolean isHighest, ComponentTypeEnum componentTypeEnum, String internalComponentType) {
1652 List<VertexTypeEnum> internalVertexTypes = getInternalVertexTypes(componentTypeEnum, internalComponentType);
1653 List<Component> result = new ArrayList<>();
1654 for (VertexTypeEnum vertexType : internalVertexTypes) {
1655 Either<List<Component>, StorageOperationStatus> listByVertexType = getLatestVersionNotAbstractToscaElementsMetadataOnly(isAbstract, isHighest, componentTypeEnum, internalComponentType, vertexType);
1656 if (listByVertexType.isRight()) {
1657 return listByVertexType;
1659 result.addAll(listByVertexType.left().value());
1661 return Either.left(result);
1665 private Either<List<Component>, StorageOperationStatus> getLatestComponentListByUuid(String componentUuid, Map<GraphPropertyEnum, Object> additionalPropertiesToMatch) {
1666 Map<GraphPropertyEnum, Object> propertiesToMatch = new EnumMap<>(GraphPropertyEnum.class);
1667 if (additionalPropertiesToMatch != null) {
1668 propertiesToMatch.putAll(additionalPropertiesToMatch);
1670 propertiesToMatch.put(GraphPropertyEnum.IS_HIGHEST_VERSION, true);
1671 Either<List<Component>, StorageOperationStatus> componentListByUuid = getComponentListByUuid(componentUuid, propertiesToMatch);
1672 return componentListByUuid;
1675 public Either<Component, StorageOperationStatus> getComponentByUuidAndVersion(String componentUuid, String version) {
1676 Map<GraphPropertyEnum, Object> propertiesToMatch = new EnumMap<>(GraphPropertyEnum.class);
1678 propertiesToMatch.put(GraphPropertyEnum.UUID, componentUuid);
1679 propertiesToMatch.put(GraphPropertyEnum.VERSION, version);
1681 Map<GraphPropertyEnum, Object> propertiesNotToMatch = new EnumMap<>(GraphPropertyEnum.class);
1682 propertiesNotToMatch.put(GraphPropertyEnum.IS_DELETED, true);
1683 Either<List<GraphVertex>, TitanOperationStatus> vertexEither = titanDao.getByCriteria(null, propertiesToMatch, propertiesNotToMatch, JsonParseFlagEnum.ParseAll);
1684 if (vertexEither.isRight()) {
1685 return Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(vertexEither.right().value()));
1688 List<GraphVertex> vertexList = vertexEither.isLeft() ? vertexEither.left().value() : null;
1689 if (vertexList == null || vertexList.isEmpty() || vertexList.size() > 1) {
1690 return Either.right(StorageOperationStatus.NOT_FOUND);
1693 return getToscaElementByOperation(vertexList.get(0));
1696 public Either<List<Component>, StorageOperationStatus> getComponentListByUuid(String componentUuid, Map<GraphPropertyEnum, Object> additionalPropertiesToMatch) {
1698 Map<GraphPropertyEnum, Object> propertiesToMatch = new EnumMap<>(GraphPropertyEnum.class);
1700 if (additionalPropertiesToMatch != null) {
1701 propertiesToMatch.putAll(additionalPropertiesToMatch);
1704 propertiesToMatch.put(GraphPropertyEnum.UUID, componentUuid);
1706 Map<GraphPropertyEnum, Object> propertiesNotToMatch = new EnumMap<>(GraphPropertyEnum.class);
1707 propertiesNotToMatch.put(GraphPropertyEnum.IS_DELETED, true);
1709 Either<List<GraphVertex>, TitanOperationStatus> vertexEither = titanDao.getByCriteria(null, propertiesToMatch, propertiesNotToMatch, JsonParseFlagEnum.ParseAll);
1711 if (vertexEither.isRight()) {
1712 log.debug("Couldn't fetch metadata for component with type {} and uuid {}, error: {}", componentUuid, vertexEither.right().value());
1713 return Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(vertexEither.right().value()));
1715 List<GraphVertex> vertexList = vertexEither.isLeft() ? vertexEither.left().value() : null;
1717 if (vertexList == null || vertexList.isEmpty()) {
1718 log.debug("Component with uuid {} was not found", componentUuid);
1719 return Either.right(StorageOperationStatus.NOT_FOUND);
1722 ArrayList<Component> latestComponents = new ArrayList<>();
1723 for (GraphVertex vertex : vertexList) {
1724 Either<Component, StorageOperationStatus> toscaElementByOperation = getToscaElementByOperation(vertex);
1726 if (toscaElementByOperation.isRight()) {
1727 log.debug("Could not fetch the following Component by UUID {}", vertex.getUniqueId());
1728 return Either.right(toscaElementByOperation.right().value());
1731 latestComponents.add(toscaElementByOperation.left().value());
1734 if (latestComponents.size() > 1) {
1735 for (Component component : latestComponents) {
1736 if (component.isHighestVersion()) {
1737 LinkedList<Component> highestComponent = new LinkedList<>();
1738 highestComponent.add(component);
1739 return Either.left(highestComponent);
1744 return Either.left(latestComponents);
1747 public Either<Component, StorageOperationStatus> getLatestServiceByUuid(String serviceUuid) {
1748 Map<GraphPropertyEnum, Object> propertiesToMatch = new HashMap<>();
1749 propertiesToMatch.put(GraphPropertyEnum.COMPONENT_TYPE, ComponentTypeEnum.SERVICE.name());
1750 return getLatestComponentByUuid(serviceUuid, propertiesToMatch);
1753 public Either<Component, StorageOperationStatus> getLatestComponentByUuid(String componentUuid) {
1754 return getLatestComponentByUuid(componentUuid, null);
1757 public Either<Component, StorageOperationStatus> getLatestComponentByUuid(String componentUuid, Map<GraphPropertyEnum, Object> propertiesToMatch) {
1759 Either<List<Component>, StorageOperationStatus> latestVersionListEither = getLatestComponentListByUuid(componentUuid, propertiesToMatch);
1761 if (latestVersionListEither.isRight()) {
1762 return Either.right(latestVersionListEither.right().value());
1765 List<Component> latestVersionList = latestVersionListEither.left().value();
1767 if (latestVersionList.isEmpty()) {
1768 return Either.right(StorageOperationStatus.NOT_FOUND);
1770 Component component = latestVersionList.size() == 1 ? latestVersionList.get(0) : latestVersionList.stream().max((c1, c2) -> Double.compare(Double.parseDouble(c1.getVersion()), Double.parseDouble(c2.getVersion()))).get();
1772 return Either.left(component);
1775 public Either<List<Resource>, StorageOperationStatus> getAllCertifiedResources(boolean isAbstract, Boolean isHighest) {
1777 List<Resource> resources = new ArrayList<>();
1778 Map<GraphPropertyEnum, Object> propertiesToMatch = new EnumMap<>(GraphPropertyEnum.class);
1779 Map<GraphPropertyEnum, Object> propertiesNotToMatch = new EnumMap<>(GraphPropertyEnum.class);
1781 propertiesToMatch.put(GraphPropertyEnum.IS_ABSTRACT, isAbstract);
1782 if (isHighest != null) {
1783 propertiesToMatch.put(GraphPropertyEnum.IS_HIGHEST_VERSION, isHighest.booleanValue());
1785 propertiesToMatch.put(GraphPropertyEnum.STATE, LifecycleStateEnum.CERTIFIED.name());
1786 propertiesToMatch.put(GraphPropertyEnum.COMPONENT_TYPE, ComponentTypeEnum.RESOURCE.name());
1787 propertiesNotToMatch.put(GraphPropertyEnum.IS_DELETED, true);
1789 Either<List<GraphVertex>, TitanOperationStatus> getResourcesRes = titanDao.getByCriteria(null, propertiesToMatch, propertiesNotToMatch, JsonParseFlagEnum.ParseAll);
1791 if (getResourcesRes.isRight()) {
1792 log.debug("Failed to fetch all certified resources. Status is {}", getResourcesRes.right().value());
1793 return Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(getResourcesRes.right().value()));
1795 List<GraphVertex> resourceVerticies = getResourcesRes.left().value();
1796 for (GraphVertex resourceV : resourceVerticies) {
1797 Either<Resource, StorageOperationStatus> getResourceRes = getToscaElement(resourceV);
1798 if (getResourceRes.isRight()) {
1799 return Either.right(getResourceRes.right().value());
1801 resources.add(getResourceRes.left().value());
1803 return Either.left(resources);
1806 public <T extends Component> Either<T, StorageOperationStatus> getLatestByNameAndVersion(String name, String version, JsonParseFlagEnum parseFlag) {
1807 Either<T, StorageOperationStatus> result;
1809 Map<GraphPropertyEnum, Object> hasProperties = new EnumMap<>(GraphPropertyEnum.class);
1810 Map<GraphPropertyEnum, Object> hasNotProperties = new EnumMap<>(GraphPropertyEnum.class);
1812 hasProperties.put(GraphPropertyEnum.NAME, name);
1813 hasProperties.put(GraphPropertyEnum.VERSION, version);
1814 hasProperties.put(GraphPropertyEnum.IS_HIGHEST_VERSION, true);
1816 hasNotProperties.put(GraphPropertyEnum.IS_DELETED, true);
1818 Either<List<GraphVertex>, TitanOperationStatus> getResourceRes = titanDao.getByCriteria(null, hasProperties, hasNotProperties, parseFlag);
1819 if (getResourceRes.isRight()) {
1820 TitanOperationStatus status = getResourceRes.right().value();
1821 log.debug("failed to find resource with name {}, version {}. Status is {} ", name, version, status);
1822 result = Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(status));
1825 return getToscaElementByOperation(getResourceRes.left().value().get(0));
1828 public Either<Resource, StorageOperationStatus> getLatestComponentByCsarOrName(ComponentTypeEnum componentType, String csarUUID, String systemName) {
1829 return getLatestComponentByCsarOrName(componentType, csarUUID, systemName, false, JsonParseFlagEnum.ParseAll);
1832 public Either<Resource, StorageOperationStatus> getLatestComponentByCsarOrName(ComponentTypeEnum componentType, String csarUUID, String systemName, boolean allowDeleted, JsonParseFlagEnum parseFlag) {
1833 Map<GraphPropertyEnum, Object> props = new EnumMap<>(GraphPropertyEnum.class);
1834 props.put(GraphPropertyEnum.CSAR_UUID, csarUUID);
1835 props.put(GraphPropertyEnum.IS_HIGHEST_VERSION, true);
1836 if (componentType != null) {
1837 props.put(GraphPropertyEnum.COMPONENT_TYPE, componentType.name());
1839 Map<GraphPropertyEnum, Object> propsHasNot = new EnumMap<>(GraphPropertyEnum.class);
1840 propsHasNot.put(GraphPropertyEnum.IS_DELETED, true);
1842 GraphVertex resourceMetadataData = null;
1843 List<GraphVertex> resourceMetadataDataList = null;
1844 Either<List<GraphVertex>, TitanOperationStatus> byCsar = titanDao.getByCriteria(null, props, propsHasNot, JsonParseFlagEnum.ParseMetadata);
1845 if (byCsar.isRight()) {
1846 if (TitanOperationStatus.NOT_FOUND == byCsar.right().value()) {
1847 // Fix Defect DE256036
1848 if (StringUtils.isEmpty(systemName)) {
1849 return Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(TitanOperationStatus.NOT_FOUND));
1853 props.put(GraphPropertyEnum.IS_HIGHEST_VERSION, true);
1854 props.put(GraphPropertyEnum.SYSTEM_NAME, systemName);
1855 Either<List<GraphVertex>, TitanOperationStatus> bySystemname = titanDao.getByCriteria(null, props, JsonParseFlagEnum.ParseMetadata);
1856 if (bySystemname.isRight()) {
1857 log.debug("getLatestResourceByCsarOrName - Failed to find by system name {} error {} ", systemName, bySystemname.right().value());
1858 return Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(bySystemname.right().value()));
1860 if (bySystemname.left().value().size() > 2) {
1861 log.debug("getLatestResourceByCsarOrName - getByCriteria(by system name) must return only 2 latest version, but was returned - {}", bySystemname.left().value().size());
1862 return Either.right(StorageOperationStatus.GENERAL_ERROR);
1864 resourceMetadataDataList = bySystemname.left().value();
1865 if (resourceMetadataDataList.size() == 1) {
1866 resourceMetadataData = resourceMetadataDataList.get(0);
1868 for (GraphVertex curResource : resourceMetadataDataList) {
1869 if (!((String) curResource.getJsonMetadataField(JsonPresentationFields.LIFECYCLE_STATE)).equals("CERTIFIED")) {
1870 resourceMetadataData = curResource;
1875 if (resourceMetadataData == null) {
1876 log.debug("getLatestResourceByCsarOrName - getByCriteria(by system name) returned 2 latest CERTIFIED versions");
1877 return Either.right(StorageOperationStatus.GENERAL_ERROR);
1879 if (resourceMetadataData.getJsonMetadataField(JsonPresentationFields.CSAR_UUID) != null && !((String) resourceMetadataData.getJsonMetadataField(JsonPresentationFields.CSAR_UUID)).equals(csarUUID)) {
1880 log.debug("getLatestResourceByCsarOrName - same system name {} but different csarUUID. exist {} and new {} ", systemName, resourceMetadataData.getJsonMetadataField(JsonPresentationFields.CSAR_UUID), csarUUID);
1881 // correct error will be returned from create flow. with all
1882 // correct audit records!!!!!
1883 return Either.right(StorageOperationStatus.NOT_FOUND);
1885 Either<Resource, StorageOperationStatus> resource = getToscaElement((String) resourceMetadataData.getUniqueId());
1889 resourceMetadataDataList = byCsar.left().value();
1890 if (resourceMetadataDataList.size() > 2) {
1891 log.debug("getLatestResourceByCsarOrName - getByCriteria(by csar) must return only 2 latest version, but was returned - {}", byCsar.left().value().size());
1892 return Either.right(StorageOperationStatus.GENERAL_ERROR);
1894 if (resourceMetadataDataList.size() == 1) {
1895 resourceMetadataData = resourceMetadataDataList.get(0);
1897 for (GraphVertex curResource : resourceMetadataDataList) {
1898 if (!((String) curResource.getJsonMetadataField(JsonPresentationFields.LIFECYCLE_STATE)).equals("CERTIFIED")) {
1899 resourceMetadataData = curResource;
1904 if (resourceMetadataData == null) {
1905 log.debug("getLatestResourceByCsarOrName - getByCriteria(by csar) returned 2 latest CERTIFIED versions");
1906 return Either.right(StorageOperationStatus.GENERAL_ERROR);
1908 Either<Resource, StorageOperationStatus> resource = getToscaElement((String) resourceMetadataData.getJsonMetadataField(JsonPresentationFields.UNIQUE_ID), parseFlag);
1914 public Either<Boolean, StorageOperationStatus> validateToscaResourceNameExtends(String templateNameCurrent, String templateNameExtends) {
1916 String currentTemplateNameChecked = templateNameExtends;
1918 while (currentTemplateNameChecked != null && !currentTemplateNameChecked.equalsIgnoreCase(templateNameCurrent)) {
1919 Either<Resource, StorageOperationStatus> latestByToscaResourceName = getLatestByToscaResourceName(currentTemplateNameChecked);
1921 if (latestByToscaResourceName.isRight()) {
1922 return latestByToscaResourceName.right().value() == StorageOperationStatus.NOT_FOUND ? Either.left(false) : Either.right(latestByToscaResourceName.right().value());
1925 Resource value = latestByToscaResourceName.left().value();
1927 if (value.getDerivedFrom() != null) {
1928 currentTemplateNameChecked = value.getDerivedFrom().get(0);
1930 currentTemplateNameChecked = null;
1934 return (currentTemplateNameChecked != null && currentTemplateNameChecked.equalsIgnoreCase(templateNameCurrent)) ? Either.left(true) : Either.left(false);
1937 public Either<List<Component>, StorageOperationStatus> fetchMetaDataByResourceType(String resourceType, ComponentParametersView filterBy) {
1938 Map<GraphPropertyEnum, Object> props = new EnumMap<>(GraphPropertyEnum.class);
1939 props.put(GraphPropertyEnum.RESOURCE_TYPE, resourceType);
1940 props.put(GraphPropertyEnum.IS_HIGHEST_VERSION, true);
1941 Map<GraphPropertyEnum, Object> propsHasNotToMatch = new HashMap<>();
1942 propsHasNotToMatch.put(GraphPropertyEnum.IS_DELETED, true);
1943 Either<List<GraphVertex>, TitanOperationStatus> resourcesByTypeEither = titanDao.getByCriteria(null, props, propsHasNotToMatch, JsonParseFlagEnum.ParseMetadata);
1945 if (resourcesByTypeEither.isRight()) {
1946 return Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(resourcesByTypeEither.right().value()));
1949 List<GraphVertex> vertexList = resourcesByTypeEither.left().value();
1950 List<Component> components = new ArrayList<>();
1952 for (GraphVertex vertex : vertexList) {
1953 components.add(getToscaElementByOperation(vertex, filterBy).left().value());
1956 return Either.left(components);
1959 public void commit() {
1963 public Either<Service, StorageOperationStatus> updateDistributionStatus(Service service, User user, DistributionStatusEnum distributionStatus) {
1964 Either<GraphVertex, StorageOperationStatus> updateDistributionStatus = topologyTemplateOperation.updateDistributionStatus(service.getUniqueId(), user, distributionStatus);
1965 if (updateDistributionStatus.isRight()) {
1966 return Either.right(updateDistributionStatus.right().value());
1968 GraphVertex serviceV = updateDistributionStatus.left().value();
1969 service.setDistributionStatus(distributionStatus);
1970 service.setLastUpdateDate((Long) serviceV.getJsonMetadataField(JsonPresentationFields.LAST_UPDATE_DATE));
1971 return Either.left(service);
1974 public Either<ComponentMetadataData, StorageOperationStatus> updateComponentLastUpdateDateOnGraph(Component component, Long modificationTime) {
1976 Either<ComponentMetadataData, StorageOperationStatus> result = null;
1977 GraphVertex serviceVertex;
1978 Either<GraphVertex, TitanOperationStatus> updateRes = null;
1979 Either<GraphVertex, TitanOperationStatus> getRes = titanDao.getVertexById(component.getUniqueId(), JsonParseFlagEnum.ParseMetadata);
1980 if (getRes.isRight()) {
1981 TitanOperationStatus status = getRes.right().value();
1982 log.error("Failed to fetch component {}. status is {}", component.getUniqueId(), status);
1983 result = Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(status));
1985 if (result == null) {
1986 serviceVertex = getRes.left().value();
1987 long lastUpdateDate = System.currentTimeMillis();
1988 serviceVertex.setJsonMetadataField(JsonPresentationFields.LAST_UPDATE_DATE, lastUpdateDate);
1989 component.setLastUpdateDate(lastUpdateDate);
1990 updateRes = titanDao.updateVertex(serviceVertex);
1991 if (updateRes.isRight()) {
1992 result = Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(updateRes.right().value()));
1995 if (result == null) {
1996 result = Either.left(ModelConverter.convertToComponentMetadata(updateRes.left().value()));
2001 public TitanDao getTitanDao() {
2005 public Either<List<Service>, StorageOperationStatus> getCertifiedServicesWithDistStatus(Set<DistributionStatusEnum> distStatus) {
2006 Map<GraphPropertyEnum, Object> propertiesToMatch = new EnumMap<>(GraphPropertyEnum.class);
2007 propertiesToMatch.put(GraphPropertyEnum.STATE, LifecycleStateEnum.CERTIFIED.name());
2009 return getServicesWithDistStatus(distStatus, propertiesToMatch);
2012 public Either<List<Service>, StorageOperationStatus> getServicesWithDistStatus(Set<DistributionStatusEnum> distStatus, Map<GraphPropertyEnum, Object> additionalPropertiesToMatch) {
2014 List<Service> servicesAll = new ArrayList<>();
2016 Map<GraphPropertyEnum, Object> propertiesToMatch = new EnumMap<>(GraphPropertyEnum.class);
2017 Map<GraphPropertyEnum, Object> propertiesNotToMatch = new EnumMap<>(GraphPropertyEnum.class);
2019 if (additionalPropertiesToMatch != null && !additionalPropertiesToMatch.isEmpty()) {
2020 propertiesToMatch.putAll(additionalPropertiesToMatch);
2023 propertiesToMatch.put(GraphPropertyEnum.COMPONENT_TYPE, ComponentTypeEnum.SERVICE.name());
2025 propertiesNotToMatch.put(GraphPropertyEnum.IS_DELETED, true);
2027 if (distStatus != null && !distStatus.isEmpty()) {
2028 for (DistributionStatusEnum state : distStatus) {
2029 propertiesToMatch.put(GraphPropertyEnum.DISTRIBUTION_STATUS, state.name());
2030 Either<List<Service>, StorageOperationStatus> fetchServicesByCriteria = fetchServicesByCriteria(servicesAll, propertiesToMatch, propertiesNotToMatch);
2031 if (fetchServicesByCriteria.isRight()) {
2032 return fetchServicesByCriteria;
2034 servicesAll = fetchServicesByCriteria.left().value();
2037 return Either.left(servicesAll);
2039 return fetchServicesByCriteria(servicesAll, propertiesToMatch, propertiesNotToMatch);
2043 private Either<List<Service>, StorageOperationStatus> fetchServicesByCriteria(List<Service> servicesAll, Map<GraphPropertyEnum, Object> propertiesToMatch, Map<GraphPropertyEnum, Object> propertiesNotToMatch) {
2044 Either<List<GraphVertex>, TitanOperationStatus> getRes = titanDao.getByCriteria(VertexTypeEnum.TOPOLOGY_TEMPLATE, propertiesToMatch, propertiesNotToMatch, JsonParseFlagEnum.ParseAll);
2045 if (getRes.isRight()) {
2046 if (getRes.right().value() != TitanOperationStatus.NOT_FOUND) {
2047 CommonUtility.addRecordToLog(log, LogLevelEnum.DEBUG, "Failed to fetch certified services by match properties {} not match properties {} . Status is {}. ", propertiesToMatch, propertiesNotToMatch, getRes.right().value());
2048 return Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(getRes.right().value()));
2051 for (GraphVertex vertex : getRes.left().value()) {
2052 // Either<Component, StorageOperationStatus> getServiceRes = getToscaElementByOperation(vertex);
2053 Either<ToscaElement, StorageOperationStatus> getServiceRes = topologyTemplateOperation.getLightComponent(vertex, ComponentTypeEnum.SERVICE, new ComponentParametersView(true));
2055 if (getServiceRes.isRight()) {
2056 CommonUtility.addRecordToLog(log, LogLevelEnum.DEBUG, "Failed to fetch certified service {}. Status is {}. ", vertex.getJsonMetadataField(JsonPresentationFields.NAME), getServiceRes.right().value());
2057 return Either.right(getServiceRes.right().value());
2059 servicesAll.add(ModelConverter.convertFromToscaElement(getServiceRes.left().value()));
2063 return Either.left(servicesAll);
2066 public void rollback() {
2067 titanDao.rollback();
2070 public StorageOperationStatus addDeploymentArtifactsToInstance(String componentId, ComponentInstance componentInstance, Map<String, ArtifactDefinition> finalDeploymentArtifacts) {
2071 Map<String, ArtifactDataDefinition> instDeplArtifacts = finalDeploymentArtifacts.entrySet().stream().collect(Collectors.toMap(Map.Entry::getKey, e -> new ArtifactDataDefinition(e.getValue())));
2073 return nodeTemplateOperation.addDeploymentArtifactsToInstance(componentId, componentInstance.getUniqueId(), instDeplArtifacts);
2076 public StorageOperationStatus addInformationalArtifactsToInstance(String componentId, ComponentInstance componentInstance, Map<String, ArtifactDefinition> artifacts) {
2077 StorageOperationStatus status = StorageOperationStatus.OK;
2078 if (MapUtils.isNotEmpty(artifacts)) {
2079 Map<String, ArtifactDataDefinition> instDeplArtifacts = artifacts.entrySet().stream().collect(Collectors.toMap(Map.Entry::getKey, e -> new ArtifactDataDefinition(e.getValue())));
2080 status = nodeTemplateOperation.addInformationalArtifactsToInstance(componentId, componentInstance.getUniqueId(), instDeplArtifacts);
2085 public StorageOperationStatus generateCustomizationUUIDOnInstance(String componentId, String instanceId) {
2086 return nodeTemplateOperation.generateCustomizationUUIDOnInstance(componentId, instanceId);
2089 public StorageOperationStatus generateCustomizationUUIDOnInstanceGroup(String componentId, String instanceId, List<String> groupInstances) {
2090 return nodeTemplateOperation.generateCustomizationUUIDOnInstanceGroup(componentId, instanceId, groupInstances);
2094 * adds property to a resource
2095 * @warn this method has SIDE EFFECT on ownerId ,use it with caution
2097 public Either<PropertyDefinition, StorageOperationStatus> addPropertyToResource(String propertyName, PropertyDefinition newPropertyDefinition, Resource resource) {
2099 Either<PropertyDefinition, StorageOperationStatus> result = null;
2100 Either<Component, StorageOperationStatus> getUpdatedComponentRes = null;
2101 newPropertyDefinition.setName(propertyName);
2102 StorageOperationStatus status = getToscaElementOperation(resource).addToscaDataToToscaElement(resource.getUniqueId(), EdgeLabelEnum.PROPERTIES, VertexTypeEnum.PROPERTIES, newPropertyDefinition, JsonPresentationFields.NAME);
2103 if (status != StorageOperationStatus.OK) {
2104 CommonUtility.addRecordToLog(log, LogLevelEnum.DEBUG, "Failed to add the property {} to the resource {}. Status is {}. ", propertyName, resource.getName(), status);
2105 result = Either.right(status);
2107 if (result == null) {
2108 ComponentParametersView filter = new ComponentParametersView(true);
2109 filter.setIgnoreProperties(false);
2110 getUpdatedComponentRes = getToscaElement(resource.getUniqueId(), filter);
2111 if (getUpdatedComponentRes.isRight()) {
2112 CommonUtility.addRecordToLog(log, LogLevelEnum.DEBUG, "Failed to get updated resource {}. Status is {}. ", resource.getUniqueId(), getUpdatedComponentRes.right().value());
2113 result = Either.right(status);
2116 if (result == null) {
2117 PropertyDefinition newProperty = null;
2118 List<PropertyDefinition> properties = ((Resource) getUpdatedComponentRes.left().value()).getProperties();
2119 if (CollectionUtils.isNotEmpty(properties)) {
2120 Optional<PropertyDefinition> newPropertyOptional = properties.stream().filter(p -> p.getName().equals(propertyName)).findAny();
2121 if (newPropertyOptional.isPresent()) {
2122 newProperty = newPropertyOptional.get();
2125 if (newProperty == null) {
2126 CommonUtility.addRecordToLog(log, LogLevelEnum.DEBUG, "Failed to find recently added property {} on the resource {}. Status is {}. ", propertyName, resource.getUniqueId(), StorageOperationStatus.NOT_FOUND);
2127 result = Either.right(StorageOperationStatus.NOT_FOUND);
2129 result = Either.left(newProperty);
2135 public StorageOperationStatus deletePropertyOfResource(Resource resource, String propertyName) {
2136 return getToscaElementOperation(resource).deleteToscaDataElement(resource.getUniqueId(), EdgeLabelEnum.PROPERTIES, VertexTypeEnum.PROPERTIES, propertyName, JsonPresentationFields.NAME);
2139 public StorageOperationStatus deleteAttributeOfResource(Component component, String attributeName) {
2140 return getToscaElementOperation(component).deleteToscaDataElement(component.getUniqueId(), EdgeLabelEnum.ATTRIBUTES, VertexTypeEnum.ATTRIBUTES, attributeName, JsonPresentationFields.NAME);
2143 public StorageOperationStatus deleteInputOfResource(Component resource, String inputName) {
2144 return getToscaElementOperation(resource).deleteToscaDataElement(resource.getUniqueId(), EdgeLabelEnum.INPUTS, VertexTypeEnum.INPUTS, inputName, JsonPresentationFields.NAME);
2147 public Either<PropertyDefinition, StorageOperationStatus> updatePropertyOfResource(Resource resource, PropertyDefinition newPropertyDefinition) {
2149 Either<Component, StorageOperationStatus> getUpdatedComponentRes = null;
2150 Either<PropertyDefinition, StorageOperationStatus> result = null;
2151 StorageOperationStatus status = getToscaElementOperation(resource).updateToscaDataOfToscaElement(resource.getUniqueId(), EdgeLabelEnum.PROPERTIES, VertexTypeEnum.PROPERTIES, newPropertyDefinition, JsonPresentationFields.NAME);
2152 if (status != StorageOperationStatus.OK) {
2153 CommonUtility.addRecordToLog(log, LogLevelEnum.DEBUG, "Failed to add the property {} to the resource {}. Status is {}. ", newPropertyDefinition.getName(), resource.getName(), status);
2154 result = Either.right(status);
2156 if (result == null) {
2157 ComponentParametersView filter = new ComponentParametersView(true);
2158 filter.setIgnoreProperties(false);
2159 getUpdatedComponentRes = getToscaElement(resource.getUniqueId(), filter);
2160 if (getUpdatedComponentRes.isRight()) {
2161 CommonUtility.addRecordToLog(log, LogLevelEnum.DEBUG, "Failed to get updated resource {}. Status is {}. ", resource.getUniqueId(), getUpdatedComponentRes.right().value());
2162 result = Either.right(status);
2165 if (result == null) {
2166 Optional<PropertyDefinition> newProperty = ((Resource) getUpdatedComponentRes.left().value()).getProperties().stream().filter(p -> p.getName().equals(newPropertyDefinition.getName())).findAny();
2167 if (newProperty.isPresent()) {
2168 result = Either.left(newProperty.get());
2170 CommonUtility.addRecordToLog(log, LogLevelEnum.DEBUG, "Failed to find recently added property {} on the resource {}. Status is {}. ", newPropertyDefinition.getName(), resource.getUniqueId(), StorageOperationStatus.NOT_FOUND);
2171 result = Either.right(StorageOperationStatus.NOT_FOUND);
2177 public Either<PropertyDefinition, StorageOperationStatus> addAttributeOfResource(Component component, PropertyDefinition newAttributeDef) {
2179 Either<Component, StorageOperationStatus> getUpdatedComponentRes = null;
2180 Either<PropertyDefinition, StorageOperationStatus> result = null;
2181 if (newAttributeDef.getUniqueId() == null || newAttributeDef.getUniqueId().isEmpty()) {
2182 String attUniqueId = UniqueIdBuilder.buildAttributeUid(component.getUniqueId(), newAttributeDef.getName());
2183 newAttributeDef.setUniqueId(attUniqueId);
2186 StorageOperationStatus status = getToscaElementOperation(component).addToscaDataToToscaElement(component.getUniqueId(), EdgeLabelEnum.ATTRIBUTES, VertexTypeEnum.ATTRIBUTES, newAttributeDef, JsonPresentationFields.NAME);
2187 if (status != StorageOperationStatus.OK) {
2188 CommonUtility.addRecordToLog(log, LogLevelEnum.DEBUG, "Failed to add the property {} to the resource {}. Status is {}. ", newAttributeDef.getName(), component.getName(), status);
2189 result = Either.right(status);
2191 if (result == null) {
2192 ComponentParametersView filter = new ComponentParametersView(true);
2193 filter.setIgnoreAttributesFrom(false);
2194 getUpdatedComponentRes = getToscaElement(component.getUniqueId(), filter);
2195 if (getUpdatedComponentRes.isRight()) {
2196 CommonUtility.addRecordToLog(log, LogLevelEnum.DEBUG, "Failed to get updated resource {}. Status is {}. ", component.getUniqueId(), getUpdatedComponentRes.right().value());
2197 result = Either.right(status);
2200 if (result == null) {
2201 Optional<PropertyDefinition> newAttribute = ((Resource) getUpdatedComponentRes.left().value()).getAttributes().stream().filter(p -> p.getName().equals(newAttributeDef.getName())).findAny();
2202 if (newAttribute.isPresent()) {
2203 result = Either.left(newAttribute.get());
2205 CommonUtility.addRecordToLog(log, LogLevelEnum.DEBUG, "Failed to find recently added property {} on the resource {}. Status is {}. ", newAttributeDef.getName(), component.getUniqueId(), StorageOperationStatus.NOT_FOUND);
2206 result = Either.right(StorageOperationStatus.NOT_FOUND);
2212 public Either<PropertyDefinition, StorageOperationStatus> updateAttributeOfResource(Component component, PropertyDefinition newAttributeDef) {
2214 Either<Component, StorageOperationStatus> getUpdatedComponentRes = null;
2215 Either<PropertyDefinition, StorageOperationStatus> result = null;
2216 StorageOperationStatus status = getToscaElementOperation(component).updateToscaDataOfToscaElement(component.getUniqueId(), EdgeLabelEnum.ATTRIBUTES, VertexTypeEnum.ATTRIBUTES, newAttributeDef, JsonPresentationFields.NAME);
2217 if (status != StorageOperationStatus.OK) {
2218 CommonUtility.addRecordToLog(log, LogLevelEnum.DEBUG, "Failed to add the property {} to the resource {}. Status is {}. ", newAttributeDef.getName(), component.getName(), status);
2219 result = Either.right(status);
2221 if (result == null) {
2222 ComponentParametersView filter = new ComponentParametersView(true);
2223 filter.setIgnoreAttributesFrom(false);
2224 getUpdatedComponentRes = getToscaElement(component.getUniqueId(), filter);
2225 if (getUpdatedComponentRes.isRight()) {
2226 CommonUtility.addRecordToLog(log, LogLevelEnum.DEBUG, "Failed to get updated resource {}. Status is {}. ", component.getUniqueId(), getUpdatedComponentRes.right().value());
2227 result = Either.right(status);
2230 if (result == null) {
2231 Optional<PropertyDefinition> newProperty = ((Resource) getUpdatedComponentRes.left().value()).getAttributes().stream().filter(p -> p.getName().equals(newAttributeDef.getName())).findAny();
2232 if (newProperty.isPresent()) {
2233 result = Either.left(newProperty.get());
2235 CommonUtility.addRecordToLog(log, LogLevelEnum.DEBUG, "Failed to find recently added property {} on the resource {}. Status is {}. ", newAttributeDef.getName(), component.getUniqueId(), StorageOperationStatus.NOT_FOUND);
2236 result = Either.right(StorageOperationStatus.NOT_FOUND);
2242 public Either<InputDefinition, StorageOperationStatus> updateInputOfComponent(Component component, InputDefinition newInputDefinition) {
2244 Either<Component, StorageOperationStatus> getUpdatedComponentRes = null;
2245 Either<InputDefinition, StorageOperationStatus> result = null;
2246 StorageOperationStatus status = getToscaElementOperation(component).updateToscaDataOfToscaElement(component.getUniqueId(), EdgeLabelEnum.INPUTS, VertexTypeEnum.INPUTS, newInputDefinition, JsonPresentationFields.NAME);
2247 if (status != StorageOperationStatus.OK) {
2248 CommonUtility.addRecordToLog(log, LogLevelEnum.DEBUG, "Failed to update the input {} to the component {}. Status is {}. ", newInputDefinition.getName(), component.getName(), status);
2249 result = Either.right(status);
2251 if (result == null) {
2252 ComponentParametersView filter = new ComponentParametersView(true);
2253 filter.setIgnoreInputs(false);
2254 getUpdatedComponentRes = getToscaElement(component.getUniqueId(), filter);
2255 if (getUpdatedComponentRes.isRight()) {
2256 CommonUtility.addRecordToLog(log, LogLevelEnum.DEBUG, "Failed to get updated resource {}. Status is {}. ", component.getUniqueId(), getUpdatedComponentRes.right().value());
2257 result = Either.right(status);
2260 if (result == null) {
2261 Optional<InputDefinition> updatedInput = getUpdatedComponentRes.left().value().getInputs().stream().filter(p -> p.getName().equals(newInputDefinition.getName())).findAny();
2262 if (updatedInput.isPresent()) {
2263 result = Either.left(updatedInput.get());
2265 CommonUtility.addRecordToLog(log, LogLevelEnum.DEBUG, "Failed to find recently updated inputs {} on the resource {}. Status is {}. ", newInputDefinition.getName(), component.getUniqueId(), StorageOperationStatus.NOT_FOUND);
2266 result = Either.right(StorageOperationStatus.NOT_FOUND);
2273 * method - ename the group instances after referenced container name renamed flow - VF rename -(triggers)-> Group rename
2275 * @param containerComponent
2276 * - container such as service
2277 * @param componentInstance
2278 * - context component
2279 * @param componentInstanceId
2282 * @return - successfull/failed status
2284 public Either<StorageOperationStatus, StorageOperationStatus> cleanAndAddGroupInstancesToComponentInstance(Component containerComponent, ComponentInstance componentInstance, String componentInstanceId) {
2285 String uniqueId = componentInstance.getUniqueId();
2286 StorageOperationStatus status = nodeTemplateOperation.deleteToscaDataDeepElementsBlockToToscaElement(containerComponent.getUniqueId(), EdgeLabelEnum.INST_GROUPS, VertexTypeEnum.INST_GROUPS, uniqueId);
2287 if (status != StorageOperationStatus.OK && status != StorageOperationStatus.NOT_FOUND) {
2288 CommonUtility.addRecordToLog(log, LogLevelEnum.DEBUG, "Failed to delete group instances for container {}. error {] ", componentInstanceId, status);
2289 return Either.right(status);
2291 if (componentInstance.getGroupInstances() != null) {
2292 status = addGroupInstancesToComponentInstance(containerComponent, componentInstance, componentInstance.getGroupInstances());
2293 if (status != StorageOperationStatus.OK && status != StorageOperationStatus.NOT_FOUND) {
2294 CommonUtility.addRecordToLog(log, LogLevelEnum.DEBUG, "Failed to add group instances for container {}. error {] ", componentInstanceId, status);
2295 return Either.right(status);
2298 return Either.left(status);
2301 public StorageOperationStatus addGroupInstancesToComponentInstance(Component containerComponent, ComponentInstance componentInstance, List<GroupDefinition> groups, Map<String, List<ArtifactDefinition>> groupInstancesArtifacts) {
2302 return nodeTemplateOperation.addGroupInstancesToComponentInstance(containerComponent, componentInstance, groups, groupInstancesArtifacts);
2305 public Either<List<GroupDefinition>, StorageOperationStatus> updateGroupsOnComponent(Component component, List<GroupDataDefinition> updatedGroups) {
2306 return groupsOperation.updateGroups(component, updatedGroups);
2309 public Either<List<GroupInstance>, StorageOperationStatus> updateGroupInstancesOnComponent(Component component, ComponentTypeEnum componentType, String instanceId, List<GroupInstance> updatedGroupInstances) {
2310 return groupsOperation.updateGroupInstances(component, instanceId, updatedGroupInstances);
2313 public StorageOperationStatus addGroupInstancesToComponentInstance(Component containerComponent, ComponentInstance componentInstance, List<GroupInstance> groupInstances) {
2314 return nodeTemplateOperation.addGroupInstancesToComponentInstance(containerComponent, componentInstance, groupInstances);
2317 public StorageOperationStatus addDeploymentArtifactsToComponentInstance(Component containerComponent, ComponentInstance componentInstance, Map<String, ArtifactDefinition> deploymentArtifacts) {
2318 return nodeTemplateOperation.addDeploymentArtifactsToComponentInstance(containerComponent, componentInstance, deploymentArtifacts);
2321 public StorageOperationStatus updateComponentInstanceProperty(Component containerComponent, String componentInstanceId, ComponentInstanceProperty property) {
2322 return nodeTemplateOperation.updateComponentInstanceProperty(containerComponent, componentInstanceId, property);
2325 public StorageOperationStatus updateComponentInstanceProperties(Component containerComponent, String componentInstanceId, List<ComponentInstanceProperty> properties) {
2326 return nodeTemplateOperation.updateComponentInstanceProperties(containerComponent, componentInstanceId, properties);
2330 public StorageOperationStatus addComponentInstanceProperty(Component containerComponent, String componentInstanceId, ComponentInstanceProperty property) {
2331 return nodeTemplateOperation.addComponentInstanceProperty(containerComponent, componentInstanceId, property);
2334 public StorageOperationStatus updateComponentInstanceInput(Component containerComponent, String componentInstanceId, ComponentInstanceInput property) {
2335 return nodeTemplateOperation.updateComponentInstanceInput(containerComponent, componentInstanceId, property);
2338 public StorageOperationStatus updateComponentInstanceInputs(Component containerComponent, String componentInstanceId, List<ComponentInstanceInput> instanceInputs) {
2339 return nodeTemplateOperation.updateComponentInstanceInputs(containerComponent, componentInstanceId, instanceInputs);
2342 public StorageOperationStatus addComponentInstanceInput(Component containerComponent, String componentInstanceId, ComponentInstanceInput property) {
2343 return nodeTemplateOperation.addComponentInstanceInput(containerComponent, componentInstanceId, property);
2346 public void setNodeTypeOperation(NodeTypeOperation nodeTypeOperation) {
2347 this.nodeTypeOperation = nodeTypeOperation;
2350 public void setTopologyTemplateOperation(TopologyTemplateOperation topologyTemplateOperation) {
2351 this.topologyTemplateOperation = topologyTemplateOperation;
2354 public StorageOperationStatus deleteComponentInstanceInputsFromTopologyTemplate(Component containerComponent, ComponentTypeEnum componentType, List<InputDefinition> inputsToDelete) {
2355 return topologyTemplateOperation.deleteToscaDataElements(containerComponent.getUniqueId(), EdgeLabelEnum.INPUTS, inputsToDelete.stream().map(i -> i.getName()).collect(Collectors.toList()));
2358 public StorageOperationStatus updateComponentInstanceCapabiltyProperty(Component containerComponent, String componentInstanceUniqueId, String capabilityUniqueId, ComponentInstanceProperty property) {
2359 return nodeTemplateOperation.updateComponentInstanceCapabilityProperty(containerComponent, componentInstanceUniqueId, capabilityUniqueId, property);
2362 public StorageOperationStatus updateComponentInstanceCapabilityProperties(Component containerComponent, String componentInstanceUniqueId) {
2363 return convertComponentInstanceProperties(containerComponent, componentInstanceUniqueId)
2364 .map(instanceCapProps -> topologyTemplateOperation.updateComponentInstanceCapabilityProperties(containerComponent, componentInstanceUniqueId, instanceCapProps))
2365 .orElse(StorageOperationStatus.NOT_FOUND);
2368 public StorageOperationStatus updateComponentCalculatedCapabilitiesProperties(Component containerComponent) {
2369 Map<String, MapCapabiltyProperty> mapCapabiltyPropertyMap = convertComponentCapabilitiesProperties(containerComponent);
2370 return nodeTemplateOperation.overrideComponentCapabilitiesProperties(containerComponent, mapCapabiltyPropertyMap);
2373 public StorageOperationStatus deleteAllCalculatedCapabilitiesRequirements(String topologyTemplateId) {
2374 StorageOperationStatus status = topologyTemplateOperation.removeToscaData(topologyTemplateId, EdgeLabelEnum.CALCULATED_CAPABILITIES, VertexTypeEnum.CALCULATED_CAPABILITIES);
2375 if (status == StorageOperationStatus.OK) {
2376 status = topologyTemplateOperation.removeToscaData(topologyTemplateId, EdgeLabelEnum.CALCULATED_REQUIREMENTS, VertexTypeEnum.CALCULATED_REQUIREMENTS);
2378 if(status == StorageOperationStatus.OK){
2379 status = topologyTemplateOperation.removeToscaData(topologyTemplateId, EdgeLabelEnum.CALCULATED_CAP_PROPERTIES, VertexTypeEnum.CALCULATED_CAP_PROPERTIES);
2384 public Either<Component, StorageOperationStatus> shouldUpgradeToLatestDerived(Resource clonedResource) {
2385 String componentId = clonedResource.getUniqueId();
2386 Either<GraphVertex, TitanOperationStatus> getVertexEither = titanDao.getVertexById(componentId, JsonParseFlagEnum.NoParse);
2387 if (getVertexEither.isRight()) {
2388 log.debug("Couldn't fetch component with and unique id {}, error: {}", componentId, getVertexEither.right().value());
2389 return Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(getVertexEither.right().value()));
2392 GraphVertex nodeTypeV = getVertexEither.left().value();
2394 ToscaElement toscaElementToUpdate = ModelConverter.convertToToscaElement(clonedResource);
2396 Either<ToscaElement, StorageOperationStatus> shouldUpdateDerivedVersion = nodeTypeOperation.shouldUpdateDerivedVersion(toscaElementToUpdate, nodeTypeV);
2397 if ( shouldUpdateDerivedVersion.isRight() && StorageOperationStatus.OK != shouldUpdateDerivedVersion.right().value() ){
2398 log.debug("Failed to update derived version for node type {} derived {}, error: {}", componentId, clonedResource.getDerivedFrom().get(0), shouldUpdateDerivedVersion.right().value());
2399 return Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(getVertexEither.right().value()));
2401 if ( shouldUpdateDerivedVersion.isLeft() ){
2402 return Either.left(ModelConverter.convertFromToscaElement(shouldUpdateDerivedVersion.left().value()));
2404 return Either.left(clonedResource);
2407 * Returns list of ComponentInstanceProperty belonging to component instance capability specified by name, type and ownerId
2408 * @param componentId
2410 * @param capabilityName
2411 * @param capabilityType
2415 public Either<List<ComponentInstanceProperty>, StorageOperationStatus> getComponentInstanceCapabilityProperties(String componentId, String instanceId, String capabilityName, String capabilityType, String ownerId) {
2416 return topologyTemplateOperation.getComponentInstanceCapabilityProperties(componentId, instanceId, capabilityName, capabilityType, ownerId);
2419 private Map<String, MapCapabiltyProperty> convertComponentCapabilitiesProperties(Component currComponent) {
2420 return currComponent.getComponentInstances()
2422 .collect(Collectors.toMap(ComponentInstanceDataDefinition::getUniqueId,
2423 ci -> ModelConverter.convertToMapOfMapCapabiltyProperties(ci.getCapabilities(), ci.getUniqueId(), true)));
2426 private Optional<MapCapabiltyProperty> convertComponentInstanceProperties(Component component, String instanceId) {
2427 return component.fetchInstanceById(instanceId)
2428 .map(ci -> ModelConverter.convertToMapOfMapCapabiltyProperties(ci.getCapabilities(),instanceId));
2431 public Either<PolicyDefinition, StorageOperationStatus> associatePolicyToComponent(String componentId, PolicyDefinition policyDefinition, int counter) {
2432 Either<PolicyDefinition, StorageOperationStatus> result = null;
2433 Either<GraphVertex, TitanOperationStatus> getVertexEither;
2434 getVertexEither = titanDao.getVertexById(componentId, JsonParseFlagEnum.ParseMetadata);
2435 if (getVertexEither.isRight()) {
2436 log.error("Couldn't fetch a component with and UniqueId {}, error: {}", componentId, getVertexEither.right().value());
2437 result = Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(getVertexEither.right().value()));
2439 if(getVertexEither.left().value().getLabel() != VertexTypeEnum.TOPOLOGY_TEMPLATE){
2440 log.error("Policy association to component of Tosca type {} is not allowed. ", getVertexEither.left().value().getLabel());
2441 result = Either.right(StorageOperationStatus.BAD_REQUEST);
2445 StorageOperationStatus status = topologyTemplateOperation.addPolicyToToscaElement(getVertexEither.left().value(), policyDefinition, counter);
2446 if(status != StorageOperationStatus.OK){
2447 return Either.right(status);
2451 result = Either.left(policyDefinition);
2456 public Either<PolicyDefinition, StorageOperationStatus> updatePolicyOfComponent(String componentId, PolicyDefinition policyDefinition) {
2457 Either<PolicyDefinition, StorageOperationStatus> result = null;
2458 Either<GraphVertex, TitanOperationStatus> getVertexEither;
2459 getVertexEither = titanDao.getVertexById(componentId, JsonParseFlagEnum.NoParse);
2460 if (getVertexEither.isRight()) {
2461 log.error("Couldn't fetch a component with and UniqueId {}, error: {}", componentId, getVertexEither.right().value());
2462 result = Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(getVertexEither.right().value()));
2465 StorageOperationStatus status = topologyTemplateOperation.updatePolicyOfToscaElement(getVertexEither.left().value(), policyDefinition);
2466 if(status != StorageOperationStatus.OK){
2467 return Either.right(status);
2471 result = Either.left(policyDefinition);
2476 public StorageOperationStatus updatePoliciesOfComponent(String componentId, List<PolicyDefinition> policyDefinition) {
2477 log.debug("#updatePoliciesOfComponent - updating policies for component {}", componentId);
2478 return titanDao.getVertexById(componentId, JsonParseFlagEnum.NoParse)
2480 .map(DaoStatusConverter::convertTitanStatusToStorageStatus)
2481 .either(containerVertex -> topologyTemplateOperation.updatePoliciesOfToscaElement(containerVertex, policyDefinition),
2485 public StorageOperationStatus removePolicyFromComponent(String componentId, String policyId) {
2486 StorageOperationStatus status = null;
2487 Either<GraphVertex, TitanOperationStatus> getVertexEither = titanDao.getVertexById(componentId, JsonParseFlagEnum.NoParse);
2488 if (getVertexEither.isRight()) {
2489 log.error("Couldn't fetch a component with and UniqueId {}, error: {}", componentId, getVertexEither.right().value());
2490 status = DaoStatusConverter.convertTitanStatusToStorageStatus(getVertexEither.right().value());
2493 status = topologyTemplateOperation.removePolicyFromToscaElement(getVertexEither.left().value(), policyId);