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 fj.data.Either;
24 import org.apache.commons.collections.CollectionUtils;
25 import org.apache.commons.collections.MapUtils;
26 import org.apache.commons.lang3.StringUtils;
27 import org.apache.commons.lang3.tuple.ImmutablePair;
28 import org.apache.tinkerpop.gremlin.structure.Edge;
29 import org.openecomp.sdc.be.dao.jsongraph.GraphVertex;
30 import org.openecomp.sdc.be.dao.jsongraph.TitanDao;
31 import org.openecomp.sdc.be.dao.jsongraph.types.EdgeLabelEnum;
32 import org.openecomp.sdc.be.dao.jsongraph.types.JsonParseFlagEnum;
33 import org.openecomp.sdc.be.dao.jsongraph.types.VertexTypeEnum;
34 import org.openecomp.sdc.be.dao.titan.TitanOperationStatus;
35 import org.openecomp.sdc.be.datatypes.elements.*;
36 import org.openecomp.sdc.be.datatypes.enums.*;
37 import org.openecomp.sdc.be.model.*;
38 import org.openecomp.sdc.be.datatypes.elements.MapCapabilityProperty;
39 import org.openecomp.sdc.be.datatypes.elements.MapListCapabilityDataDefinition;
40 import org.openecomp.sdc.be.model.catalog.CatalogComponent;
41 import org.openecomp.sdc.be.model.jsontitan.datamodel.TopologyTemplate;
42 import org.openecomp.sdc.be.model.jsontitan.datamodel.ToscaElement;
43 import org.openecomp.sdc.be.model.jsontitan.utils.ModelConverter;
44 import org.openecomp.sdc.be.model.operations.StorageException;
45 import org.openecomp.sdc.be.model.operations.api.StorageOperationStatus;
46 import org.openecomp.sdc.be.model.operations.impl.DaoStatusConverter;
47 import org.openecomp.sdc.be.model.operations.impl.UniqueIdBuilder;
48 import org.openecomp.sdc.be.resources.data.ComponentMetadataData;
49 import org.openecomp.sdc.common.jsongraph.util.CommonUtility;
50 import org.openecomp.sdc.common.jsongraph.util.CommonUtility.LogLevelEnum;
51 import org.openecomp.sdc.common.log.wrappers.Logger;
52 import org.openecomp.sdc.common.util.ValidationUtils;
53 import org.springframework.beans.factory.annotation.Autowired;
56 import java.util.Map.Entry;
57 import java.util.function.BiPredicate;
58 import java.util.stream.Collectors;
60 import static java.util.Objects.requireNonNull;
61 import static org.apache.commons.collections.CollectionUtils.isEmpty;
62 import static org.apache.commons.collections.CollectionUtils.isNotEmpty;
65 @org.springframework.stereotype.Component("tosca-operation-facade")
66 public class ToscaOperationFacade {
70 private static final String COULDNT_FETCH_A_COMPONENT_WITH_AND_UNIQUE_ID_ERROR = "Couldn't fetch a component with and UniqueId {}, error: {}";
71 private static final String FAILED_TO_FIND_RECENTLY_ADDED_PROPERTY_ON_THE_RESOURCE_STATUS_IS = "Failed to find recently added property {} on the resource {}. Status is {}. ";
72 private static final String FAILED_TO_GET_UPDATED_RESOURCE_STATUS_IS = "Failed to get updated resource {}. Status is {}. ";
73 private static final String FAILED_TO_ADD_THE_PROPERTY_TO_THE_RESOURCE_STATUS_IS = "Failed to add the property {} to the resource {}. Status is {}. ";
74 private static final String SERVICE = "service";
75 private static final String NOT_SUPPORTED_COMPONENT_TYPE = "Not supported component type {}";
76 private static final String COMPONENT_CREATED_SUCCESSFULLY = "Component created successfully!!!";
77 private static final String COULDNT_FETCH_COMPONENT_WITH_AND_UNIQUE_ID_ERROR = "Couldn't fetch component with and unique id {}, error: {}";
79 private NodeTypeOperation nodeTypeOperation;
81 private TopologyTemplateOperation topologyTemplateOperation;
83 private NodeTemplateOperation nodeTemplateOperation;
85 private GroupsOperation groupsOperation;
87 private TitanDao titanDao;
89 private static final Logger log = Logger.getLogger(ToscaOperationFacade.class.getName());
92 // region - ToscaElement - GetById
93 public static final String PROXY_SUFFIX = "_proxy";
95 public <T extends Component> Either<T, StorageOperationStatus> getToscaFullElement(String componentId) {
96 ComponentParametersView filters = new ComponentParametersView();
97 filters.setIgnoreCapabiltyProperties(false);
98 filters.setIgnoreForwardingPath(false);
99 return getToscaElement(componentId, filters);
102 public <T extends Component> Either<T, StorageOperationStatus> getToscaElement(String componentId) {
104 return getToscaElement(componentId, JsonParseFlagEnum.ParseAll);
108 public <T extends Component> Either<T, StorageOperationStatus> getToscaElement(String componentId, ComponentParametersView filters) {
110 Either<GraphVertex, TitanOperationStatus> getVertexEither = titanDao.getVertexById(componentId, filters.detectParseFlag());
111 if (getVertexEither.isRight()) {
112 log.debug(COULDNT_FETCH_COMPONENT_WITH_AND_UNIQUE_ID_ERROR, componentId, getVertexEither.right().value());
113 return Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(getVertexEither.right().value()));
116 return getToscaElementByOperation(getVertexEither.left().value(), filters);
119 public <T extends Component> Either<T, StorageOperationStatus> getToscaElement(String componentId, JsonParseFlagEnum parseFlag) {
121 Either<GraphVertex, TitanOperationStatus> getVertexEither = titanDao.getVertexById(componentId, parseFlag);
122 if (getVertexEither.isRight()) {
123 log.debug(COULDNT_FETCH_COMPONENT_WITH_AND_UNIQUE_ID_ERROR, componentId, getVertexEither.right().value());
124 return Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(getVertexEither.right().value()));
127 return getToscaElementByOperation(getVertexEither.left().value());
130 public <T extends Component> Either<T, StorageOperationStatus> getToscaElement(GraphVertex componentVertex) {
131 return getToscaElementByOperation(componentVertex);
134 public Either<Boolean, StorageOperationStatus> validateComponentExists(String componentId) {
136 Either<GraphVertex, TitanOperationStatus> getVertexEither = titanDao.getVertexById(componentId, JsonParseFlagEnum.NoParse);
137 if (getVertexEither.isRight()) {
138 TitanOperationStatus status = getVertexEither.right().value();
139 if (status == TitanOperationStatus.NOT_FOUND) {
140 return Either.left(false);
142 log.debug(COULDNT_FETCH_COMPONENT_WITH_AND_UNIQUE_ID_ERROR, componentId, getVertexEither.right().value());
143 return Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(getVertexEither.right().value()));
146 return Either.left(true);
149 public <T extends Component> Either<T, StorageOperationStatus> findLastCertifiedToscaElementByUUID(T component) {
150 Map<GraphPropertyEnum, Object> props = new EnumMap<>(GraphPropertyEnum.class);
151 props.put(GraphPropertyEnum.UUID, component.getUUID());
152 props.put(GraphPropertyEnum.STATE, LifecycleStateEnum.CERTIFIED.name());
153 props.put(GraphPropertyEnum.IS_HIGHEST_VERSION, true);
155 Either<List<GraphVertex>, TitanOperationStatus> getVertexEither = titanDao.getByCriteria(ModelConverter.getVertexType(component), props);
156 if (getVertexEither.isRight()) {
157 log.debug(COULDNT_FETCH_COMPONENT_WITH_AND_UNIQUE_ID_ERROR, component.getUniqueId(), getVertexEither.right().value());
158 return Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(getVertexEither.right().value()));
161 return getToscaElementByOperation(getVertexEither.left().value().get(0));
165 // region - ToscaElement - GetByOperation
166 private <T extends Component> Either<T, StorageOperationStatus> getToscaElementByOperation(GraphVertex componentV) {
167 return getToscaElementByOperation(componentV, new ComponentParametersView());
170 private <T extends Component> Either<T, StorageOperationStatus> getToscaElementByOperation(GraphVertex componentV, ComponentParametersView filters) {
171 VertexTypeEnum label = componentV.getLabel();
173 ToscaElementOperation toscaOperation = getToscaElementOperation(componentV);
174 Either<ToscaElement, StorageOperationStatus> toscaElement;
175 String componentId = componentV.getUniqueId();
176 if (toscaOperation != null) {
177 log.debug("Need to fetch tosca element for id {}", componentId);
178 toscaElement = toscaOperation.getToscaElement(componentV, filters);
180 log.debug("not supported tosca type {} for id {}", label, componentId);
181 toscaElement = Either.right(StorageOperationStatus.BAD_REQUEST);
183 if (toscaElement.isRight()) {
184 return Either.right(toscaElement.right().value());
186 return Either.left(ModelConverter.convertFromToscaElement(toscaElement.left().value()));
190 private ToscaElementOperation getToscaElementOperation(GraphVertex componentV) {
191 VertexTypeEnum label = componentV.getLabel();
194 return nodeTypeOperation;
195 case TOPOLOGY_TEMPLATE:
196 return topologyTemplateOperation;
202 public <T extends Component> Either<T, StorageOperationStatus> createToscaComponent(T resource) {
203 ToscaElement toscaElement = ModelConverter.convertToToscaElement(resource);
205 ToscaElementOperation toscaElementOperation = getToscaElementOperation(resource);
206 Either<ToscaElement, StorageOperationStatus> createToscaElement = toscaElementOperation.createToscaElement(toscaElement);
207 if (createToscaElement.isLeft()) {
208 log.debug(COMPONENT_CREATED_SUCCESSFULLY);
209 T dataModel = ModelConverter.convertFromToscaElement(createToscaElement.left().value());
210 return Either.left(dataModel);
212 return Either.right(createToscaElement.right().value());
215 // region - ToscaElement Delete
216 public StorageOperationStatus markComponentToDelete(Component componentToDelete) {
218 if ((componentToDelete.getIsDeleted() != null) && componentToDelete.getIsDeleted() && !componentToDelete.isHighestVersion()) {
219 // component already marked for delete
220 return StorageOperationStatus.OK;
223 Either<GraphVertex, TitanOperationStatus> getResponse = titanDao.getVertexById(componentToDelete.getUniqueId(), JsonParseFlagEnum.ParseAll);
224 if (getResponse.isRight()) {
225 log.debug(COULDNT_FETCH_COMPONENT_WITH_AND_UNIQUE_ID_ERROR, componentToDelete.getUniqueId(), getResponse.right().value());
226 return DaoStatusConverter.convertTitanStatusToStorageStatus(getResponse.right().value());
229 GraphVertex componentV = getResponse.left().value();
231 // same operation for node type and topology template operations
232 Either<GraphVertex, StorageOperationStatus> result = nodeTypeOperation.markComponentToDelete(componentV);
233 if (result.isRight()) {
234 return result.right().value();
236 return StorageOperationStatus.OK;
240 public <T extends Component> Either<T, StorageOperationStatus> deleteToscaComponent(String componentId) {
242 Either<GraphVertex, TitanOperationStatus> getVertexEither = titanDao.getVertexById(componentId, JsonParseFlagEnum.ParseAll);
243 if (getVertexEither.isRight()) {
244 log.debug("Couldn't fetch component vertex with and unique id {}, error: {}", componentId, getVertexEither.right().value());
245 return Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(getVertexEither.right().value()));
248 Either<ToscaElement, StorageOperationStatus> deleteElement = deleteToscaElement(getVertexEither.left().value());
249 if (deleteElement.isRight()) {
250 log.debug("Failed to delete component with and unique id {}, error: {}", componentId, deleteElement.right().value());
251 return Either.right(deleteElement.right().value());
253 T dataModel = ModelConverter.convertFromToscaElement(deleteElement.left().value());
255 return Either.left(dataModel);
258 private Either<ToscaElement, StorageOperationStatus> deleteToscaElement(GraphVertex componentV) {
259 VertexTypeEnum label = componentV.getLabel();
260 Either<ToscaElement, StorageOperationStatus> toscaElement;
261 Object componentId = componentV.getUniqueId();
264 log.debug("Need to fetch node type for id {}", componentId);
265 toscaElement = nodeTypeOperation.deleteToscaElement(componentV);
267 case TOPOLOGY_TEMPLATE:
268 log.debug("Need to fetch topology template for id {}", componentId);
269 toscaElement = topologyTemplateOperation.deleteToscaElement(componentV);
272 log.debug("not supported tosca type {} for id {}", label, componentId);
273 toscaElement = Either.right(StorageOperationStatus.BAD_REQUEST);
280 private ToscaElementOperation getToscaElementOperation(Component component) {
281 return ModelConverter.isAtomicComponent(component) ? nodeTypeOperation : topologyTemplateOperation;
284 public <T extends Component> Either<T, StorageOperationStatus> getLatestByToscaResourceName(String toscaResourceName) {
285 return getLatestByName(GraphPropertyEnum.TOSCA_RESOURCE_NAME, toscaResourceName);
288 public <T extends Component> Either<T, StorageOperationStatus> getFullLatestComponentByToscaResourceName(String toscaResourceName) {
289 ComponentParametersView fetchAllFilter = new ComponentParametersView();
290 fetchAllFilter.setIgnoreForwardingPath(true);
291 fetchAllFilter.setIgnoreCapabiltyProperties(false);
292 return getLatestByName(GraphPropertyEnum.TOSCA_RESOURCE_NAME, toscaResourceName, JsonParseFlagEnum.ParseAll, fetchAllFilter);
295 public <T extends Component> Either<T, StorageOperationStatus> getLatestByName(String resourceName) {
296 return getLatestByName(GraphPropertyEnum.NAME, resourceName);
300 public StorageOperationStatus validateCsarUuidUniqueness(String csarUUID) {
302 Map<GraphPropertyEnum, Object> properties = new EnumMap<>(GraphPropertyEnum.class);
303 properties.put(GraphPropertyEnum.CSAR_UUID, csarUUID);
305 Either<List<GraphVertex>, TitanOperationStatus> resources = titanDao.getByCriteria(null, properties, JsonParseFlagEnum.ParseMetadata);
307 if (resources.isRight()) {
308 if (resources.right().value() == TitanOperationStatus.NOT_FOUND) {
309 return StorageOperationStatus.OK;
311 log.debug("failed to get resources from graph with property name: {}", csarUUID);
312 return DaoStatusConverter.convertTitanStatusToStorageStatus(resources.right().value());
315 return StorageOperationStatus.ENTITY_ALREADY_EXISTS;
319 public <T extends Component> Either<Set<T>, StorageOperationStatus> getFollowed(String userId, Set<LifecycleStateEnum> lifecycleStates, Set<LifecycleStateEnum> lastStateStates, ComponentTypeEnum componentType) {
320 Either<List<ToscaElement>, StorageOperationStatus> followedResources;
321 if (componentType == ComponentTypeEnum.RESOURCE) {
322 followedResources = nodeTypeOperation.getFollowedComponent(userId, lifecycleStates, lastStateStates, componentType);
324 followedResources = topologyTemplateOperation.getFollowedComponent(userId, lifecycleStates, lastStateStates, componentType);
327 Set<T> components = new HashSet<>();
328 if (followedResources.isRight() && followedResources.right().value() != StorageOperationStatus.NOT_FOUND) {
329 return Either.right(followedResources.right().value());
331 if (followedResources.isLeft()) {
332 List<ToscaElement> toscaElements = followedResources.left().value();
333 toscaElements.forEach(te -> {
334 T component = ModelConverter.convertFromToscaElement(te);
335 components.add(component);
338 return Either.left(components);
341 public Either<Resource, StorageOperationStatus> getLatestCertifiedNodeTypeByToscaResourceName(String toscaResourceName) {
343 return getLatestCertifiedByToscaResourceName(toscaResourceName, VertexTypeEnum.NODE_TYPE, JsonParseFlagEnum.ParseMetadata);
346 public Either<Resource, StorageOperationStatus> getLatestCertifiedByToscaResourceName(String toscaResourceName, VertexTypeEnum vertexType, JsonParseFlagEnum parseFlag) {
348 Either<Resource, StorageOperationStatus> result = null;
349 Map<GraphPropertyEnum, Object> props = new EnumMap<>(GraphPropertyEnum.class);
350 props.put(GraphPropertyEnum.TOSCA_RESOURCE_NAME, toscaResourceName);
351 props.put(GraphPropertyEnum.IS_HIGHEST_VERSION, true);
352 props.put(GraphPropertyEnum.STATE, LifecycleStateEnum.CERTIFIED.name());
353 Either<List<GraphVertex>, TitanOperationStatus> getLatestRes = titanDao.getByCriteria(vertexType, props, parseFlag);
355 if (getLatestRes.isRight()) {
356 TitanOperationStatus status = getLatestRes.right().value();
357 CommonUtility.addRecordToLog(log, LogLevelEnum.DEBUG, "Failed to fetch {} with name {}. status={} ", vertexType, toscaResourceName, status);
358 result = Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(status));
360 if (result == null) {
361 List<GraphVertex> resources = getLatestRes.left().value();
362 double version = 0.0;
363 GraphVertex highestResource = null;
364 for (GraphVertex resource : resources) {
365 double resourceVersion = Double.parseDouble((String) resource.getJsonMetadataField(JsonPresentationFields.VERSION));
366 if (resourceVersion > version) {
367 version = resourceVersion;
368 highestResource = resource;
371 result = getToscaFullElement(highestResource.getUniqueId());
376 public Either<Boolean, StorageOperationStatus> validateToscaResourceNameExists(String templateName) {
377 Either<Boolean, StorageOperationStatus> validateUniquenessRes = validateToscaResourceNameUniqueness(templateName);
378 if (validateUniquenessRes.isLeft()) {
379 return Either.left(!validateUniquenessRes.left().value());
381 return validateUniquenessRes;
384 public Either<RequirementCapabilityRelDef, StorageOperationStatus> dissociateResourceInstances(String componentId, RequirementCapabilityRelDef requirementDef) {
385 return nodeTemplateOperation.dissociateResourceInstances(componentId, requirementDef);
389 * Allows to get fulfilled requirement by relation and received predicate
391 public Either<RequirementDataDefinition, StorageOperationStatus> getFulfilledRequirementByRelation(String componentId, String instanceId, RequirementCapabilityRelDef relation, BiPredicate<RelationshipInfo, RequirementDataDefinition> predicate) {
392 return nodeTemplateOperation.getFulfilledRequirementByRelation(componentId, instanceId, relation, predicate);
396 * Allows to get fulfilled capability by relation and received predicate
398 public Either<CapabilityDataDefinition, StorageOperationStatus> getFulfilledCapabilityByRelation(String componentId, String instanceId, RequirementCapabilityRelDef relation, BiPredicate<RelationshipInfo, CapabilityDataDefinition> predicate) {
399 return nodeTemplateOperation.getFulfilledCapabilityByRelation(componentId, instanceId, relation, predicate);
402 public StorageOperationStatus associateResourceInstances(String componentId, List<RequirementCapabilityRelDef> relations) {
403 Either<List<RequirementCapabilityRelDef>, StorageOperationStatus> status = nodeTemplateOperation.associateResourceInstances(componentId, relations);
404 if (status.isRight()) {
405 return status.right().value();
407 return StorageOperationStatus.OK;
410 protected Either<Boolean, StorageOperationStatus> validateToscaResourceNameUniqueness(String name) {
412 Map<GraphPropertyEnum, Object> properties = new EnumMap<>(GraphPropertyEnum.class);
413 properties.put(GraphPropertyEnum.TOSCA_RESOURCE_NAME, name);
415 Either<List<GraphVertex>, TitanOperationStatus> resources = titanDao.getByCriteria(null, properties, JsonParseFlagEnum.ParseMetadata);
417 if (resources.isRight() && resources.right().value() != TitanOperationStatus.NOT_FOUND) {
418 log.debug("failed to get resources from graph with property name: {}", name);
419 return Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(resources.right().value()));
421 List<GraphVertex> resourceList = (resources.isLeft() ? resources.left().value() : null);
422 if (isNotEmpty(resourceList)) {
423 if (log.isDebugEnabled()) {
424 StringBuilder builder = new StringBuilder();
425 for (GraphVertex resourceData : resourceList) {
426 builder.append(resourceData.getUniqueId() + "|");
428 log.debug("resources with property name:{} exists in graph. found {}", name, builder);
430 return Either.left(false);
432 log.debug("resources with property name:{} does not exists in graph", name);
433 return Either.left(true);
438 // region - Component Update
440 public Either<Resource, StorageOperationStatus> overrideComponent(Resource newComponent, Resource oldComponent) {
442 copyArtifactsToNewComponent(newComponent, oldComponent);
444 Either<GraphVertex, TitanOperationStatus> componentVEither = titanDao.getVertexById(oldComponent.getUniqueId(), JsonParseFlagEnum.NoParse);
445 if (componentVEither.isRight()) {
446 log.debug("Falied to fetch component {} error {}", oldComponent.getUniqueId(), componentVEither.right().value());
447 return Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(componentVEither.right().value()));
449 GraphVertex componentv = componentVEither.left().value();
450 Either<GraphVertex, TitanOperationStatus> parentVertexEither = titanDao.getParentVertex(componentv, EdgeLabelEnum.VERSION, JsonParseFlagEnum.NoParse);
451 if (parentVertexEither.isRight() && parentVertexEither.right().value() != TitanOperationStatus.NOT_FOUND) {
452 log.debug("Falied to fetch parent version for component {} error {}", oldComponent.getUniqueId(), parentVertexEither.right().value());
453 return Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(parentVertexEither.right().value()));
456 Either<ToscaElement, StorageOperationStatus> deleteToscaComponent = deleteToscaElement(componentv);
457 if (deleteToscaComponent.isRight()) {
458 log.debug("Falied to remove old component {} error {}", oldComponent.getUniqueId(), deleteToscaComponent.right().value());
459 return Either.right(deleteToscaComponent.right().value());
461 Either<Resource, StorageOperationStatus> createToscaComponent = createToscaComponent(newComponent);
462 if (createToscaComponent.isRight()) {
463 log.debug("Falied to create tosca element component {} error {}", newComponent.getUniqueId(), createToscaComponent.right().value());
464 return Either.right(createToscaComponent.right().value());
466 Resource newElement = createToscaComponent.left().value();
467 Either<GraphVertex, TitanOperationStatus> newVersionEither = titanDao.getVertexById(newElement.getUniqueId(), JsonParseFlagEnum.NoParse);
468 if (newVersionEither.isRight()) {
469 log.debug("Falied to fetch new tosca element component {} error {}", newComponent.getUniqueId(), newVersionEither.right().value());
470 return Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(newVersionEither.right().value()));
472 if (parentVertexEither.isLeft()) {
473 GraphVertex previousVersionV = parentVertexEither.left().value();
474 TitanOperationStatus createEdge = titanDao.createEdge(previousVersionV, newVersionEither.left().value(), EdgeLabelEnum.VERSION, null);
475 if (createEdge != TitanOperationStatus.OK) {
476 log.debug("Falied to associate to previous version {} new version {} error {}", previousVersionV.getUniqueId(), newVersionEither.right().value(), createEdge);
477 return Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(createEdge));
480 return Either.left(newElement);
483 void copyArtifactsToNewComponent(Resource newComponent, Resource oldComponent) {
484 // TODO - check if required
485 Map<String, ArtifactDefinition> toscaArtifacts = oldComponent.getToscaArtifacts();
486 if (toscaArtifacts != null && !toscaArtifacts.isEmpty()) {
487 toscaArtifacts.values().stream().forEach(a -> a.setDuplicated(Boolean.TRUE));
489 newComponent.setToscaArtifacts(toscaArtifacts);
491 Map<String, ArtifactDefinition> artifacts = oldComponent.getArtifacts();
492 if (artifacts != null && !artifacts.isEmpty()) {
493 artifacts.values().stream().forEach(a -> a.setDuplicated(Boolean.TRUE));
495 newComponent.setArtifacts(artifacts);
497 Map<String, ArtifactDefinition> depArtifacts = oldComponent.getDeploymentArtifacts();
498 if (depArtifacts != null && !depArtifacts.isEmpty()) {
499 depArtifacts.values().stream().forEach(a -> a.setDuplicated(Boolean.TRUE));
501 newComponent.setDeploymentArtifacts(depArtifacts);
503 newComponent.setGroups(oldComponent.getGroups());
504 newComponent.setLastUpdateDate(null);
505 newComponent.setHighestVersion(true);
508 public <T extends Component> Either<T, StorageOperationStatus> updateToscaElement(T componentToUpdate) {
509 return updateToscaElement(componentToUpdate, new ComponentParametersView());
512 public <T extends Component> Either<T, StorageOperationStatus> updateToscaElement(T componentToUpdate, ComponentParametersView filterResult) {
513 String componentId = componentToUpdate.getUniqueId();
514 Either<GraphVertex, TitanOperationStatus> getVertexEither = titanDao.getVertexById(componentId, JsonParseFlagEnum.ParseAll);
515 if (getVertexEither.isRight()) {
516 log.debug(COULDNT_FETCH_COMPONENT_WITH_AND_UNIQUE_ID_ERROR, componentId, getVertexEither.right().value());
517 return Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(getVertexEither.right().value()));
519 GraphVertex elementV = getVertexEither.left().value();
520 ToscaElementOperation toscaElementOperation = getToscaElementOperation(elementV);
522 ToscaElement toscaElementToUpdate = ModelConverter.convertToToscaElement(componentToUpdate);
523 Either<ToscaElement, StorageOperationStatus> updateToscaElement = toscaElementOperation.updateToscaElement(toscaElementToUpdate, elementV, filterResult);
524 if (updateToscaElement.isRight()) {
525 log.debug("Failed to update tosca element {} error {}", componentId, updateToscaElement.right().value());
526 return Either.right(updateToscaElement.right().value());
528 return Either.left(ModelConverter.convertFromToscaElement(updateToscaElement.left().value()));
531 private <T extends Component> Either<T, StorageOperationStatus> getLatestByName(GraphPropertyEnum property, String nodeName, JsonParseFlagEnum parseFlag) {
532 return getLatestByName(property, nodeName, parseFlag, new ComponentParametersView());
535 private <T extends Component> Either<T, StorageOperationStatus> getLatestByName(GraphPropertyEnum property, String nodeName, JsonParseFlagEnum parseFlag, ComponentParametersView filter) {
536 Either<T, StorageOperationStatus> result;
538 Map<GraphPropertyEnum, Object> propertiesToMatch = new EnumMap<>(GraphPropertyEnum.class);
539 Map<GraphPropertyEnum, Object> propertiesNotToMatch = new EnumMap<>(GraphPropertyEnum.class);
541 propertiesToMatch.put(property, nodeName);
542 propertiesToMatch.put(GraphPropertyEnum.IS_HIGHEST_VERSION, true);
544 propertiesNotToMatch.put(GraphPropertyEnum.IS_DELETED, true);
546 Either<List<GraphVertex>, TitanOperationStatus> highestResources = titanDao.getByCriteria(null, propertiesToMatch, propertiesNotToMatch, parseFlag);
547 if (highestResources.isRight()) {
548 TitanOperationStatus status = highestResources.right().value();
549 log.debug("failed to find resource with name {}. status={} ", nodeName, status);
550 result = Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(status));
554 List<GraphVertex> resources = highestResources.left().value();
555 double version = 0.0;
556 GraphVertex highestResource = null;
557 for (GraphVertex vertex : resources) {
558 Object versionObj = vertex.getMetadataProperty(GraphPropertyEnum.VERSION);
559 double resourceVersion = Double.parseDouble((String) versionObj);
560 if (resourceVersion > version) {
561 version = resourceVersion;
562 highestResource = vertex;
565 return getToscaElementByOperation(highestResource, filter);
569 // region - Component Get By ..
570 private <T extends Component> Either<T, StorageOperationStatus> getLatestByName(GraphPropertyEnum property, String nodeName) {
571 return getLatestByName(property, nodeName, JsonParseFlagEnum.ParseMetadata);
574 public <T extends Component> Either<List<T>, StorageOperationStatus> getBySystemName(ComponentTypeEnum componentType, String systemName) {
576 Either<List<T>, StorageOperationStatus> result = null;
577 Either<T, StorageOperationStatus> getComponentRes;
578 List<T> components = new ArrayList<>();
579 List<GraphVertex> componentVertices;
580 Map<GraphPropertyEnum, Object> propertiesToMatch = new EnumMap<>(GraphPropertyEnum.class);
581 Map<GraphPropertyEnum, Object> propertiesNotToMatch = new EnumMap<>(GraphPropertyEnum.class);
583 propertiesToMatch.put(GraphPropertyEnum.SYSTEM_NAME, systemName);
584 if (componentType != null)
585 propertiesToMatch.put(GraphPropertyEnum.COMPONENT_TYPE, componentType.name());
587 propertiesNotToMatch.put(GraphPropertyEnum.IS_DELETED, true);
589 Either<List<GraphVertex>, TitanOperationStatus> getComponentsRes = titanDao.getByCriteria(null, propertiesToMatch, propertiesNotToMatch, JsonParseFlagEnum.ParseAll);
590 if (getComponentsRes.isRight()) {
591 TitanOperationStatus status = getComponentsRes.right().value();
592 log.debug("Failed to fetch the component with system name {}. Status is {} ", systemName, status);
593 result = Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(status));
595 if (result == null) {
596 componentVertices = getComponentsRes.left().value();
597 for (GraphVertex componentVertex : componentVertices) {
598 getComponentRes = getToscaElementByOperation(componentVertex);
599 if (getComponentRes.isRight()) {
600 log.debug("Failed to get the component {}. Status is {} ", componentVertex.getJsonMetadataField(JsonPresentationFields.NAME), getComponentRes.right().value());
601 result = Either.right(getComponentRes.right().value());
604 T componentBySystemName = getComponentRes.left().value();
605 log.debug("Found component, id: {}", componentBySystemName.getUniqueId());
606 components.add(componentBySystemName);
609 if (result == null) {
610 result = Either.left(components);
615 public <T extends Component> Either<T, StorageOperationStatus> getComponentByNameAndVersion(ComponentTypeEnum componentType, String name, String version) {
616 return getComponentByNameAndVersion(componentType, name, version, JsonParseFlagEnum.ParseAll);
619 public <T extends Component> Either<T, StorageOperationStatus> getComponentByNameAndVersion(ComponentTypeEnum componentType, String name, String version, JsonParseFlagEnum parseFlag) {
620 Either<T, StorageOperationStatus> result;
622 Map<GraphPropertyEnum, Object> hasProperties = new EnumMap<>(GraphPropertyEnum.class);
623 Map<GraphPropertyEnum, Object> hasNotProperties = new EnumMap<>(GraphPropertyEnum.class);
625 hasProperties.put(GraphPropertyEnum.NAME, name);
626 hasProperties.put(GraphPropertyEnum.VERSION, version);
627 hasNotProperties.put(GraphPropertyEnum.IS_DELETED, true);
628 if (componentType != null) {
629 hasProperties.put(GraphPropertyEnum.COMPONENT_TYPE, componentType.name());
631 Either<List<GraphVertex>, TitanOperationStatus> getResourceRes = titanDao.getByCriteria(null, hasProperties, hasNotProperties, parseFlag);
632 if (getResourceRes.isRight()) {
633 TitanOperationStatus status = getResourceRes.right().value();
634 log.debug("failed to find resource with name {}, version {}. Status is {} ", name, version, status);
635 result = Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(status));
638 return getToscaElementByOperation(getResourceRes.left().value().get(0));
641 public Either<List<CatalogComponent>, StorageOperationStatus> getCatalogOrArchiveComponents(boolean isCatalog, List<OriginTypeEnum> excludeTypes) {
642 List<ResourceTypeEnum> excludedResourceTypes = Optional.ofNullable(excludeTypes).orElse(Collections.emptyList()).stream().filter(type -> !type.equals(OriginTypeEnum.SERVICE)).map(type -> ResourceTypeEnum.getTypeByName(type.name()))
643 .collect(Collectors.toList());
644 return topologyTemplateOperation.getElementCatalogData(isCatalog, excludedResourceTypes);
648 public <T extends Component> Either<List<T>, StorageOperationStatus> getCatalogComponents(ComponentTypeEnum componentType, List<OriginTypeEnum> excludeTypes, boolean isHighestVersions) {
649 List<T> components = new ArrayList<>();
650 Either<List<ToscaElement>, StorageOperationStatus> catalogDataResult;
651 List<ToscaElement> toscaElements = new ArrayList<>();
652 List<ResourceTypeEnum> excludedResourceTypes = Optional.ofNullable(excludeTypes).orElse(Collections.emptyList()).stream().filter(type -> !type.equals(OriginTypeEnum.SERVICE)).map(type -> ResourceTypeEnum.getTypeByName(type.name()))
653 .collect(Collectors.toList());
655 switch (componentType) {
657 catalogDataResult = nodeTypeOperation.getElementCatalogData(ComponentTypeEnum.RESOURCE, excludedResourceTypes, isHighestVersions);
658 if (catalogDataResult.isRight()) {
659 return Either.right(catalogDataResult.right().value());
661 toscaElements = catalogDataResult.left().value();
664 if (excludeTypes != null && excludeTypes.contains(OriginTypeEnum.SERVICE)) {
667 catalogDataResult = topologyTemplateOperation.getElementCatalogData(ComponentTypeEnum.SERVICE, null, isHighestVersions);
668 if (catalogDataResult.isRight()) {
669 return Either.right(catalogDataResult.right().value());
671 toscaElements = catalogDataResult.left().value();
674 log.debug(NOT_SUPPORTED_COMPONENT_TYPE, componentType);
675 return Either.right(StorageOperationStatus.BAD_REQUEST);
677 toscaElements.forEach(te -> {
678 T component = ModelConverter.convertFromToscaElement(te);
679 components.add(component);
681 return Either.left(components);
684 public Either<List<String>, StorageOperationStatus> deleteMarkedElements(ComponentTypeEnum componentType) {
685 Either<List<GraphVertex>, StorageOperationStatus> allComponentsMarkedForDeletion;
686 switch (componentType) {
688 allComponentsMarkedForDeletion = nodeTypeOperation.getAllComponentsMarkedForDeletion(componentType);
692 allComponentsMarkedForDeletion = topologyTemplateOperation.getAllComponentsMarkedForDeletion(componentType);
695 log.debug(NOT_SUPPORTED_COMPONENT_TYPE, componentType);
696 return Either.right(StorageOperationStatus.BAD_REQUEST);
698 if (allComponentsMarkedForDeletion.isRight()) {
699 return Either.right(allComponentsMarkedForDeletion.right().value());
701 List<GraphVertex> allMarked = allComponentsMarkedForDeletion.left().value();
702 return Either.left(checkIfInUseAndDelete(allMarked));
705 private List<String> checkIfInUseAndDelete(List<GraphVertex> allMarked) {
706 final List<EdgeLabelEnum> forbiddenEdgeLabelEnums = Arrays.asList(EdgeLabelEnum.INSTANCE_OF, EdgeLabelEnum.PROXY_OF, EdgeLabelEnum.ALLOTTED_OF);
707 List<String> deleted = new ArrayList<>();
709 for (GraphVertex elementV : allMarked) {
710 boolean isAllowedToDelete = true;
712 for (EdgeLabelEnum edgeLabelEnum : forbiddenEdgeLabelEnums) {
713 Either<Edge, TitanOperationStatus> belongingEdgeByCriteria = titanDao.getBelongingEdgeByCriteria(elementV, edgeLabelEnum, null);
714 if (belongingEdgeByCriteria.isLeft()){
715 log.debug("Marked element {} in use. don't delete it", elementV.getUniqueId());
716 isAllowedToDelete = false;
721 if (isAllowedToDelete) {
722 Either<ToscaElement, StorageOperationStatus> deleteToscaElement = deleteToscaElement(elementV);
723 if (deleteToscaElement.isRight()) {
724 log.debug("Failed to delete marked element UniqueID {}, Name {}, error {}", elementV.getUniqueId(), elementV.getMetadataProperties().get(GraphPropertyEnum.NAME), deleteToscaElement.right().value());
727 deleted.add(elementV.getUniqueId());
733 public Either<List<String>, StorageOperationStatus> getAllComponentsMarkedForDeletion(ComponentTypeEnum componentType) {
734 Either<List<GraphVertex>, StorageOperationStatus> allComponentsMarkedForDeletion;
735 switch (componentType) {
737 allComponentsMarkedForDeletion = nodeTypeOperation.getAllComponentsMarkedForDeletion(componentType);
741 allComponentsMarkedForDeletion = topologyTemplateOperation.getAllComponentsMarkedForDeletion(componentType);
744 log.debug(NOT_SUPPORTED_COMPONENT_TYPE, componentType);
745 return Either.right(StorageOperationStatus.BAD_REQUEST);
747 if (allComponentsMarkedForDeletion.isRight()) {
748 return Either.right(allComponentsMarkedForDeletion.right().value());
750 return Either.left(allComponentsMarkedForDeletion.left().value().stream().map(GraphVertex::getUniqueId).collect(Collectors.toList()));
753 // region - Component Update
754 public Either<ImmutablePair<Component, String>, StorageOperationStatus> addComponentInstanceToTopologyTemplate(Component containerComponent, Component origComponent, ComponentInstance componentInstance, boolean allowDeleted, User user) {
756 Either<ImmutablePair<Component, String>, StorageOperationStatus> result = null;
757 Either<ToscaElement, StorageOperationStatus> updateContainerComponentRes = null;
758 if (StringUtils.isEmpty(componentInstance.getIcon())) {
759 componentInstance.setIcon(origComponent.getIcon());
761 String nameToFindForCounter = componentInstance.getOriginType() == OriginTypeEnum.ServiceProxy ? componentInstance.getSourceModelName() + PROXY_SUFFIX : origComponent.getName();
762 String nextComponentInstanceCounter = getNextComponentInstanceCounter(containerComponent, nameToFindForCounter);
763 Either<ImmutablePair<TopologyTemplate, String>, StorageOperationStatus> addResult = nodeTemplateOperation.addComponentInstanceToTopologyTemplate(ModelConverter.convertToToscaElement(containerComponent),
764 ModelConverter.convertToToscaElement(origComponent), nextComponentInstanceCounter, componentInstance, allowDeleted, user);
766 if (addResult.isRight()) {
767 CommonUtility.addRecordToLog(log, LogLevelEnum.DEBUG, "Failed to add the component instance {} to container component {}. ", componentInstance.getName(), containerComponent.getName());
768 result = Either.right(addResult.right().value());
770 if (result == null) {
771 updateContainerComponentRes = topologyTemplateOperation.getToscaElement(containerComponent.getUniqueId());
772 if (updateContainerComponentRes.isRight()) {
773 CommonUtility.addRecordToLog(log, LogLevelEnum.DEBUG, "Failed to fetch updated topology template {} with updated component instance {}. ", containerComponent.getName(), componentInstance.getName());
774 result = Either.right(updateContainerComponentRes.right().value());
777 if (result == null) {
778 Component updatedComponent = ModelConverter.convertFromToscaElement(updateContainerComponentRes.left().value());
779 String createdInstanceId = addResult.left().value().getRight();
780 CommonUtility.addRecordToLog(log, LogLevelEnum.TRACE, "The component instance {} has been added to container component {}. ", createdInstanceId, updatedComponent.getName());
781 result = Either.left(new ImmutablePair<>(updatedComponent, createdInstanceId));
786 public StorageOperationStatus associateComponentInstancesToComponent(Component containerComponent, Map<ComponentInstance, Resource> resourcesInstancesMap, boolean allowDeleted) {
788 StorageOperationStatus result = null;
789 CommonUtility.addRecordToLog(log, LogLevelEnum.DEBUG, "Going to add component instances to component {}", containerComponent.getUniqueId());
791 Either<GraphVertex, TitanOperationStatus> metadataVertex = titanDao.getVertexById(containerComponent.getUniqueId(), JsonParseFlagEnum.ParseAll);
792 if (metadataVertex.isRight()) {
793 TitanOperationStatus status = metadataVertex.right().value();
794 if (status == TitanOperationStatus.NOT_FOUND) {
795 status = TitanOperationStatus.INVALID_ID;
797 result = DaoStatusConverter.convertTitanStatusToStorageStatus(status);
799 if (result == null) {
800 result = nodeTemplateOperation.associateComponentInstancesToComponent(containerComponent, resourcesInstancesMap, metadataVertex.left().value(), allowDeleted);
805 public Either<ImmutablePair<Component, String>, StorageOperationStatus> updateComponentInstanceMetadataOfTopologyTemplate(Component containerComponent, Component origComponent, ComponentInstance componentInstance) {
807 Either<ImmutablePair<Component, String>, StorageOperationStatus> result = null;
809 CommonUtility.addRecordToLog(log, LogLevelEnum.TRACE, "Going to update the metadata of the component instance {} belonging to container component {}. ", componentInstance.getName(), containerComponent.getName());
810 componentInstance.setIcon(origComponent.getIcon());
811 Either<ImmutablePair<TopologyTemplate, String>, StorageOperationStatus> updateResult = nodeTemplateOperation.updateComponentInstanceMetadataOfTopologyTemplate(ModelConverter.convertToToscaElement(containerComponent),
812 ModelConverter.convertToToscaElement(origComponent), componentInstance);
813 if (updateResult.isRight()) {
814 CommonUtility.addRecordToLog(log, LogLevelEnum.DEBUG, "Failed to update the metadata of the component instance {} belonging to container component {}. ", componentInstance.getName(), containerComponent.getName());
815 result = Either.right(updateResult.right().value());
817 if (result == null) {
818 Component updatedComponent = ModelConverter.convertFromToscaElement(updateResult.left().value().getLeft());
819 String createdInstanceId = updateResult.left().value().getRight();
820 CommonUtility.addRecordToLog(log, LogLevelEnum.TRACE, "The metadata of the component instance {} has been updated to container component {}. ", createdInstanceId, updatedComponent.getName());
821 result = Either.left(new ImmutablePair<>(updatedComponent, createdInstanceId));
826 public Either<Component, StorageOperationStatus> updateComponentInstanceMetadataOfTopologyTemplate(Component containerComponent) {
827 return updateComponentInstanceMetadataOfTopologyTemplate(containerComponent, new ComponentParametersView());
830 public Either<Component, StorageOperationStatus> updateComponentInstanceMetadataOfTopologyTemplate(Component containerComponent, ComponentParametersView filter) {
832 Either<Component, StorageOperationStatus> result = null;
834 CommonUtility.addRecordToLog(log, LogLevelEnum.TRACE, "Going to update the metadata belonging to container component {}. ", containerComponent.getName());
836 Either<TopologyTemplate, StorageOperationStatus> updateResult = nodeTemplateOperation.updateComponentInstanceMetadataOfTopologyTemplate(ModelConverter.convertToToscaElement(containerComponent), filter);
837 if (updateResult.isRight()) {
838 CommonUtility.addRecordToLog(log, LogLevelEnum.DEBUG, "Failed to update the metadata belonging to container component {}. ", containerComponent.getName());
839 result = Either.right(updateResult.right().value());
841 if (result == null) {
842 Component updatedComponent = ModelConverter.convertFromToscaElement(updateResult.left().value());
843 CommonUtility.addRecordToLog(log, LogLevelEnum.TRACE, "The metadata has been updated to container component {}. ", updatedComponent.getName());
844 result = Either.left(updatedComponent);
850 public Either<ImmutablePair<Component, String>, StorageOperationStatus> deleteComponentInstanceFromTopologyTemplate(Component containerComponent, String resourceInstanceId) {
852 Either<ImmutablePair<Component, String>, StorageOperationStatus> result = null;
854 CommonUtility.addRecordToLog(log, LogLevelEnum.TRACE, "Going to delete the component instance {} belonging to container component {}. ", resourceInstanceId, containerComponent.getName());
856 Either<ImmutablePair<TopologyTemplate, String>, StorageOperationStatus> updateResult = nodeTemplateOperation.deleteComponentInstanceFromTopologyTemplate(ModelConverter.convertToToscaElement(containerComponent), resourceInstanceId);
857 if (updateResult.isRight()) {
858 CommonUtility.addRecordToLog(log, LogLevelEnum.DEBUG, "Failed to delete the component instance {} belonging to container component {}. ", resourceInstanceId, containerComponent.getName());
859 result = Either.right(updateResult.right().value());
861 if (result == null) {
862 Component updatedComponent = ModelConverter.convertFromToscaElement(updateResult.left().value().getLeft());
863 String deletedInstanceId = updateResult.left().value().getRight();
864 CommonUtility.addRecordToLog(log, LogLevelEnum.TRACE, "The component instance {} has been deleted from container component {}. ", deletedInstanceId, updatedComponent.getName());
865 result = Either.left(new ImmutablePair<>(updatedComponent, deletedInstanceId));
870 private String getNextComponentInstanceCounter(Component containerComponent, String originResourceName) {
871 Integer nextCounter = 0;
872 if (CollectionUtils.isNotEmpty(containerComponent.getComponentInstances())) {
873 String normalizedName = ValidationUtils.normalizeComponentInstanceName(originResourceName);
874 Integer maxCounter = getMaxCounterFromNamesAndIds(containerComponent, normalizedName);
875 if (maxCounter != null) {
876 nextCounter = maxCounter + 1;
879 return nextCounter.toString();
883 * @return max counter of component instance Id's, null if not found
885 private Integer getMaxCounterFromNamesAndIds(Component containerComponent, String normalizedName) {
886 List<String> countersInNames = containerComponent.getComponentInstances().stream()
887 .filter(ci -> ci.getNormalizedName() != null && ci.getNormalizedName().startsWith(normalizedName))
888 .map(ci -> ci.getNormalizedName().split(normalizedName)[1])
889 .collect(Collectors.toList());
890 List<String> countersInIds = containerComponent.getComponentInstances().stream()
891 .filter(ci -> ci.getUniqueId() != null && ci.getUniqueId().contains(normalizedName))
892 .map(ci -> ci.getUniqueId().split(normalizedName)[1])
893 .collect(Collectors.toList());
894 List<String> namesAndIdsList = new ArrayList<>(countersInNames);
895 namesAndIdsList.addAll(countersInIds);
896 return getMaxInteger(namesAndIdsList);
899 private Integer getMaxInteger(List<String> counters) {
900 Integer maxCounter = 0;
901 Integer currCounter = null;
902 for (String counter : counters) {
904 currCounter = Integer.parseInt(counter);
905 if (maxCounter < currCounter) {
906 maxCounter = currCounter;
908 } catch (NumberFormatException e) {
912 return currCounter == null ? null : maxCounter;
915 public Either<RequirementCapabilityRelDef, StorageOperationStatus> associateResourceInstances(String componentId, RequirementCapabilityRelDef requirementDef) {
916 return nodeTemplateOperation.associateResourceInstances(componentId, requirementDef);
920 public Either<List<InputDefinition>, StorageOperationStatus> createAndAssociateInputs(Map<String, InputDefinition> inputs, String componentId) {
922 Either<GraphVertex, TitanOperationStatus> getVertexEither = titanDao.getVertexById(componentId, JsonParseFlagEnum.NoParse);
923 if (getVertexEither.isRight()) {
924 log.debug(COULDNT_FETCH_COMPONENT_WITH_AND_UNIQUE_ID_ERROR, componentId, getVertexEither.right().value());
925 return Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(getVertexEither.right().value()));
929 GraphVertex vertex = getVertexEither.left().value();
930 Map<String, PropertyDataDefinition> inputsMap = inputs.entrySet().stream().collect(Collectors.toMap(Map.Entry::getKey, e -> new PropertyDataDefinition(e.getValue())));
932 StorageOperationStatus status = topologyTemplateOperation.associateInputsToComponent(vertex, inputsMap, componentId);
934 if (StorageOperationStatus.OK == status) {
935 log.debug(COMPONENT_CREATED_SUCCESSFULLY);
936 List<InputDefinition> inputsResList = null;
937 if (inputsMap != null && !inputsMap.isEmpty()) {
938 inputsResList = inputsMap.values().stream()
939 .map(InputDefinition::new)
940 .collect(Collectors.toList());
942 return Either.left(inputsResList);
944 return Either.right(status);
948 public Either<List<InputDefinition>, StorageOperationStatus> addInputsToComponent(Map<String, InputDefinition> inputs, String componentId) {
950 Either<GraphVertex, TitanOperationStatus> getVertexEither = titanDao.getVertexById(componentId, JsonParseFlagEnum.NoParse);
951 if (getVertexEither.isRight()) {
952 log.debug(COULDNT_FETCH_COMPONENT_WITH_AND_UNIQUE_ID_ERROR, componentId, getVertexEither.right().value());
953 return Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(getVertexEither.right().value()));
957 GraphVertex vertex = getVertexEither.left().value();
958 Map<String, PropertyDataDefinition> inputsMap = inputs.entrySet().stream().collect(Collectors.toMap(Map.Entry::getKey, e -> new PropertyDataDefinition(e.getValue())));
960 StorageOperationStatus status = topologyTemplateOperation.addToscaDataToToscaElement(vertex, EdgeLabelEnum.INPUTS, VertexTypeEnum.INPUTS, inputsMap, JsonPresentationFields.NAME);
962 if (StorageOperationStatus.OK == status) {
963 log.debug(COMPONENT_CREATED_SUCCESSFULLY);
964 List<InputDefinition> inputsResList = null;
965 if (inputsMap != null && !inputsMap.isEmpty()) {
966 inputsResList = inputsMap.values().stream().map(InputDefinition::new).collect(Collectors.toList());
968 return Either.left(inputsResList);
970 return Either.right(status);
974 public Either<List<InputDefinition>, StorageOperationStatus> updateInputsToComponent(List<InputDefinition> inputs, String componentId) {
976 Either<GraphVertex, TitanOperationStatus> getVertexEither = titanDao.getVertexById(componentId, JsonParseFlagEnum.NoParse);
977 if (getVertexEither.isRight()) {
978 log.debug(COULDNT_FETCH_COMPONENT_WITH_AND_UNIQUE_ID_ERROR, componentId, getVertexEither.right().value());
979 return Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(getVertexEither.right().value()));
983 GraphVertex vertex = getVertexEither.left().value();
984 List<PropertyDataDefinition> inputsAsDataDef = inputs.stream().map(PropertyDataDefinition::new).collect(Collectors.toList());
986 StorageOperationStatus status = topologyTemplateOperation.updateToscaDataOfToscaElement(vertex, EdgeLabelEnum.INPUTS, VertexTypeEnum.INPUTS, inputsAsDataDef, JsonPresentationFields.NAME);
988 if (StorageOperationStatus.OK == status) {
989 log.debug(COMPONENT_CREATED_SUCCESSFULLY);
990 List<InputDefinition> inputsResList = null;
991 if (inputsAsDataDef != null && !inputsAsDataDef.isEmpty()) {
992 inputsResList = inputsAsDataDef.stream().map(InputDefinition::new).collect(Collectors.toList());
994 return Either.left(inputsResList);
996 return Either.right(status);
1000 // region - ComponentInstance
1001 public Either<Map<String, List<ComponentInstanceProperty>>, StorageOperationStatus> associateComponentInstancePropertiesToComponent(Map<String, List<ComponentInstanceProperty>> instProperties, String componentId) {
1003 Either<GraphVertex, TitanOperationStatus> getVertexEither = titanDao.getVertexById(componentId, JsonParseFlagEnum.NoParse);
1004 if (getVertexEither.isRight()) {
1005 log.debug(COULDNT_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, MapPropertiesDataDefinition> instPropsMap = new HashMap<>();
1012 if (instProperties != null) {
1014 MapPropertiesDataDefinition propertiesMap;
1015 for (Entry<String, List<ComponentInstanceProperty>> entry : instProperties.entrySet()) {
1016 propertiesMap = new MapPropertiesDataDefinition();
1018 propertiesMap.setMapToscaDataDefinition(entry.getValue().stream().map(PropertyDataDefinition::new).collect(Collectors.toMap(PropertyDataDefinition::getName, e -> e)));
1020 instPropsMap.put(entry.getKey(), propertiesMap);
1024 StorageOperationStatus status = topologyTemplateOperation.associateInstPropertiesToComponent(vertex, instPropsMap);
1026 if (StorageOperationStatus.OK == status) {
1027 log.debug(COMPONENT_CREATED_SUCCESSFULLY);
1028 return Either.left(instProperties);
1030 return Either.right(status);
1035 * saves the instInputs as the updated instance inputs of the component container in DB
1037 public Either<Map<String, List<ComponentInstanceInput>>, StorageOperationStatus> updateComponentInstanceInputsToComponent(Map<String, List<ComponentInstanceInput>> instInputs, String componentId) {
1038 if (instInputs == null || instInputs.isEmpty()) {
1039 return Either.left(instInputs);
1041 StorageOperationStatus status;
1042 for (Entry<String, List<ComponentInstanceInput>> inputsPerIntance : instInputs.entrySet()) {
1043 List<ComponentInstanceInput> toscaDataListPerInst = inputsPerIntance.getValue();
1044 List<String> pathKeysPerInst = new ArrayList<>();
1045 pathKeysPerInst.add(inputsPerIntance.getKey());
1046 status = topologyTemplateOperation.updateToscaDataDeepElementsOfToscaElement(componentId, EdgeLabelEnum.INST_INPUTS, VertexTypeEnum.INST_INPUTS, toscaDataListPerInst, pathKeysPerInst, JsonPresentationFields.NAME);
1047 if (status != StorageOperationStatus.OK) {
1048 log.debug("Failed to update component instance inputs for instance {} in component {} edge type {} error {}", inputsPerIntance.getKey(), componentId, EdgeLabelEnum.INST_INPUTS, status);
1049 return Either.right(status);
1053 return Either.left(instInputs);
1057 * saves the instProps as the updated instance properties of the component container in DB
1059 public Either<Map<String, List<ComponentInstanceProperty>>, StorageOperationStatus> updateComponentInstancePropsToComponent(Map<String, List<ComponentInstanceProperty>> instProps, String componentId) {
1060 if (instProps == null || instProps.isEmpty()) {
1061 return Either.left(instProps);
1063 StorageOperationStatus status;
1064 for (Entry<String, List<ComponentInstanceProperty>> propsPerIntance : instProps.entrySet()) {
1065 List<ComponentInstanceProperty> toscaDataListPerInst = propsPerIntance.getValue();
1066 List<String> pathKeysPerInst = new ArrayList<>();
1067 pathKeysPerInst.add(propsPerIntance.getKey());
1068 status = topologyTemplateOperation.updateToscaDataDeepElementsOfToscaElement(componentId, EdgeLabelEnum.INST_PROPERTIES, VertexTypeEnum.INST_PROPERTIES, toscaDataListPerInst, pathKeysPerInst, JsonPresentationFields.NAME);
1069 if (status != StorageOperationStatus.OK) {
1070 log.debug("Failed to update component instance inputs for instance {} in component {} edge type {} error {}", propsPerIntance.getKey(), componentId, EdgeLabelEnum.INST_PROPERTIES, status);
1071 return Either.right(status);
1075 return Either.left(instProps);
1078 public Either<Map<String, List<ComponentInstanceInput>>, StorageOperationStatus> associateComponentInstanceInputsToComponent(Map<String, List<ComponentInstanceInput>> instInputs, String componentId) {
1080 Either<GraphVertex, TitanOperationStatus> getVertexEither = titanDao.getVertexById(componentId, JsonParseFlagEnum.NoParse);
1081 if (getVertexEither.isRight()) {
1082 log.debug(COULDNT_FETCH_COMPONENT_WITH_AND_UNIQUE_ID_ERROR, componentId, getVertexEither.right().value());
1083 return Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(getVertexEither.right().value()));
1086 GraphVertex vertex = getVertexEither.left().value();
1087 Map<String, MapPropertiesDataDefinition> instPropsMap = new HashMap<>();
1088 if (instInputs != null) {
1090 MapPropertiesDataDefinition propertiesMap;
1091 for (Entry<String, List<ComponentInstanceInput>> entry : instInputs.entrySet()) {
1092 propertiesMap = new MapPropertiesDataDefinition();
1094 propertiesMap.setMapToscaDataDefinition(entry.getValue().stream().map(PropertyDataDefinition::new).collect(Collectors.toMap(PropertyDataDefinition::getName, e -> e)));
1096 instPropsMap.put(entry.getKey(), propertiesMap);
1100 StorageOperationStatus status = topologyTemplateOperation.associateInstInputsToComponent(vertex, instPropsMap);
1102 if (StorageOperationStatus.OK == status) {
1103 log.debug(COMPONENT_CREATED_SUCCESSFULLY);
1104 return Either.left(instInputs);
1106 return Either.right(status);
1110 public Either<Map<String, List<ComponentInstanceInput>>, StorageOperationStatus> addComponentInstanceInputsToComponent(Component containerComponent, Map<String, List<ComponentInstanceInput>> instProperties) {
1111 requireNonNull(instProperties);
1112 StorageOperationStatus status;
1113 for (Entry<String, List<ComponentInstanceInput>> entry : instProperties.entrySet()) {
1114 List<ComponentInstanceInput> props = entry.getValue();
1115 String componentInstanceId = entry.getKey();
1116 if (!isEmpty(props)) {
1117 for (ComponentInstanceInput property : props) {
1118 List<ComponentInstanceInput> componentInstancesInputs = containerComponent.getComponentInstancesInputs().get(componentInstanceId);
1119 Optional<ComponentInstanceInput> instanceProperty = componentInstancesInputs.stream()
1120 .filter(p -> p.getName().equals(property.getName()))
1122 if (instanceProperty.isPresent()) {
1123 status = updateComponentInstanceInput(containerComponent, componentInstanceId, property);
1125 status = addComponentInstanceInput(containerComponent, componentInstanceId, property);
1127 if (status != StorageOperationStatus.OK) {
1128 log.debug("Failed to update instance input {} for instance {} error {} ", property, componentInstanceId, status);
1129 return Either.right(status);
1131 log.trace("instance input {} for instance {} updated", property, componentInstanceId);
1136 return Either.left(instProperties);
1139 public Either<Map<String, List<ComponentInstanceProperty>>, StorageOperationStatus> addComponentInstancePropertiesToComponent(Component containerComponent, Map<String, List<ComponentInstanceProperty>> instProperties) {
1140 requireNonNull(instProperties);
1141 StorageOperationStatus status;
1142 for (Entry<String, List<ComponentInstanceProperty>> entry : instProperties.entrySet()) {
1143 List<ComponentInstanceProperty> props = entry.getValue();
1144 String componentInstanceId = entry.getKey();
1145 List<ComponentInstanceProperty> instanceProperties = containerComponent.getComponentInstancesProperties().get(componentInstanceId);
1146 if (!isEmpty(props)) {
1147 for (ComponentInstanceProperty property : props) {
1148 Optional<ComponentInstanceProperty> instanceProperty = instanceProperties.stream()
1149 .filter(p -> p.getUniqueId().equals(property.getUniqueId()))
1151 if (instanceProperty.isPresent()) {
1152 status = updateComponentInstanceProperty(containerComponent, componentInstanceId, property);
1154 status = addComponentInstanceProperty(containerComponent, componentInstanceId, property);
1156 if (status != StorageOperationStatus.OK) {
1157 log.debug("Failed to update instance property {} for instance {} error {} ", property, componentInstanceId, status);
1158 return Either.right(status);
1163 return Either.left(instProperties);
1166 public StorageOperationStatus associateDeploymentArtifactsToInstances(Map<String, Map<String, ArtifactDefinition>> instDeploymentArtifacts, String componentId, User user) {
1168 Either<GraphVertex, TitanOperationStatus> getVertexEither = titanDao.getVertexById(componentId, JsonParseFlagEnum.NoParse);
1169 if (getVertexEither.isRight()) {
1170 log.debug(COULDNT_FETCH_COMPONENT_WITH_AND_UNIQUE_ID_ERROR, componentId, getVertexEither.right().value());
1171 return DaoStatusConverter.convertTitanStatusToStorageStatus(getVertexEither.right().value());
1175 GraphVertex vertex = getVertexEither.left().value();
1176 Map<String, MapArtifactDataDefinition> instArtMap = new HashMap<>();
1177 if (instDeploymentArtifacts != null) {
1179 MapArtifactDataDefinition artifactsMap;
1180 for (Entry<String, Map<String, ArtifactDefinition>> entry : instDeploymentArtifacts.entrySet()) {
1181 Map<String, ArtifactDefinition> artList = entry.getValue();
1182 Map<String, ArtifactDataDefinition> artifacts = artList.entrySet().stream().collect(Collectors.toMap(Map.Entry::getKey, e -> new ArtifactDataDefinition(e.getValue())));
1183 artifactsMap = nodeTemplateOperation.prepareInstDeploymentArtifactPerInstance(artifacts, entry.getKey(), user, NodeTemplateOperation.HEAT_VF_ENV_NAME);
1185 instArtMap.put(entry.getKey(), artifactsMap);
1189 return topologyTemplateOperation.associateInstDeploymentArtifactsToComponent(vertex, instArtMap);
1193 public StorageOperationStatus associateArtifactsToInstances(Map<String, Map<String, ArtifactDefinition>> instArtifacts, String componentId) {
1195 Either<GraphVertex, TitanOperationStatus> getVertexEither = titanDao.getVertexById(componentId, JsonParseFlagEnum.NoParse);
1196 if (getVertexEither.isRight()) {
1197 log.debug(COULDNT_FETCH_COMPONENT_WITH_AND_UNIQUE_ID_ERROR, componentId, getVertexEither.right().value());
1198 return DaoStatusConverter.convertTitanStatusToStorageStatus(getVertexEither.right().value());
1202 GraphVertex vertex = getVertexEither.left().value();
1203 Map<String, MapArtifactDataDefinition> instArtMap = new HashMap<>();
1204 if (instArtifacts != null) {
1206 MapArtifactDataDefinition artifactsMap;
1207 for (Entry<String, Map<String, ArtifactDefinition>> entry : instArtifacts.entrySet()) {
1208 Map<String, ArtifactDefinition> artList = entry.getValue();
1209 Map<String, ArtifactDataDefinition> artifacts = artList.entrySet().stream().collect(Collectors.toMap(Map.Entry::getKey, e -> new ArtifactDataDefinition(e.getValue())));
1210 artifactsMap = new MapArtifactDataDefinition(artifacts);
1212 instArtMap.put(entry.getKey(), artifactsMap);
1216 return topologyTemplateOperation.associateInstArtifactsToComponent(vertex, instArtMap);
1220 public StorageOperationStatus associateInstAttributeToComponentToInstances(Map<String, List<PropertyDefinition>> instArttributes, String componentId) {
1222 Either<GraphVertex, TitanOperationStatus> getVertexEither = titanDao.getVertexById(componentId, JsonParseFlagEnum.NoParse);
1223 if (getVertexEither.isRight()) {
1224 log.debug(COULDNT_FETCH_COMPONENT_WITH_AND_UNIQUE_ID_ERROR, componentId, getVertexEither.right().value());
1225 return DaoStatusConverter.convertTitanStatusToStorageStatus(getVertexEither.right().value());
1229 GraphVertex vertex = getVertexEither.left().value();
1230 Map<String, MapPropertiesDataDefinition> instAttr = new HashMap<>();
1231 if (instArttributes != null) {
1233 MapPropertiesDataDefinition attributesMap;
1234 for (Entry<String, List<PropertyDefinition>> entry : instArttributes.entrySet()) {
1235 attributesMap = new MapPropertiesDataDefinition();
1236 attributesMap.setMapToscaDataDefinition(entry.getValue().stream().map(PropertyDataDefinition::new).collect(Collectors.toMap(PropertyDataDefinition::getName, e -> e)));
1237 instAttr.put(entry.getKey(), attributesMap);
1241 return topologyTemplateOperation.associateInstAttributeToComponent(vertex, instAttr);
1246 public StorageOperationStatus associateOrAddCalculatedCapReq(Map<ComponentInstance, Map<String, List<CapabilityDefinition>>> instCapabilties, Map<ComponentInstance, Map<String, List<RequirementDefinition>>> instReg, String componentId) {
1247 Either<GraphVertex, TitanOperationStatus> getVertexEither = titanDao.getVertexById(componentId, JsonParseFlagEnum.NoParse);
1248 if (getVertexEither.isRight()) {
1249 log.debug(COULDNT_FETCH_COMPONENT_WITH_AND_UNIQUE_ID_ERROR, componentId, getVertexEither.right().value());
1250 return DaoStatusConverter.convertTitanStatusToStorageStatus(getVertexEither.right().value());
1254 GraphVertex vertex = getVertexEither.left().value();
1256 Map<String, MapListRequirementDataDefinition> calcRequirements = new HashMap<>();
1258 Map<String, MapListCapabilityDataDefinition> calcCapabilty = new HashMap<>();
1259 Map<String, MapCapabilityProperty> calculatedCapabilitiesProperties = new HashMap<>();
1260 if (instCapabilties != null) {
1261 for (Entry<ComponentInstance, Map<String, List<CapabilityDefinition>>> entry : instCapabilties.entrySet()) {
1263 Map<String, List<CapabilityDefinition>> caps = entry.getValue();
1264 Map<String, ListCapabilityDataDefinition> mapToscaDataDefinition = new HashMap<>();
1265 for (Entry<String, List<CapabilityDefinition>> instCapability : caps.entrySet()) {
1266 mapToscaDataDefinition.put(instCapability.getKey(), new ListCapabilityDataDefinition(instCapability.getValue().stream().map(CapabilityDataDefinition::new).collect(Collectors.toList())));
1269 ComponentInstanceDataDefinition componentInstance = new ComponentInstanceDataDefinition(entry.getKey());
1270 MapListCapabilityDataDefinition capMap = nodeTemplateOperation.prepareCalculatedCapabiltyForNodeType(mapToscaDataDefinition, componentInstance);
1272 MapCapabilityProperty mapCapabilityProperty = ModelConverter.convertToMapOfMapCapabiltyProperties(caps, componentInstance.getUniqueId(), true);
1274 calcCapabilty.put(entry.getKey().getUniqueId(), capMap);
1275 calculatedCapabilitiesProperties.put(entry.getKey().getUniqueId(), mapCapabilityProperty);
1279 if (instReg != null) {
1280 for (Entry<ComponentInstance, Map<String, List<RequirementDefinition>>> entry : instReg.entrySet()) {
1282 Map<String, List<RequirementDefinition>> req = entry.getValue();
1283 Map<String, ListRequirementDataDefinition> mapToscaDataDefinition = new HashMap<>();
1284 for (Entry<String, List<RequirementDefinition>> instReq : req.entrySet()) {
1285 mapToscaDataDefinition.put(instReq.getKey(), new ListRequirementDataDefinition(instReq.getValue().stream().map(RequirementDataDefinition::new).collect(Collectors.toList())));
1288 MapListRequirementDataDefinition capMap = nodeTemplateOperation.prepareCalculatedRequirementForNodeType(mapToscaDataDefinition, new ComponentInstanceDataDefinition(entry.getKey()));
1290 calcRequirements.put(entry.getKey().getUniqueId(), capMap);
1294 return topologyTemplateOperation.associateOrAddCalcCapReqToComponent(vertex, calcRequirements, calcCapabilty, calculatedCapabilitiesProperties);
1297 private Either<List<Service>, StorageOperationStatus> getLatestVersionNonCheckoutServicesMetadataOnly(Map<GraphPropertyEnum, Object> hasProps, Map<GraphPropertyEnum, Object> hasNotProps) {
1298 List<Service> services = new ArrayList<>();
1299 List<LifecycleStateEnum> states = new ArrayList<>();
1301 hasProps.put(GraphPropertyEnum.COMPONENT_TYPE, ComponentTypeEnum.SERVICE.name());
1302 hasProps.put(GraphPropertyEnum.IS_HIGHEST_VERSION, true);
1305 states.add(LifecycleStateEnum.NOT_CERTIFIED_CHECKOUT);
1306 hasNotProps.put(GraphPropertyEnum.STATE, states);
1307 hasNotProps.put(GraphPropertyEnum.IS_DELETED, true);
1308 hasNotProps.put(GraphPropertyEnum.IS_ARCHIVED, true);
1309 return fetchServicesByCriteria(services, hasProps, hasNotProps);
1312 private Either<List<Component>, StorageOperationStatus> getLatestVersionNotAbstractToscaElementsMetadataOnly(boolean isAbstract, ComponentTypeEnum componentTypeEnum, String internalComponentType, VertexTypeEnum vertexType) {
1313 List<Service> services = null;
1314 Map<GraphPropertyEnum, Object> hasProps = new EnumMap<>(GraphPropertyEnum.class);
1315 Map<GraphPropertyEnum, Object> hasNotProps = new EnumMap<>(GraphPropertyEnum.class);
1316 fillPropsMap(hasProps, hasNotProps, internalComponentType, componentTypeEnum, isAbstract, vertexType);
1317 Either<List<GraphVertex>, TitanOperationStatus> getRes = titanDao.getByCriteria(vertexType, hasProps, hasNotProps, JsonParseFlagEnum.ParseMetadata);
1318 if (getRes.isRight()) {
1319 if (getRes.right().value().equals(TitanOperationStatus.NOT_FOUND)) {
1320 return Either.left(new ArrayList<>());
1322 return Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(getRes.right().value()));
1325 // region -> Fetch non checked-out services
1326 if (internalComponentType != null && internalComponentType.toLowerCase().trim().equals(SERVICE) && VertexTypeEnum.NODE_TYPE == vertexType) {
1327 Either<List<Service>, StorageOperationStatus> result = getLatestVersionNonCheckoutServicesMetadataOnly(new EnumMap<>(GraphPropertyEnum.class), new EnumMap<>(GraphPropertyEnum.class));
1328 if (result.isRight()) {
1329 log.debug("Failed to fetch services for");
1330 return Either.right(result.right().value());
1332 services = result.left().value();
1333 if (log.isTraceEnabled() && isEmpty(services))
1334 log.trace("No relevant services available");
1337 List<Component> nonAbstractLatestComponents = new ArrayList<>();
1338 ComponentParametersView params = new ComponentParametersView(true);
1339 params.setIgnoreAllVersions(false);
1340 for (GraphVertex vertexComponent : getRes.left().value()) {
1341 Either<ToscaElement, StorageOperationStatus> componentRes = topologyTemplateOperation.getLightComponent(vertexComponent, componentTypeEnum, params);
1342 if (componentRes.isRight()) {
1343 log.debug("Failed to fetch light element for {} error {}", vertexComponent.getUniqueId(), componentRes.right().value());
1344 return Either.right(componentRes.right().value());
1346 Component component = ModelConverter.convertFromToscaElement(componentRes.left().value());
1347 nonAbstractLatestComponents.add(component);
1350 if (CollectionUtils.isNotEmpty(services)) {
1351 nonAbstractLatestComponents.addAll(services);
1353 return Either.left(nonAbstractLatestComponents);
1356 public Either<ComponentMetadataData, StorageOperationStatus> getLatestComponentMetadataByUuid(String componentUuid, JsonParseFlagEnum parseFlag, Boolean isHighest) {
1358 Either<ComponentMetadataData, StorageOperationStatus> result;
1359 Map<GraphPropertyEnum, Object> hasProperties = new EnumMap<>(GraphPropertyEnum.class);
1360 hasProperties.put(GraphPropertyEnum.UUID, componentUuid);
1361 if (isHighest != null) {
1362 hasProperties.put(GraphPropertyEnum.IS_HIGHEST_VERSION, isHighest);
1364 Map<GraphPropertyEnum, Object> propertiesNotToMatch = new EnumMap<>(GraphPropertyEnum.class);
1365 propertiesNotToMatch.put(GraphPropertyEnum.IS_DELETED, true);
1366 propertiesNotToMatch.put(GraphPropertyEnum.IS_ARCHIVED, true); //US382674, US382683
1368 Either<List<GraphVertex>, TitanOperationStatus> getRes = titanDao.getByCriteria(null, hasProperties, propertiesNotToMatch, parseFlag);
1369 if (getRes.isRight()) {
1370 result = Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(getRes.right().value()));
1372 List<ComponentMetadataData> latestVersionList = getRes.left().value().stream().map(ModelConverter::convertToComponentMetadata).collect(Collectors.toList());
1373 ComponentMetadataData latestVersion = latestVersionList.size() == 1 ? latestVersionList.get(0)
1374 : latestVersionList.stream().max((c1, c2) -> Double.compare(Double.parseDouble(c1.getMetadataDataDefinition().getVersion()), Double.parseDouble(c2.getMetadataDataDefinition().getVersion()))).get();
1375 result = Either.left(latestVersion);
1380 public Either<ComponentMetadataData, StorageOperationStatus> getComponentMetadata(String componentId) {
1381 Either<ComponentMetadataData, StorageOperationStatus> result;
1382 Either<GraphVertex, TitanOperationStatus> getRes = titanDao.getVertexById(componentId, JsonParseFlagEnum.ParseMetadata);
1383 if (getRes.isRight()) {
1384 result = Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(getRes.right().value()));
1386 ComponentMetadataData componentMetadata = ModelConverter.convertToComponentMetadata(getRes.left().value());
1387 result = Either.left(componentMetadata);
1392 public Either<List<Component>, StorageOperationStatus> getLatestVersionNotAbstractComponents(boolean isAbstract, ComponentTypeEnum componentTypeEnum,
1393 String internalComponentType, List<String> componentUids) {
1395 List<Component> components = new ArrayList<>();
1396 if (componentUids == null) {
1397 Either<List<String>, StorageOperationStatus> componentUidsRes = getComponentUids(isAbstract, componentTypeEnum, internalComponentType);
1398 if (componentUidsRes.isRight()) {
1399 return Either.right(componentUidsRes.right().value());
1401 componentUids = componentUidsRes.left().value();
1403 if (!isEmpty(componentUids)) {
1404 for (String componentUid : componentUids) {
1405 ComponentParametersView componentParametersView = buildComponentViewForNotAbstract();
1406 if ("vl".equalsIgnoreCase(internalComponentType)) {
1407 componentParametersView.setIgnoreCapabilities(false);
1408 componentParametersView.setIgnoreRequirements(false);
1410 Either<ToscaElement, StorageOperationStatus> getToscaElementRes = nodeTemplateOperation.getToscaElementOperation(componentTypeEnum).getLightComponent(componentUid, componentTypeEnum, componentParametersView);
1411 if (getToscaElementRes.isRight()) {
1412 log.debug("Failed to fetch resource for error is {}", getToscaElementRes.right().value());
1413 return Either.right(getToscaElementRes.right().value());
1415 Component component = ModelConverter.convertFromToscaElement(getToscaElementRes.left().value());
1416 nullifySomeComponentProperties(component);
1417 components.add(component);
1420 return Either.left(components);
1423 public void nullifySomeComponentProperties(Component component) {
1424 component.setContactId(null);
1425 component.setCreationDate(null);
1426 component.setCreatorUserId(null);
1427 component.setCreatorFullName(null);
1428 component.setLastUpdateDate(null);
1429 component.setLastUpdaterUserId(null);
1430 component.setLastUpdaterFullName(null);
1431 component.setNormalizedName(null);
1434 private Either<List<String>, StorageOperationStatus> getComponentUids(boolean isAbstract, ComponentTypeEnum componentTypeEnum, String internalComponentType) {
1436 Either<List<Component>, StorageOperationStatus> getToscaElementsRes = getLatestVersionNotAbstractMetadataOnly(isAbstract, componentTypeEnum, internalComponentType);
1437 if (getToscaElementsRes.isRight()) {
1438 return Either.right(getToscaElementsRes.right().value());
1440 List<Component> collection = getToscaElementsRes.left().value();
1441 List<String> componentUids;
1442 if (collection == null) {
1443 componentUids = new ArrayList<>();
1445 componentUids = collection.stream()
1446 .map(Component::getUniqueId)
1447 .collect(Collectors.toList());
1449 return Either.left(componentUids);
1452 private ComponentParametersView buildComponentViewForNotAbstract() {
1453 ComponentParametersView componentParametersView = new ComponentParametersView();
1454 componentParametersView.disableAll();
1455 componentParametersView.setIgnoreCategories(false);
1456 componentParametersView.setIgnoreAllVersions(false);
1457 return componentParametersView;
1460 public Either<Boolean, StorageOperationStatus> validateComponentNameExists(String name, ResourceTypeEnum resourceType, ComponentTypeEnum componentType) {
1461 Either<Boolean, StorageOperationStatus> result = validateComponentNameUniqueness(name, resourceType, componentType);
1462 if (result.isLeft()) {
1463 result = Either.left(!result.left().value());
1468 public Either<Boolean, StorageOperationStatus> validateComponentNameUniqueness(String name, ResourceTypeEnum resourceType, ComponentTypeEnum componentType) {
1469 VertexTypeEnum vertexType = ModelConverter.isAtomicComponent(resourceType) ? VertexTypeEnum.NODE_TYPE : VertexTypeEnum.TOPOLOGY_TEMPLATE;
1470 String normalizedName = ValidationUtils.normaliseComponentName(name);
1471 Map<GraphPropertyEnum, Object> properties = new EnumMap<>(GraphPropertyEnum.class);
1472 properties.put(GraphPropertyEnum.NORMALIZED_NAME, normalizedName);
1473 properties.put(GraphPropertyEnum.COMPONENT_TYPE, componentType.name());
1475 Either<List<GraphVertex>, TitanOperationStatus> vertexEither = titanDao.getByCriteria(vertexType, properties, JsonParseFlagEnum.NoParse);
1476 if (vertexEither.isRight() && vertexEither.right().value() != TitanOperationStatus.NOT_FOUND) {
1477 log.debug("failed to get vertex from graph with property normalizedName: {}", normalizedName);
1478 return Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(vertexEither.right().value()));
1480 List<GraphVertex> vertexList = vertexEither.isLeft() ? vertexEither.left().value() : null;
1481 if (vertexList != null && !vertexList.isEmpty()) {
1482 return Either.left(false);
1484 return Either.left(true);
1488 private void fillNodeTypePropsMap(Map<GraphPropertyEnum, Object> hasProps, Map<GraphPropertyEnum, Object> hasNotProps, String internalComponentType) {
1489 switch (internalComponentType.toLowerCase()) {
1492 hasNotProps.put(GraphPropertyEnum.RESOURCE_TYPE, Arrays.asList(ResourceTypeEnum.VFCMT.name(), ResourceTypeEnum.Configuration.name()));
1497 hasNotProps.put(GraphPropertyEnum.RESOURCE_TYPE, Arrays.asList(ResourceTypeEnum.VFC.name(), ResourceTypeEnum.VFCMT.name()));
1500 hasProps.put(GraphPropertyEnum.RESOURCE_TYPE, ResourceTypeEnum.VL.name());
1507 private void fillTopologyTemplatePropsMap(Map<GraphPropertyEnum, Object> hasProps, Map<GraphPropertyEnum, Object> hasNotProps, ComponentTypeEnum componentTypeEnum) {
1508 switch (componentTypeEnum) {
1510 hasProps.put(GraphPropertyEnum.COMPONENT_TYPE, ComponentTypeEnum.RESOURCE.name());
1513 hasProps.put(GraphPropertyEnum.COMPONENT_TYPE, ComponentTypeEnum.SERVICE.name());
1518 hasNotProps.put(GraphPropertyEnum.RESOURCE_TYPE, ResourceTypeEnum.CVFC.name());
1521 private void fillPropsMap(Map<GraphPropertyEnum, Object> hasProps, Map<GraphPropertyEnum, Object> hasNotProps, String internalComponentType, ComponentTypeEnum componentTypeEnum, boolean isAbstract, VertexTypeEnum internalVertexType) {
1522 hasNotProps.put(GraphPropertyEnum.STATE, LifecycleStateEnum.NOT_CERTIFIED_CHECKOUT.name());
1524 hasNotProps.put(GraphPropertyEnum.IS_DELETED, true);
1525 hasNotProps.put(GraphPropertyEnum.IS_ARCHIVED, true);
1526 hasProps.put(GraphPropertyEnum.IS_HIGHEST_VERSION, true);
1527 if (VertexTypeEnum.NODE_TYPE == internalVertexType) {
1528 hasProps.put(GraphPropertyEnum.IS_ABSTRACT, isAbstract);
1529 if (internalComponentType != null) {
1530 fillNodeTypePropsMap(hasProps, hasNotProps, internalComponentType);
1533 fillTopologyTemplatePropsMap(hasProps, hasNotProps, componentTypeEnum);
1537 private List<VertexTypeEnum> getInternalVertexTypes(ComponentTypeEnum componentTypeEnum, String internalComponentType) {
1538 List<VertexTypeEnum> internalVertexTypes = new ArrayList<>();
1539 if (ComponentTypeEnum.RESOURCE == componentTypeEnum) {
1540 internalVertexTypes.add(VertexTypeEnum.NODE_TYPE);
1542 if (ComponentTypeEnum.SERVICE == componentTypeEnum || SERVICE.equalsIgnoreCase(internalComponentType)) {
1543 internalVertexTypes.add(VertexTypeEnum.TOPOLOGY_TEMPLATE);
1545 return internalVertexTypes;
1548 public Either<List<Component>, StorageOperationStatus> getLatestVersionNotAbstractMetadataOnly(boolean isAbstract, ComponentTypeEnum componentTypeEnum, String internalComponentType) {
1549 List<VertexTypeEnum> internalVertexTypes = getInternalVertexTypes(componentTypeEnum, internalComponentType);
1550 List<Component> result = new ArrayList<>();
1551 for (VertexTypeEnum vertexType : internalVertexTypes) {
1552 Either<List<Component>, StorageOperationStatus> listByVertexType = getLatestVersionNotAbstractToscaElementsMetadataOnly(isAbstract, componentTypeEnum, internalComponentType, vertexType);
1553 if (listByVertexType.isRight()) {
1554 return listByVertexType;
1556 result.addAll(listByVertexType.left().value());
1558 return Either.left(result);
1562 private Either<List<Component>, StorageOperationStatus> getLatestComponentListByUuid(String componentUuid, Map<GraphPropertyEnum, Object> additionalPropertiesToMatch) {
1563 Map<GraphPropertyEnum, Object> propertiesToMatch = new EnumMap<>(GraphPropertyEnum.class);
1564 if (additionalPropertiesToMatch != null) {
1565 propertiesToMatch.putAll(additionalPropertiesToMatch);
1567 propertiesToMatch.put(GraphPropertyEnum.IS_HIGHEST_VERSION, true);
1568 return getComponentListByUuid(componentUuid, propertiesToMatch);
1571 public Either<Component, StorageOperationStatus> getComponentByUuidAndVersion(String componentUuid, String version) {
1572 Map<GraphPropertyEnum, Object> propertiesToMatch = new EnumMap<>(GraphPropertyEnum.class);
1574 propertiesToMatch.put(GraphPropertyEnum.UUID, componentUuid);
1575 propertiesToMatch.put(GraphPropertyEnum.VERSION, version);
1577 Map<GraphPropertyEnum, Object> propertiesNotToMatch = new EnumMap<>(GraphPropertyEnum.class);
1578 propertiesNotToMatch.put(GraphPropertyEnum.IS_DELETED, true);
1579 Either<List<GraphVertex>, TitanOperationStatus> vertexEither = titanDao.getByCriteria(null, propertiesToMatch, propertiesNotToMatch, JsonParseFlagEnum.ParseAll);
1580 if (vertexEither.isRight()) {
1581 return Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(vertexEither.right().value()));
1584 List<GraphVertex> vertexList = vertexEither.isLeft() ? vertexEither.left().value() : null;
1585 if (vertexList == null || vertexList.isEmpty() || vertexList.size() > 1) {
1586 return Either.right(StorageOperationStatus.NOT_FOUND);
1589 return getToscaElementByOperation(vertexList.get(0));
1592 public Either<List<Component>, StorageOperationStatus> getComponentListByUuid(String componentUuid, Map<GraphPropertyEnum, Object> additionalPropertiesToMatch) {
1594 Map<GraphPropertyEnum, Object> propertiesToMatch = new EnumMap<>(GraphPropertyEnum.class);
1596 if (additionalPropertiesToMatch != null) {
1597 propertiesToMatch.putAll(additionalPropertiesToMatch);
1600 propertiesToMatch.put(GraphPropertyEnum.UUID, componentUuid);
1602 Map<GraphPropertyEnum, Object> propertiesNotToMatch = new EnumMap<>(GraphPropertyEnum.class);
1603 propertiesNotToMatch.put(GraphPropertyEnum.IS_DELETED, true);
1604 propertiesNotToMatch.put(GraphPropertyEnum.IS_ARCHIVED, true); //US382674, US382683
1606 Either<List<GraphVertex>, TitanOperationStatus> vertexEither = titanDao.getByCriteria(null, propertiesToMatch, propertiesNotToMatch, JsonParseFlagEnum.ParseAll);
1608 if (vertexEither.isRight()) {
1609 log.debug("Couldn't fetch metadata for component with uuid {}, error: {}", componentUuid, vertexEither.right().value());
1610 return Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(vertexEither.right().value()));
1612 List<GraphVertex> vertexList = vertexEither.isLeft() ? vertexEither.left().value() : null;
1614 if (vertexList == null || vertexList.isEmpty()) {
1615 log.debug("Component with uuid {} was not found", componentUuid);
1616 return Either.right(StorageOperationStatus.NOT_FOUND);
1619 ArrayList<Component> latestComponents = new ArrayList<>();
1620 for (GraphVertex vertex : vertexList) {
1621 Either<Component, StorageOperationStatus> toscaElementByOperation = getToscaElementByOperation(vertex);
1623 if (toscaElementByOperation.isRight()) {
1624 log.debug("Could not fetch the following Component by UUID {}", vertex.getUniqueId());
1625 return Either.right(toscaElementByOperation.right().value());
1628 latestComponents.add(toscaElementByOperation.left().value());
1631 if (latestComponents.size() > 1) {
1632 for (Component component : latestComponents) {
1633 if (component.isHighestVersion()) {
1634 LinkedList<Component> highestComponent = new LinkedList<>();
1635 highestComponent.add(component);
1636 return Either.left(highestComponent);
1641 return Either.left(latestComponents);
1644 public Either<Component, StorageOperationStatus> getLatestServiceByUuid(String serviceUuid) {
1645 Map<GraphPropertyEnum, Object> propertiesToMatch = new EnumMap<>(GraphPropertyEnum.class);
1646 propertiesToMatch.put(GraphPropertyEnum.COMPONENT_TYPE, ComponentTypeEnum.SERVICE.name());
1647 return getLatestComponentByUuid(serviceUuid, propertiesToMatch);
1650 public Either<Component, StorageOperationStatus> getLatestComponentByUuid(String componentUuid) {
1651 return getLatestComponentByUuid(componentUuid, null);
1654 public Either<Component, StorageOperationStatus> getLatestComponentByUuid(String componentUuid, Map<GraphPropertyEnum, Object> propertiesToMatch) {
1656 Either<List<Component>, StorageOperationStatus> latestVersionListEither = getLatestComponentListByUuid(componentUuid, propertiesToMatch);
1658 if (latestVersionListEither.isRight()) {
1659 return Either.right(latestVersionListEither.right().value());
1662 List<Component> latestVersionList = latestVersionListEither.left().value();
1664 if (latestVersionList.isEmpty()) {
1665 return Either.right(StorageOperationStatus.NOT_FOUND);
1667 Component component = latestVersionList.size() == 1 ? latestVersionList.get(0) : latestVersionList.stream().max((c1, c2) -> Double.compare(Double.parseDouble(c1.getVersion()), Double.parseDouble(c2.getVersion()))).get();
1669 return Either.left(component);
1672 public Either<List<Resource>, StorageOperationStatus> getAllCertifiedResources(boolean isAbstract, Boolean isHighest) {
1674 List<Resource> resources = new ArrayList<>();
1675 Map<GraphPropertyEnum, Object> propertiesToMatch = new EnumMap<>(GraphPropertyEnum.class);
1676 Map<GraphPropertyEnum, Object> propertiesNotToMatch = new EnumMap<>(GraphPropertyEnum.class);
1678 propertiesToMatch.put(GraphPropertyEnum.IS_ABSTRACT, isAbstract);
1679 if (isHighest != null) {
1680 propertiesToMatch.put(GraphPropertyEnum.IS_HIGHEST_VERSION, isHighest);
1682 propertiesToMatch.put(GraphPropertyEnum.STATE, LifecycleStateEnum.CERTIFIED.name());
1683 propertiesToMatch.put(GraphPropertyEnum.COMPONENT_TYPE, ComponentTypeEnum.RESOURCE.name());
1684 propertiesNotToMatch.put(GraphPropertyEnum.IS_DELETED, true);
1686 Either<List<GraphVertex>, TitanOperationStatus> getResourcesRes = titanDao.getByCriteria(null, propertiesToMatch, propertiesNotToMatch, JsonParseFlagEnum.ParseAll);
1688 if (getResourcesRes.isRight()) {
1689 log.debug("Failed to fetch all certified resources. Status is {}", getResourcesRes.right().value());
1690 return Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(getResourcesRes.right().value()));
1692 List<GraphVertex> resourceVerticies = getResourcesRes.left().value();
1693 for (GraphVertex resourceV : resourceVerticies) {
1694 Either<Resource, StorageOperationStatus> getResourceRes = getToscaElement(resourceV);
1695 if (getResourceRes.isRight()) {
1696 return Either.right(getResourceRes.right().value());
1698 resources.add(getResourceRes.left().value());
1700 return Either.left(resources);
1703 public <T extends Component> Either<T, StorageOperationStatus> getLatestByNameAndVersion(String name, String version, JsonParseFlagEnum parseFlag) {
1704 Either<T, StorageOperationStatus> result;
1706 Map<GraphPropertyEnum, Object> hasProperties = new EnumMap<>(GraphPropertyEnum.class);
1707 Map<GraphPropertyEnum, Object> hasNotProperties = new EnumMap<>(GraphPropertyEnum.class);
1709 hasProperties.put(GraphPropertyEnum.NAME, name);
1710 hasProperties.put(GraphPropertyEnum.VERSION, version);
1711 hasProperties.put(GraphPropertyEnum.IS_HIGHEST_VERSION, true);
1713 hasNotProperties.put(GraphPropertyEnum.IS_DELETED, true);
1715 Either<List<GraphVertex>, TitanOperationStatus> getResourceRes = titanDao.getByCriteria(null, hasProperties, hasNotProperties, parseFlag);
1716 if (getResourceRes.isRight()) {
1717 TitanOperationStatus status = getResourceRes.right().value();
1718 log.debug("failed to find resource with name {}, version {}. Status is {} ", name, version, status);
1719 result = Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(status));
1722 return getToscaElementByOperation(getResourceRes.left().value().get(0));
1725 public Either<Resource, StorageOperationStatus> getLatestComponentByCsarOrName(ComponentTypeEnum componentType, String csarUUID, String systemName) {
1726 return getLatestComponentByCsarOrName(componentType, csarUUID, systemName, JsonParseFlagEnum.ParseAll);
1729 public Either<Resource, StorageOperationStatus> getLatestComponentByCsarOrName(ComponentTypeEnum componentType, String csarUUID, String systemName, JsonParseFlagEnum parseFlag) {
1730 Map<GraphPropertyEnum, Object> props = new EnumMap<>(GraphPropertyEnum.class);
1731 Map<GraphPropertyEnum, Object> propsHasNot = new EnumMap<>(GraphPropertyEnum.class);
1732 props.put(GraphPropertyEnum.CSAR_UUID, csarUUID);
1733 props.put(GraphPropertyEnum.IS_HIGHEST_VERSION, true);
1734 if (componentType != null) {
1735 props.put(GraphPropertyEnum.COMPONENT_TYPE, componentType.name());
1737 propsHasNot.put(GraphPropertyEnum.IS_DELETED, true);
1739 GraphVertex resourceMetadataData = null;
1740 List<GraphVertex> resourceMetadataDataList = null;
1741 Either<List<GraphVertex>, TitanOperationStatus> byCsar = titanDao.getByCriteria(null, props, propsHasNot, JsonParseFlagEnum.ParseMetadata);
1742 if (byCsar.isRight()) {
1743 if (TitanOperationStatus.NOT_FOUND == byCsar.right().value()) {
1744 // Fix Defect DE256036
1745 if (StringUtils.isEmpty(systemName)) {
1746 return Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(TitanOperationStatus.NOT_FOUND));
1750 props.put(GraphPropertyEnum.IS_HIGHEST_VERSION, true);
1751 props.put(GraphPropertyEnum.SYSTEM_NAME, systemName);
1752 Either<List<GraphVertex>, TitanOperationStatus> bySystemname = titanDao.getByCriteria(null, props, JsonParseFlagEnum.ParseMetadata);
1753 if (bySystemname.isRight()) {
1754 log.debug("getLatestResourceByCsarOrName - Failed to find by system name {} error {} ", systemName, bySystemname.right().value());
1755 return Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(bySystemname.right().value()));
1757 if (bySystemname.left().value().size() > 2) {
1758 log.debug("getLatestResourceByCsarOrName - getByCriteria(by system name) must return only 2 latest version, but was returned - {}", bySystemname.left().value().size());
1759 return Either.right(StorageOperationStatus.GENERAL_ERROR);
1761 resourceMetadataDataList = bySystemname.left().value();
1762 if (resourceMetadataDataList.size() == 1) {
1763 resourceMetadataData = resourceMetadataDataList.get(0);
1765 for (GraphVertex curResource : resourceMetadataDataList) {
1766 if (!((String) curResource.getJsonMetadataField(JsonPresentationFields.LIFECYCLE_STATE)).equals("CERTIFIED")) {
1767 resourceMetadataData = curResource;
1772 if (resourceMetadataData == null) {
1773 log.debug("getLatestResourceByCsarOrName - getByCriteria(by system name) returned 2 latest CERTIFIED versions");
1774 return Either.right(StorageOperationStatus.GENERAL_ERROR);
1776 if (resourceMetadataData.getJsonMetadataField(JsonPresentationFields.CSAR_UUID) != null && !((String) resourceMetadataData.getJsonMetadataField(JsonPresentationFields.CSAR_UUID)).equals(csarUUID)) {
1777 log.debug("getLatestResourceByCsarOrName - same system name {} but different csarUUID. exist {} and new {} ", systemName, resourceMetadataData.getJsonMetadataField(JsonPresentationFields.CSAR_UUID), csarUUID);
1778 // correct error will be returned from create flow. with all
1779 // correct audit records!!!!!
1780 return Either.right(StorageOperationStatus.NOT_FOUND);
1782 return getToscaElement((String) resourceMetadataData.getUniqueId());
1785 resourceMetadataDataList = byCsar.left().value();
1786 if (resourceMetadataDataList.size() > 2) {
1787 log.debug("getLatestResourceByCsarOrName - getByCriteria(by csar) must return only 2 latest version, but was returned - {}", byCsar.left().value().size());
1788 return Either.right(StorageOperationStatus.GENERAL_ERROR);
1790 if (resourceMetadataDataList.size() == 1) {
1791 resourceMetadataData = resourceMetadataDataList.get(0);
1793 for (GraphVertex curResource : resourceMetadataDataList) {
1794 if (!((String) curResource.getJsonMetadataField(JsonPresentationFields.LIFECYCLE_STATE)).equals("CERTIFIED")) {
1795 resourceMetadataData = curResource;
1800 if (resourceMetadataData == null) {
1801 log.debug("getLatestResourceByCsarOrName - getByCriteria(by csar) returned 2 latest CERTIFIED versions");
1802 return Either.right(StorageOperationStatus.GENERAL_ERROR);
1804 return getToscaElement((String) resourceMetadataData.getJsonMetadataField(JsonPresentationFields.UNIQUE_ID), parseFlag);
1809 public Either<Boolean, StorageOperationStatus> validateToscaResourceNameExtends(String templateNameCurrent, String templateNameExtends) {
1811 String currentTemplateNameChecked = templateNameExtends;
1813 while (currentTemplateNameChecked != null && !currentTemplateNameChecked.equalsIgnoreCase(templateNameCurrent)) {
1814 Either<Resource, StorageOperationStatus> latestByToscaResourceName = getLatestByToscaResourceName(currentTemplateNameChecked);
1816 if (latestByToscaResourceName.isRight()) {
1817 return latestByToscaResourceName.right().value() == StorageOperationStatus.NOT_FOUND ? Either.left(false) : Either.right(latestByToscaResourceName.right().value());
1820 Resource value = latestByToscaResourceName.left().value();
1822 if (value.getDerivedFrom() != null) {
1823 currentTemplateNameChecked = value.getDerivedFrom().get(0);
1825 currentTemplateNameChecked = null;
1829 return (currentTemplateNameChecked != null && currentTemplateNameChecked.equalsIgnoreCase(templateNameCurrent)) ? Either.left(true) : Either.left(false);
1832 public Either<List<Component>, StorageOperationStatus> fetchMetaDataByResourceType(String resourceType, ComponentParametersView filterBy) {
1833 Map<GraphPropertyEnum, Object> props = new EnumMap<>(GraphPropertyEnum.class);
1834 props.put(GraphPropertyEnum.RESOURCE_TYPE, resourceType);
1835 props.put(GraphPropertyEnum.IS_HIGHEST_VERSION, true);
1836 Map<GraphPropertyEnum, Object> propsHasNotToMatch = new EnumMap<>(GraphPropertyEnum.class);
1837 propsHasNotToMatch.put(GraphPropertyEnum.IS_DELETED, true);
1838 Either<List<GraphVertex>, TitanOperationStatus> resourcesByTypeEither = titanDao.getByCriteria(null, props, propsHasNotToMatch, JsonParseFlagEnum.ParseMetadata);
1840 if (resourcesByTypeEither.isRight()) {
1841 return Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(resourcesByTypeEither.right().value()));
1844 List<GraphVertex> vertexList = resourcesByTypeEither.left().value();
1845 List<Component> components = new ArrayList<>();
1847 for (GraphVertex vertex : vertexList) {
1848 components.add(getToscaElementByOperation(vertex, filterBy).left().value());
1851 return Either.left(components);
1854 public void commit() {
1858 public Either<Service, StorageOperationStatus> updateDistributionStatus(Service service, User user, DistributionStatusEnum distributionStatus) {
1859 Either<GraphVertex, StorageOperationStatus> updateDistributionStatus = topologyTemplateOperation.updateDistributionStatus(service.getUniqueId(), user, distributionStatus);
1860 if (updateDistributionStatus.isRight()) {
1861 return Either.right(updateDistributionStatus.right().value());
1863 GraphVertex serviceV = updateDistributionStatus.left().value();
1864 service.setDistributionStatus(distributionStatus);
1865 service.setLastUpdateDate((Long) serviceV.getJsonMetadataField(JsonPresentationFields.LAST_UPDATE_DATE));
1866 return Either.left(service);
1869 public Either<ComponentMetadataData, StorageOperationStatus> updateComponentLastUpdateDateOnGraph(Component component) {
1871 Either<ComponentMetadataData, StorageOperationStatus> result = null;
1872 GraphVertex serviceVertex;
1873 Either<GraphVertex, TitanOperationStatus> updateRes = null;
1874 Either<GraphVertex, TitanOperationStatus> getRes = titanDao.getVertexById(component.getUniqueId(), JsonParseFlagEnum.ParseMetadata);
1875 if (getRes.isRight()) {
1876 TitanOperationStatus status = getRes.right().value();
1877 log.error("Failed to fetch component {}. status is {}", component.getUniqueId(), status);
1878 result = Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(status));
1880 if (result == null) {
1881 serviceVertex = getRes.left().value();
1882 long lastUpdateDate = System.currentTimeMillis();
1883 serviceVertex.setJsonMetadataField(JsonPresentationFields.LAST_UPDATE_DATE, lastUpdateDate);
1884 component.setLastUpdateDate(lastUpdateDate);
1885 updateRes = titanDao.updateVertex(serviceVertex);
1886 if (updateRes.isRight()) {
1887 result = Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(updateRes.right().value()));
1890 if (result == null) {
1891 result = Either.left(ModelConverter.convertToComponentMetadata(updateRes.left().value()));
1896 public TitanDao getTitanDao() {
1900 public Either<List<Service>, StorageOperationStatus> getCertifiedServicesWithDistStatus(Set<DistributionStatusEnum> distStatus) {
1901 Map<GraphPropertyEnum, Object> propertiesToMatch = new EnumMap<>(GraphPropertyEnum.class);
1902 propertiesToMatch.put(GraphPropertyEnum.STATE, LifecycleStateEnum.CERTIFIED.name());
1904 return getServicesWithDistStatus(distStatus, propertiesToMatch);
1907 public Either<List<Service>, StorageOperationStatus> getServicesWithDistStatus(Set<DistributionStatusEnum> distStatus, Map<GraphPropertyEnum, Object> additionalPropertiesToMatch) {
1909 List<Service> servicesAll = new ArrayList<>();
1911 Map<GraphPropertyEnum, Object> propertiesToMatch = new EnumMap<>(GraphPropertyEnum.class);
1912 Map<GraphPropertyEnum, Object> propertiesNotToMatch = new EnumMap<>(GraphPropertyEnum.class);
1914 if (additionalPropertiesToMatch != null && !additionalPropertiesToMatch.isEmpty()) {
1915 propertiesToMatch.putAll(additionalPropertiesToMatch);
1918 propertiesToMatch.put(GraphPropertyEnum.COMPONENT_TYPE, ComponentTypeEnum.SERVICE.name());
1920 propertiesNotToMatch.put(GraphPropertyEnum.IS_DELETED, true);
1922 if (distStatus != null && !distStatus.isEmpty()) {
1923 for (DistributionStatusEnum state : distStatus) {
1924 propertiesToMatch.put(GraphPropertyEnum.DISTRIBUTION_STATUS, state.name());
1925 Either<List<Service>, StorageOperationStatus> fetchServicesByCriteria = fetchServicesByCriteria(servicesAll, propertiesToMatch, propertiesNotToMatch);
1926 if (fetchServicesByCriteria.isRight()) {
1927 return fetchServicesByCriteria;
1929 servicesAll = fetchServicesByCriteria.left().value();
1932 return Either.left(servicesAll);
1934 return fetchServicesByCriteria(servicesAll, propertiesToMatch, propertiesNotToMatch);
1938 private Either<List<Service>, StorageOperationStatus> fetchServicesByCriteria(List<Service> servicesAll, Map<GraphPropertyEnum, Object> propertiesToMatch, Map<GraphPropertyEnum, Object> propertiesNotToMatch) {
1939 Either<List<GraphVertex>, TitanOperationStatus> getRes = titanDao.getByCriteria(VertexTypeEnum.TOPOLOGY_TEMPLATE, propertiesToMatch, propertiesNotToMatch, JsonParseFlagEnum.ParseAll);
1940 if (getRes.isRight()) {
1941 if (getRes.right().value() != TitanOperationStatus.NOT_FOUND) {
1942 CommonUtility.addRecordToLog(log, LogLevelEnum.DEBUG, "Failed to fetch certified services by match properties {} not match properties {} . Status is {}. ", propertiesToMatch, propertiesNotToMatch, getRes.right().value());
1943 return Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(getRes.right().value()));
1946 for (GraphVertex vertex : getRes.left().value()) {
1947 Either<ToscaElement, StorageOperationStatus> getServiceRes = topologyTemplateOperation.getLightComponent(vertex, ComponentTypeEnum.SERVICE, new ComponentParametersView(true));
1949 if (getServiceRes.isRight()) {
1950 CommonUtility.addRecordToLog(log, LogLevelEnum.DEBUG, "Failed to fetch certified service {}. Status is {}. ", vertex.getJsonMetadataField(JsonPresentationFields.NAME), getServiceRes.right().value());
1951 return Either.right(getServiceRes.right().value());
1953 servicesAll.add(ModelConverter.convertFromToscaElement(getServiceRes.left().value()));
1957 return Either.left(servicesAll);
1960 public void rollback() {
1961 titanDao.rollback();
1964 public StorageOperationStatus addDeploymentArtifactsToInstance(String componentId, ComponentInstance componentInstance, Map<String, ArtifactDefinition> finalDeploymentArtifacts) {
1965 Map<String, ArtifactDataDefinition> instDeplArtifacts = finalDeploymentArtifacts.entrySet().stream().collect(Collectors.toMap(Map.Entry::getKey, e -> new ArtifactDataDefinition(e.getValue())));
1967 return nodeTemplateOperation.addDeploymentArtifactsToInstance(componentId, componentInstance.getUniqueId(), instDeplArtifacts);
1970 public StorageOperationStatus addInformationalArtifactsToInstance(String componentId, ComponentInstance componentInstance, Map<String, ArtifactDefinition> artifacts) {
1971 StorageOperationStatus status = StorageOperationStatus.OK;
1972 if (MapUtils.isNotEmpty(artifacts)) {
1973 Map<String, ArtifactDataDefinition> instDeplArtifacts = artifacts.entrySet().stream().collect(Collectors.toMap(Map.Entry::getKey, e -> new ArtifactDataDefinition(e.getValue())));
1974 status = nodeTemplateOperation.addInformationalArtifactsToInstance(componentId, componentInstance.getUniqueId(), instDeplArtifacts);
1979 public StorageOperationStatus generateCustomizationUUIDOnInstance(String componentId, String instanceId) {
1980 return nodeTemplateOperation.generateCustomizationUUIDOnInstance(componentId, instanceId);
1983 public StorageOperationStatus generateCustomizationUUIDOnInstanceGroup(String componentId, String instanceId, List<String> groupInstances) {
1984 return nodeTemplateOperation.generateCustomizationUUIDOnInstanceGroup(componentId, instanceId, groupInstances);
1988 * adds property to a resource
1989 * @warn this method has SIDE EFFECT on ownerId ,use it with caution
1991 public Either<PropertyDefinition, StorageOperationStatus> addPropertyToResource(String propertyName, PropertyDefinition newPropertyDefinition, Resource resource) {
1993 Either<PropertyDefinition, StorageOperationStatus> result = null;
1994 Either<Component, StorageOperationStatus> getUpdatedComponentRes = null;
1995 newPropertyDefinition.setName(propertyName);
1996 StorageOperationStatus status = getToscaElementOperation(resource).addToscaDataToToscaElement(resource.getUniqueId(), EdgeLabelEnum.PROPERTIES, VertexTypeEnum.PROPERTIES, newPropertyDefinition, JsonPresentationFields.NAME);
1997 if (status != StorageOperationStatus.OK) {
1998 CommonUtility.addRecordToLog(log, LogLevelEnum.DEBUG, FAILED_TO_ADD_THE_PROPERTY_TO_THE_RESOURCE_STATUS_IS, propertyName, resource.getName(), status);
1999 result = Either.right(status);
2001 if (result == null) {
2002 ComponentParametersView filter = new ComponentParametersView(true);
2003 filter.setIgnoreProperties(false);
2004 getUpdatedComponentRes = getToscaElement(resource.getUniqueId(), filter);
2005 if (getUpdatedComponentRes.isRight()) {
2006 CommonUtility.addRecordToLog(log, LogLevelEnum.DEBUG, FAILED_TO_GET_UPDATED_RESOURCE_STATUS_IS, resource.getUniqueId(), getUpdatedComponentRes.right().value());
2007 result = Either.right(status);
2010 if (result == null) {
2011 PropertyDefinition newProperty = null;
2012 List<PropertyDefinition> properties = ((Resource) getUpdatedComponentRes.left().value()).getProperties();
2013 if (CollectionUtils.isNotEmpty(properties)) {
2014 Optional<PropertyDefinition> newPropertyOptional = properties.stream().filter(p -> p.getName().equals(propertyName)).findAny();
2015 if (newPropertyOptional.isPresent()) {
2016 newProperty = newPropertyOptional.get();
2019 if (newProperty == null) {
2020 CommonUtility.addRecordToLog(log, LogLevelEnum.DEBUG, FAILED_TO_FIND_RECENTLY_ADDED_PROPERTY_ON_THE_RESOURCE_STATUS_IS, propertyName, resource.getUniqueId(), StorageOperationStatus.NOT_FOUND);
2021 result = Either.right(StorageOperationStatus.NOT_FOUND);
2023 result = Either.left(newProperty);
2029 public StorageOperationStatus deletePropertyOfResource(Resource resource, String propertyName) {
2030 return getToscaElementOperation(resource).deleteToscaDataElement(resource.getUniqueId(), EdgeLabelEnum.PROPERTIES, VertexTypeEnum.PROPERTIES, propertyName, JsonPresentationFields.NAME);
2033 public StorageOperationStatus deleteAttributeOfResource(Component component, String attributeName) {
2034 return getToscaElementOperation(component).deleteToscaDataElement(component.getUniqueId(), EdgeLabelEnum.ATTRIBUTES, VertexTypeEnum.ATTRIBUTES, attributeName, JsonPresentationFields.NAME);
2037 public StorageOperationStatus deleteInputOfResource(Component resource, String inputName) {
2038 return getToscaElementOperation(resource).deleteToscaDataElement(resource.getUniqueId(), EdgeLabelEnum.INPUTS, VertexTypeEnum.INPUTS, inputName, JsonPresentationFields.NAME);
2041 public Either<PropertyDefinition, StorageOperationStatus> updatePropertyOfResource(Resource resource, PropertyDefinition newPropertyDefinition) {
2043 Either<Component, StorageOperationStatus> getUpdatedComponentRes = null;
2044 Either<PropertyDefinition, StorageOperationStatus> result = null;
2045 StorageOperationStatus status = getToscaElementOperation(resource).updateToscaDataOfToscaElement(resource.getUniqueId(), EdgeLabelEnum.PROPERTIES, VertexTypeEnum.PROPERTIES, newPropertyDefinition, JsonPresentationFields.NAME);
2046 if (status != StorageOperationStatus.OK) {
2047 CommonUtility.addRecordToLog(log, LogLevelEnum.DEBUG, FAILED_TO_ADD_THE_PROPERTY_TO_THE_RESOURCE_STATUS_IS, newPropertyDefinition.getName(), resource.getName(), status);
2048 result = Either.right(status);
2050 if (result == null) {
2051 ComponentParametersView filter = new ComponentParametersView(true);
2052 filter.setIgnoreProperties(false);
2053 getUpdatedComponentRes = getToscaElement(resource.getUniqueId(), filter);
2054 if (getUpdatedComponentRes.isRight()) {
2055 CommonUtility.addRecordToLog(log, LogLevelEnum.DEBUG, FAILED_TO_GET_UPDATED_RESOURCE_STATUS_IS, resource.getUniqueId(), getUpdatedComponentRes.right().value());
2056 result = Either.right(status);
2059 if (result == null) {
2060 Optional<PropertyDefinition> newProperty = ((Resource) getUpdatedComponentRes.left().value()).getProperties().stream().filter(p -> p.getName().equals(newPropertyDefinition.getName())).findAny();
2061 if (newProperty.isPresent()) {
2062 result = Either.left(newProperty.get());
2064 CommonUtility.addRecordToLog(log, LogLevelEnum.DEBUG, FAILED_TO_FIND_RECENTLY_ADDED_PROPERTY_ON_THE_RESOURCE_STATUS_IS, newPropertyDefinition.getName(), resource.getUniqueId(), StorageOperationStatus.NOT_FOUND);
2065 result = Either.right(StorageOperationStatus.NOT_FOUND);
2071 public Either<PropertyDefinition, StorageOperationStatus> addAttributeOfResource(Component component, PropertyDefinition newAttributeDef) {
2073 Either<Component, StorageOperationStatus> getUpdatedComponentRes = null;
2074 Either<PropertyDefinition, StorageOperationStatus> result = null;
2075 if (newAttributeDef.getUniqueId() == null || newAttributeDef.getUniqueId().isEmpty()) {
2076 String attUniqueId = UniqueIdBuilder.buildAttributeUid(component.getUniqueId(), newAttributeDef.getName());
2077 newAttributeDef.setUniqueId(attUniqueId);
2080 StorageOperationStatus status = getToscaElementOperation(component).addToscaDataToToscaElement(component.getUniqueId(), EdgeLabelEnum.ATTRIBUTES, VertexTypeEnum.ATTRIBUTES, newAttributeDef, JsonPresentationFields.NAME);
2081 if (status != StorageOperationStatus.OK) {
2082 CommonUtility.addRecordToLog(log, LogLevelEnum.DEBUG, FAILED_TO_ADD_THE_PROPERTY_TO_THE_RESOURCE_STATUS_IS, newAttributeDef.getName(), component.getName(), status);
2083 result = Either.right(status);
2085 if (result == null) {
2086 ComponentParametersView filter = new ComponentParametersView(true);
2087 filter.setIgnoreAttributesFrom(false);
2088 getUpdatedComponentRes = getToscaElement(component.getUniqueId(), filter);
2089 if (getUpdatedComponentRes.isRight()) {
2090 CommonUtility.addRecordToLog(log, LogLevelEnum.DEBUG, FAILED_TO_GET_UPDATED_RESOURCE_STATUS_IS, component.getUniqueId(), getUpdatedComponentRes.right().value());
2091 result = Either.right(status);
2094 if (result == null) {
2095 Optional<PropertyDefinition> newAttribute = ((Resource) getUpdatedComponentRes.left().value()).getAttributes().stream().filter(p -> p.getName().equals(newAttributeDef.getName())).findAny();
2096 if (newAttribute.isPresent()) {
2097 result = Either.left(newAttribute.get());
2099 CommonUtility.addRecordToLog(log, LogLevelEnum.DEBUG, FAILED_TO_FIND_RECENTLY_ADDED_PROPERTY_ON_THE_RESOURCE_STATUS_IS, newAttributeDef.getName(), component.getUniqueId(), StorageOperationStatus.NOT_FOUND);
2100 result = Either.right(StorageOperationStatus.NOT_FOUND);
2106 public Either<PropertyDefinition, StorageOperationStatus> updateAttributeOfResource(Component component, PropertyDefinition newAttributeDef) {
2108 Either<Component, StorageOperationStatus> getUpdatedComponentRes = null;
2109 Either<PropertyDefinition, StorageOperationStatus> result = null;
2110 StorageOperationStatus status = getToscaElementOperation(component).updateToscaDataOfToscaElement(component.getUniqueId(), EdgeLabelEnum.ATTRIBUTES, VertexTypeEnum.ATTRIBUTES, newAttributeDef, JsonPresentationFields.NAME);
2111 if (status != StorageOperationStatus.OK) {
2112 CommonUtility.addRecordToLog(log, LogLevelEnum.DEBUG, FAILED_TO_ADD_THE_PROPERTY_TO_THE_RESOURCE_STATUS_IS, newAttributeDef.getName(), component.getName(), status);
2113 result = Either.right(status);
2115 if (result == null) {
2116 ComponentParametersView filter = new ComponentParametersView(true);
2117 filter.setIgnoreAttributesFrom(false);
2118 getUpdatedComponentRes = getToscaElement(component.getUniqueId(), filter);
2119 if (getUpdatedComponentRes.isRight()) {
2120 CommonUtility.addRecordToLog(log, LogLevelEnum.DEBUG, FAILED_TO_GET_UPDATED_RESOURCE_STATUS_IS, component.getUniqueId(), getUpdatedComponentRes.right().value());
2121 result = Either.right(status);
2124 if (result == null) {
2125 Optional<PropertyDefinition> newProperty = ((Resource) getUpdatedComponentRes.left().value()).getAttributes().stream().filter(p -> p.getName().equals(newAttributeDef.getName())).findAny();
2126 if (newProperty.isPresent()) {
2127 result = Either.left(newProperty.get());
2129 CommonUtility.addRecordToLog(log, LogLevelEnum.DEBUG, FAILED_TO_FIND_RECENTLY_ADDED_PROPERTY_ON_THE_RESOURCE_STATUS_IS, newAttributeDef.getName(), component.getUniqueId(), StorageOperationStatus.NOT_FOUND);
2130 result = Either.right(StorageOperationStatus.NOT_FOUND);
2136 public Either<InputDefinition, StorageOperationStatus> updateInputOfComponent(Component component, InputDefinition newInputDefinition) {
2138 Either<Component, StorageOperationStatus> getUpdatedComponentRes = null;
2139 Either<InputDefinition, StorageOperationStatus> result = null;
2140 StorageOperationStatus status = getToscaElementOperation(component).updateToscaDataOfToscaElement(component.getUniqueId(), EdgeLabelEnum.INPUTS, VertexTypeEnum.INPUTS, newInputDefinition, JsonPresentationFields.NAME);
2141 if (status != StorageOperationStatus.OK) {
2142 CommonUtility.addRecordToLog(log, LogLevelEnum.DEBUG, "Failed to update the input {} to the component {}. Status is {}. ", newInputDefinition.getName(), component.getName(), status);
2143 result = Either.right(status);
2145 if (result == null) {
2146 ComponentParametersView filter = new ComponentParametersView(true);
2147 filter.setIgnoreInputs(false);
2148 getUpdatedComponentRes = getToscaElement(component.getUniqueId(), filter);
2149 if (getUpdatedComponentRes.isRight()) {
2150 CommonUtility.addRecordToLog(log, LogLevelEnum.DEBUG, FAILED_TO_GET_UPDATED_RESOURCE_STATUS_IS, component.getUniqueId(), getUpdatedComponentRes.right().value());
2151 result = Either.right(status);
2154 if (result == null) {
2155 Optional<InputDefinition> updatedInput = getUpdatedComponentRes.left().value().getInputs().stream().filter(p -> p.getName().equals(newInputDefinition.getName())).findAny();
2156 if (updatedInput.isPresent()) {
2157 result = Either.left(updatedInput.get());
2159 CommonUtility.addRecordToLog(log, LogLevelEnum.DEBUG, "Failed to find recently updated inputs {} on the resource {}. Status is {}. ", newInputDefinition.getName(), component.getUniqueId(), StorageOperationStatus.NOT_FOUND);
2160 result = Either.right(StorageOperationStatus.NOT_FOUND);
2167 * method - ename the group instances after referenced container name renamed flow - VF rename -(triggers)-> Group rename
2169 * @param containerComponent - container such as service
2170 * @param componentInstance - context component
2171 * @param componentInstanceId - id
2172 * @return - successfull/failed status
2174 public Either<StorageOperationStatus, StorageOperationStatus> cleanAndAddGroupInstancesToComponentInstance(Component containerComponent, ComponentInstance componentInstance, String componentInstanceId) {
2175 String uniqueId = componentInstance.getUniqueId();
2176 StorageOperationStatus status = nodeTemplateOperation.deleteToscaDataDeepElementsBlockOfToscaElement(containerComponent.getUniqueId(), EdgeLabelEnum.INST_GROUPS, VertexTypeEnum.INST_GROUPS, uniqueId);
2177 if (status != StorageOperationStatus.OK && status != StorageOperationStatus.NOT_FOUND) {
2178 CommonUtility.addRecordToLog(log, LogLevelEnum.DEBUG, "Failed to delete group instances for container {}. error {] ", componentInstanceId, status);
2179 return Either.right(status);
2181 if (componentInstance.getGroupInstances() != null) {
2182 status = addGroupInstancesToComponentInstance(containerComponent, componentInstance, componentInstance.getGroupInstances());
2183 if (status != StorageOperationStatus.OK && status != StorageOperationStatus.NOT_FOUND) {
2184 CommonUtility.addRecordToLog(log, LogLevelEnum.DEBUG, "Failed to add group instances for container {}. error {] ", componentInstanceId, status);
2185 return Either.right(status);
2188 return Either.left(status);
2191 public StorageOperationStatus addGroupInstancesToComponentInstance(Component containerComponent, ComponentInstance componentInstance, List<GroupDefinition> groups, Map<String, List<ArtifactDefinition>> groupInstancesArtifacts) {
2192 return nodeTemplateOperation.addGroupInstancesToComponentInstance(containerComponent, componentInstance, groups, groupInstancesArtifacts);
2195 public Either<List<GroupDefinition>, StorageOperationStatus> updateGroupsOnComponent(Component component, List<GroupDataDefinition> updatedGroups) {
2196 return groupsOperation.updateGroups(component, updatedGroups, true);
2199 public Either<List<GroupInstance>, StorageOperationStatus> updateGroupInstancesOnComponent(Component component, String instanceId, List<GroupInstance> updatedGroupInstances) {
2200 return groupsOperation.updateGroupInstances(component, instanceId, updatedGroupInstances);
2203 public StorageOperationStatus addGroupInstancesToComponentInstance(Component containerComponent, ComponentInstance componentInstance, List<GroupInstance> groupInstances) {
2204 return nodeTemplateOperation.addGroupInstancesToComponentInstance(containerComponent, componentInstance, groupInstances);
2207 public StorageOperationStatus addDeploymentArtifactsToComponentInstance(Component containerComponent, ComponentInstance componentInstance, Map<String, ArtifactDefinition> deploymentArtifacts) {
2208 return nodeTemplateOperation.addDeploymentArtifactsToComponentInstance(containerComponent, componentInstance, deploymentArtifacts);
2211 public StorageOperationStatus updateComponentInstanceProperty(Component containerComponent, String componentInstanceId, ComponentInstanceProperty property) {
2212 return nodeTemplateOperation.updateComponentInstanceProperty(containerComponent, componentInstanceId, property);
2215 public StorageOperationStatus updateComponentInstanceProperties(Component containerComponent, String componentInstanceId, List<ComponentInstanceProperty> properties) {
2216 return nodeTemplateOperation.updateComponentInstanceProperties(containerComponent, componentInstanceId, properties);
2220 public StorageOperationStatus addComponentInstanceProperty(Component containerComponent, String componentInstanceId, ComponentInstanceProperty property) {
2221 return nodeTemplateOperation.addComponentInstanceProperty(containerComponent, componentInstanceId, property);
2224 public StorageOperationStatus updateComponentInstanceAttribute(Component containerComponent, String componentInstanceId, ComponentInstanceProperty property){
2225 return nodeTemplateOperation.updateComponentInstanceAttribute(containerComponent, componentInstanceId, property);
2228 public StorageOperationStatus addComponentInstanceAttribute(Component containerComponent, String componentInstanceId, ComponentInstanceProperty property){
2229 return nodeTemplateOperation.addComponentInstanceAttribute(containerComponent, componentInstanceId, property);
2232 public StorageOperationStatus updateComponentInstanceInput(Component containerComponent, String componentInstanceId, ComponentInstanceInput property) {
2233 return nodeTemplateOperation.updateComponentInstanceInput(containerComponent, componentInstanceId, property);
2236 public StorageOperationStatus updateComponentInstanceInputs(Component containerComponent, String componentInstanceId, List<ComponentInstanceInput> instanceInputs) {
2237 return nodeTemplateOperation.updateComponentInstanceInputs(containerComponent, componentInstanceId, instanceInputs);
2240 public StorageOperationStatus addComponentInstanceInput(Component containerComponent, String componentInstanceId, ComponentInstanceInput property) {
2241 return nodeTemplateOperation.addComponentInstanceInput(containerComponent, componentInstanceId, property);
2244 public void setNodeTypeOperation(NodeTypeOperation nodeTypeOperation) {
2245 this.nodeTypeOperation = nodeTypeOperation;
2248 public void setTopologyTemplateOperation(TopologyTemplateOperation topologyTemplateOperation) {
2249 this.topologyTemplateOperation = topologyTemplateOperation;
2252 public StorageOperationStatus deleteComponentInstanceInputsFromTopologyTemplate(Component containerComponent, List<InputDefinition> inputsToDelete) {
2253 return topologyTemplateOperation.deleteToscaDataElements(containerComponent.getUniqueId(), EdgeLabelEnum.INPUTS, inputsToDelete.stream().map(PropertyDataDefinition::getName).collect(Collectors.toList()));
2256 public StorageOperationStatus updateComponentInstanceCapabiltyProperty(Component containerComponent, String componentInstanceUniqueId, String capabilityUniqueId, ComponentInstanceProperty property) {
2257 return nodeTemplateOperation.updateComponentInstanceCapabilityProperty(containerComponent, componentInstanceUniqueId, capabilityUniqueId, property);
2260 public StorageOperationStatus updateComponentInstanceCapabilityProperties(Component containerComponent, String componentInstanceUniqueId) {
2261 return convertComponentInstanceProperties(containerComponent, componentInstanceUniqueId)
2262 .map(instanceCapProps -> topologyTemplateOperation.updateComponentInstanceCapabilityProperties(containerComponent, componentInstanceUniqueId, instanceCapProps))
2263 .orElse(StorageOperationStatus.NOT_FOUND);
2266 public StorageOperationStatus updateComponentCalculatedCapabilitiesProperties(Component containerComponent) {
2267 Map<String, MapCapabilityProperty> MapCapabilityPropertyMap = convertComponentCapabilitiesProperties(containerComponent);
2268 return nodeTemplateOperation.overrideComponentCapabilitiesProperties(containerComponent, MapCapabilityPropertyMap);
2271 public StorageOperationStatus deleteAllCalculatedCapabilitiesRequirements(String topologyTemplateId) {
2272 StorageOperationStatus status = topologyTemplateOperation.removeToscaData(topologyTemplateId, EdgeLabelEnum.CALCULATED_CAPABILITIES, VertexTypeEnum.CALCULATED_CAPABILITIES);
2273 if (status == StorageOperationStatus.OK) {
2274 status = topologyTemplateOperation.removeToscaData(topologyTemplateId, EdgeLabelEnum.CALCULATED_REQUIREMENTS, VertexTypeEnum.CALCULATED_REQUIREMENTS);
2276 if (status == StorageOperationStatus.OK) {
2277 status = topologyTemplateOperation.removeToscaData(topologyTemplateId, EdgeLabelEnum.CALCULATED_CAP_PROPERTIES, VertexTypeEnum.CALCULATED_CAP_PROPERTIES);
2282 public Either<Component, StorageOperationStatus> shouldUpgradeToLatestDerived(Resource clonedResource) {
2283 String componentId = clonedResource.getUniqueId();
2284 Either<GraphVertex, TitanOperationStatus> getVertexEither = titanDao.getVertexById(componentId, JsonParseFlagEnum.NoParse);
2285 if (getVertexEither.isRight()) {
2286 log.debug(COULDNT_FETCH_COMPONENT_WITH_AND_UNIQUE_ID_ERROR, componentId, getVertexEither.right().value());
2287 return Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(getVertexEither.right().value()));
2290 GraphVertex nodeTypeV = getVertexEither.left().value();
2292 ToscaElement toscaElementToUpdate = ModelConverter.convertToToscaElement(clonedResource);
2294 Either<ToscaElement, StorageOperationStatus> shouldUpdateDerivedVersion = nodeTypeOperation.shouldUpdateDerivedVersion(toscaElementToUpdate, nodeTypeV);
2295 if (shouldUpdateDerivedVersion.isRight() && StorageOperationStatus.OK != shouldUpdateDerivedVersion.right().value()) {
2296 log.debug("Failed to update derived version for node type {} derived {}, error: {}", componentId, clonedResource.getDerivedFrom().get(0), shouldUpdateDerivedVersion.right().value());
2297 return Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(getVertexEither.right().value()));
2299 if (shouldUpdateDerivedVersion.isLeft()) {
2300 return Either.left(ModelConverter.convertFromToscaElement(shouldUpdateDerivedVersion.left().value()));
2302 return Either.left(clonedResource);
2306 * Returns list of ComponentInstanceProperty belonging to component instance capability specified by name, type and ownerId
2308 public Either<List<ComponentInstanceProperty>, StorageOperationStatus> getComponentInstanceCapabilityProperties(String componentId, String instanceId, String capabilityName, String capabilityType, String ownerId) {
2309 return topologyTemplateOperation.getComponentInstanceCapabilityProperties(componentId, instanceId, capabilityName, capabilityType, ownerId);
2312 private Map<String, MapCapabilityProperty> convertComponentCapabilitiesProperties(Component currComponent) {
2313 Map<String, MapCapabilityProperty> map = ModelConverter.extractCapabilityPropertiesFromGroups(currComponent.getGroups(), true);
2314 map.putAll(ModelConverter.extractCapabilityProperteisFromInstances(currComponent.getComponentInstances(), true));
2318 private Optional<MapCapabilityProperty> convertComponentInstanceProperties(Component component, String instanceId) {
2319 return component.fetchInstanceById(instanceId)
2320 .map(ci -> ModelConverter.convertToMapOfMapCapabiltyProperties(ci.getCapabilities(), instanceId));
2323 public Either<PolicyDefinition, StorageOperationStatus> associatePolicyToComponent(String componentId, PolicyDefinition policyDefinition, int counter) {
2324 Either<PolicyDefinition, StorageOperationStatus> result = null;
2325 Either<GraphVertex, TitanOperationStatus> getVertexEither;
2326 getVertexEither = titanDao.getVertexById(componentId, JsonParseFlagEnum.ParseMetadata);
2327 if (getVertexEither.isRight()) {
2328 log.error(COULDNT_FETCH_A_COMPONENT_WITH_AND_UNIQUE_ID_ERROR, componentId, getVertexEither.right().value());
2329 result = Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(getVertexEither.right().value()));
2331 if (getVertexEither.left().value().getLabel() != VertexTypeEnum.TOPOLOGY_TEMPLATE) {
2332 log.error("Policy association to component of Tosca type {} is not allowed. ", getVertexEither.left().value().getLabel());
2333 result = Either.right(StorageOperationStatus.BAD_REQUEST);
2336 if (result == null) {
2337 StorageOperationStatus status = topologyTemplateOperation.addPolicyToToscaElement(getVertexEither.left().value(), policyDefinition, counter);
2338 if (status != StorageOperationStatus.OK) {
2339 return Either.right(status);
2342 if (result == null) {
2343 result = Either.left(policyDefinition);
2348 public StorageOperationStatus associatePoliciesToComponent(String componentId, List<PolicyDefinition> policies) {
2349 log.debug("#associatePoliciesToComponent - associating policies for component {}.", componentId);
2350 return titanDao.getVertexById(componentId, JsonParseFlagEnum.ParseMetadata)
2351 .either(containerVertex -> topologyTemplateOperation.addPoliciesToToscaElement(containerVertex, policies),
2352 DaoStatusConverter::convertTitanStatusToStorageStatus);
2355 public Either<PolicyDefinition, StorageOperationStatus> updatePolicyOfComponent(String componentId, PolicyDefinition policyDefinition) {
2356 Either<PolicyDefinition, StorageOperationStatus> result = null;
2357 Either<GraphVertex, TitanOperationStatus> getVertexEither;
2358 getVertexEither = titanDao.getVertexById(componentId, JsonParseFlagEnum.NoParse);
2359 if (getVertexEither.isRight()) {
2360 log.error(COULDNT_FETCH_A_COMPONENT_WITH_AND_UNIQUE_ID_ERROR, componentId, getVertexEither.right().value());
2361 result = Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(getVertexEither.right().value()));
2363 if (result == null) {
2364 StorageOperationStatus status = topologyTemplateOperation.updatePolicyOfToscaElement(getVertexEither.left().value(), policyDefinition);
2365 if (status != StorageOperationStatus.OK) {
2366 return Either.right(status);
2369 if (result == null) {
2370 result = Either.left(policyDefinition);
2375 public StorageOperationStatus updatePoliciesOfComponent(String componentId, List<PolicyDefinition> policyDefinition) {
2376 log.debug("#updatePoliciesOfComponent - updating policies for component {}", componentId);
2377 return titanDao.getVertexById(componentId, JsonParseFlagEnum.NoParse)
2379 .map(DaoStatusConverter::convertTitanStatusToStorageStatus)
2380 .either(containerVertex -> topologyTemplateOperation.updatePoliciesOfToscaElement(containerVertex, policyDefinition),
2384 public StorageOperationStatus removePolicyFromComponent(String componentId, String policyId) {
2385 StorageOperationStatus status = null;
2386 Either<GraphVertex, TitanOperationStatus> getVertexEither = titanDao.getVertexById(componentId, JsonParseFlagEnum.NoParse);
2387 if (getVertexEither.isRight()) {
2388 log.error(COULDNT_FETCH_A_COMPONENT_WITH_AND_UNIQUE_ID_ERROR, componentId, getVertexEither.right().value());
2389 status = DaoStatusConverter.convertTitanStatusToStorageStatus(getVertexEither.right().value());
2391 if (status == null) {
2392 status = topologyTemplateOperation.removePolicyFromToscaElement(getVertexEither.left().value(), policyId);
2397 public boolean canAddGroups(String componentId) {
2398 GraphVertex vertex = titanDao.getVertexById(componentId)
2400 .on(this::onTitanError);
2401 return topologyTemplateOperation.hasEdgeOfType(vertex, EdgeLabelEnum.GROUPS);
2404 GraphVertex onTitanError(TitanOperationStatus toe) {
2405 throw new StorageException(
2406 DaoStatusConverter.convertTitanStatusToStorageStatus(toe));
2409 public void updateNamesOfCalculatedCapabilitiesRequirements(String componentId){
2410 topologyTemplateOperation
2411 .updateNamesOfCalculatedCapabilitiesRequirements(componentId, getTopologyTemplate(componentId));
2414 public void revertNamesOfCalculatedCapabilitiesRequirements(String componentId) {
2415 topologyTemplateOperation
2416 .revertNamesOfCalculatedCapabilitiesRequirements(componentId, getTopologyTemplate(componentId));
2419 private TopologyTemplate getTopologyTemplate(String componentId) {
2420 return (TopologyTemplate)topologyTemplateOperation
2421 .getToscaElement(componentId, getFilterComponentWithCapProperties())
2423 .on(this::throwStorageException);
2426 private ComponentParametersView getFilterComponentWithCapProperties() {
2427 ComponentParametersView filter = new ComponentParametersView();
2428 filter.setIgnoreCapabiltyProperties(false);
2432 private ToscaElement throwStorageException(StorageOperationStatus status) {
2433 throw new StorageException(status);