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.Direction;
29 import org.apache.tinkerpop.gremlin.structure.Edge;
30 import org.openecomp.sdc.be.dao.jsongraph.GraphVertex;
31 import org.openecomp.sdc.be.dao.jsongraph.TitanDao;
32 import org.openecomp.sdc.be.dao.jsongraph.types.EdgeLabelEnum;
33 import org.openecomp.sdc.be.dao.jsongraph.types.JsonParseFlagEnum;
34 import org.openecomp.sdc.be.dao.jsongraph.types.VertexTypeEnum;
35 import org.openecomp.sdc.be.dao.titan.TitanOperationStatus;
36 import org.openecomp.sdc.be.datatypes.elements.*;
37 import org.openecomp.sdc.be.datatypes.elements.MapInterfaceDataDefinition;
38 import org.openecomp.sdc.be.datatypes.enums.*;
39 import org.openecomp.sdc.be.model.*;
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> getComponentInputs(String componentId) {
976 Either<GraphVertex, TitanOperationStatus> getVertexEither = titanDao.getVertexById(componentId, JsonParseFlagEnum.NoParse);
977 if (getVertexEither.isRight()) {
978 log.debug("Couldn't fetch component with and unique id {}, error: {}", componentId, getVertexEither.right().value());
979 return Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(getVertexEither.right().value()));
983 Either<ToscaElement, StorageOperationStatus> toscaElement =
984 topologyTemplateOperation.getToscaElement(componentId);
985 if(toscaElement.isRight()) {
986 return Either.right(toscaElement.right().value());
989 TopologyTemplate topologyTemplate = (TopologyTemplate) toscaElement.left().value();
991 Map<String, PropertyDataDefinition> inputsMap = topologyTemplate.getInputs();
993 List<InputDefinition> inputs = new ArrayList<>();
994 if(MapUtils.isNotEmpty(inputsMap)) {
996 inputsMap.values().stream().map(p -> new InputDefinition(p)).collect(Collectors.toList());
999 return Either.left(inputs);
1002 public Either<List<InputDefinition>, StorageOperationStatus> updateInputsToComponent(List<InputDefinition> inputs, String componentId) {
1004 Either<GraphVertex, TitanOperationStatus> getVertexEither = titanDao.getVertexById(componentId, JsonParseFlagEnum.NoParse);
1005 if (getVertexEither.isRight()) {
1006 log.debug(COULDNT_FETCH_COMPONENT_WITH_AND_UNIQUE_ID_ERROR, componentId, getVertexEither.right().value());
1007 return Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(getVertexEither.right().value()));
1011 GraphVertex vertex = getVertexEither.left().value();
1012 List<PropertyDataDefinition> inputsAsDataDef = inputs.stream().map(PropertyDataDefinition::new).collect(Collectors.toList());
1014 StorageOperationStatus status = topologyTemplateOperation.updateToscaDataOfToscaElement(vertex, EdgeLabelEnum.INPUTS, VertexTypeEnum.INPUTS, inputsAsDataDef, JsonPresentationFields.NAME);
1016 if (StorageOperationStatus.OK == status) {
1017 log.debug(COMPONENT_CREATED_SUCCESSFULLY);
1018 List<InputDefinition> inputsResList = null;
1019 if (inputsAsDataDef != null && !inputsAsDataDef.isEmpty()) {
1020 inputsResList = inputsAsDataDef.stream().map(InputDefinition::new).collect(Collectors.toList());
1022 return Either.left(inputsResList);
1024 return Either.right(status);
1028 // region - ComponentInstance
1029 public Either<Map<String, List<ComponentInstanceProperty>>, StorageOperationStatus> associateComponentInstancePropertiesToComponent(Map<String, List<ComponentInstanceProperty>> instProperties, String componentId) {
1031 Either<GraphVertex, TitanOperationStatus> getVertexEither = titanDao.getVertexById(componentId, JsonParseFlagEnum.NoParse);
1032 if (getVertexEither.isRight()) {
1033 log.debug(COULDNT_FETCH_COMPONENT_WITH_AND_UNIQUE_ID_ERROR, componentId, getVertexEither.right().value());
1034 return Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(getVertexEither.right().value()));
1038 GraphVertex vertex = getVertexEither.left().value();
1039 Map<String, MapPropertiesDataDefinition> instPropsMap = new HashMap<>();
1040 if (instProperties != null) {
1042 MapPropertiesDataDefinition propertiesMap;
1043 for (Entry<String, List<ComponentInstanceProperty>> entry : instProperties.entrySet()) {
1044 propertiesMap = new MapPropertiesDataDefinition();
1046 propertiesMap.setMapToscaDataDefinition(entry.getValue().stream().map(PropertyDataDefinition::new).collect(Collectors.toMap(PropertyDataDefinition::getName, e -> e)));
1048 instPropsMap.put(entry.getKey(), propertiesMap);
1052 StorageOperationStatus status = topologyTemplateOperation.associateInstPropertiesToComponent(vertex, instPropsMap);
1054 if (StorageOperationStatus.OK == status) {
1055 log.debug(COMPONENT_CREATED_SUCCESSFULLY);
1056 return Either.left(instProperties);
1058 return Either.right(status);
1063 * saves the instInputs as the updated instance inputs of the component container in DB
1065 public Either<Map<String, List<ComponentInstanceInput>>, StorageOperationStatus> updateComponentInstanceInputsToComponent(Map<String, List<ComponentInstanceInput>> instInputs, String componentId) {
1066 if (instInputs == null || instInputs.isEmpty()) {
1067 return Either.left(instInputs);
1069 StorageOperationStatus status;
1070 for (Entry<String, List<ComponentInstanceInput>> inputsPerIntance : instInputs.entrySet()) {
1071 List<ComponentInstanceInput> toscaDataListPerInst = inputsPerIntance.getValue();
1072 List<String> pathKeysPerInst = new ArrayList<>();
1073 pathKeysPerInst.add(inputsPerIntance.getKey());
1074 status = topologyTemplateOperation.updateToscaDataDeepElementsOfToscaElement(componentId, EdgeLabelEnum.INST_INPUTS, VertexTypeEnum.INST_INPUTS, toscaDataListPerInst, pathKeysPerInst, JsonPresentationFields.NAME);
1075 if (status != StorageOperationStatus.OK) {
1076 log.debug("Failed to update component instance inputs for instance {} in component {} edge type {} error {}", inputsPerIntance.getKey(), componentId, EdgeLabelEnum.INST_INPUTS, status);
1077 return Either.right(status);
1081 return Either.left(instInputs);
1085 * saves the instProps as the updated instance properties of the component container in DB
1087 public Either<Map<String, List<ComponentInstanceProperty>>, StorageOperationStatus> updateComponentInstancePropsToComponent(Map<String, List<ComponentInstanceProperty>> instProps, String componentId) {
1088 if (instProps == null || instProps.isEmpty()) {
1089 return Either.left(instProps);
1091 StorageOperationStatus status;
1092 for (Entry<String, List<ComponentInstanceProperty>> propsPerIntance : instProps.entrySet()) {
1093 List<ComponentInstanceProperty> toscaDataListPerInst = propsPerIntance.getValue();
1094 List<String> pathKeysPerInst = new ArrayList<>();
1095 pathKeysPerInst.add(propsPerIntance.getKey());
1096 status = topologyTemplateOperation.updateToscaDataDeepElementsOfToscaElement(componentId, EdgeLabelEnum.INST_PROPERTIES, VertexTypeEnum.INST_PROPERTIES, toscaDataListPerInst, pathKeysPerInst, JsonPresentationFields.NAME);
1097 if (status != StorageOperationStatus.OK) {
1098 log.debug("Failed to update component instance inputs for instance {} in component {} edge type {} error {}", propsPerIntance.getKey(), componentId, EdgeLabelEnum.INST_PROPERTIES, status);
1099 return Either.right(status);
1103 return Either.left(instProps);
1106 public Either<Map<String, List<ComponentInstanceInput>>, StorageOperationStatus> associateComponentInstanceInputsToComponent(Map<String, List<ComponentInstanceInput>> instInputs, String componentId) {
1108 Either<GraphVertex, TitanOperationStatus> getVertexEither = titanDao.getVertexById(componentId, JsonParseFlagEnum.NoParse);
1109 if (getVertexEither.isRight()) {
1110 log.debug(COULDNT_FETCH_COMPONENT_WITH_AND_UNIQUE_ID_ERROR, componentId, getVertexEither.right().value());
1111 return Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(getVertexEither.right().value()));
1114 GraphVertex vertex = getVertexEither.left().value();
1115 Map<String, MapPropertiesDataDefinition> instPropsMap = new HashMap<>();
1116 if (instInputs != null) {
1118 MapPropertiesDataDefinition propertiesMap;
1119 for (Entry<String, List<ComponentInstanceInput>> entry : instInputs.entrySet()) {
1120 propertiesMap = new MapPropertiesDataDefinition();
1122 propertiesMap.setMapToscaDataDefinition(entry.getValue().stream().map(PropertyDataDefinition::new).collect(Collectors.toMap(PropertyDataDefinition::getName, e -> e)));
1124 instPropsMap.put(entry.getKey(), propertiesMap);
1128 StorageOperationStatus status = topologyTemplateOperation.associateInstInputsToComponent(vertex, instPropsMap);
1130 if (StorageOperationStatus.OK == status) {
1131 log.debug(COMPONENT_CREATED_SUCCESSFULLY);
1132 return Either.left(instInputs);
1134 return Either.right(status);
1138 public Either<Map<String, List<ComponentInstanceInput>>, StorageOperationStatus> addComponentInstanceInputsToComponent(Component containerComponent, Map<String, List<ComponentInstanceInput>> instProperties) {
1139 requireNonNull(instProperties);
1140 StorageOperationStatus status;
1141 for (Entry<String, List<ComponentInstanceInput>> entry : instProperties.entrySet()) {
1142 List<ComponentInstanceInput> props = entry.getValue();
1143 String componentInstanceId = entry.getKey();
1144 if (!isEmpty(props)) {
1145 for (ComponentInstanceInput property : props) {
1146 List<ComponentInstanceInput> componentInstancesInputs = containerComponent.getComponentInstancesInputs().get(componentInstanceId);
1147 Optional<ComponentInstanceInput> instanceProperty = componentInstancesInputs.stream()
1148 .filter(p -> p.getName().equals(property.getName()))
1150 if (instanceProperty.isPresent()) {
1151 status = updateComponentInstanceInput(containerComponent, componentInstanceId, property);
1153 status = addComponentInstanceInput(containerComponent, componentInstanceId, property);
1155 if (status != StorageOperationStatus.OK) {
1156 log.debug("Failed to update instance input {} for instance {} error {} ", property, componentInstanceId, status);
1157 return Either.right(status);
1159 log.trace("instance input {} for instance {} updated", property, componentInstanceId);
1164 return Either.left(instProperties);
1167 public Either<Map<String, List<ComponentInstanceProperty>>, StorageOperationStatus> addComponentInstancePropertiesToComponent(Component containerComponent, Map<String, List<ComponentInstanceProperty>> instProperties) {
1168 requireNonNull(instProperties);
1169 StorageOperationStatus status;
1170 for (Entry<String, List<ComponentInstanceProperty>> entry : instProperties.entrySet()) {
1171 List<ComponentInstanceProperty> props = entry.getValue();
1172 String componentInstanceId = entry.getKey();
1173 List<ComponentInstanceProperty> instanceProperties = containerComponent.getComponentInstancesProperties().get(componentInstanceId);
1174 if (!isEmpty(props)) {
1175 for (ComponentInstanceProperty property : props) {
1176 Optional<ComponentInstanceProperty> instanceProperty = instanceProperties.stream()
1177 .filter(p -> p.getUniqueId().equals(property.getUniqueId()))
1179 if (instanceProperty.isPresent()) {
1180 status = updateComponentInstanceProperty(containerComponent, componentInstanceId, property);
1182 status = addComponentInstanceProperty(containerComponent, componentInstanceId, property);
1184 if (status != StorageOperationStatus.OK) {
1185 log.debug("Failed to update instance property {} for instance {} error {} ", property, componentInstanceId, status);
1186 return Either.right(status);
1191 return Either.left(instProperties);
1194 public StorageOperationStatus associateDeploymentArtifactsToInstances(Map<String, Map<String, ArtifactDefinition>> instDeploymentArtifacts, String componentId, User user) {
1196 Either<GraphVertex, TitanOperationStatus> getVertexEither = titanDao.getVertexById(componentId, JsonParseFlagEnum.NoParse);
1197 if (getVertexEither.isRight()) {
1198 log.debug(COULDNT_FETCH_COMPONENT_WITH_AND_UNIQUE_ID_ERROR, componentId, getVertexEither.right().value());
1199 return DaoStatusConverter.convertTitanStatusToStorageStatus(getVertexEither.right().value());
1203 GraphVertex vertex = getVertexEither.left().value();
1204 Map<String, MapArtifactDataDefinition> instArtMap = new HashMap<>();
1205 if (instDeploymentArtifacts != null) {
1207 MapArtifactDataDefinition artifactsMap;
1208 for (Entry<String, Map<String, ArtifactDefinition>> entry : instDeploymentArtifacts.entrySet()) {
1209 Map<String, ArtifactDefinition> artList = entry.getValue();
1210 Map<String, ArtifactDataDefinition> artifacts = artList.entrySet().stream().collect(Collectors.toMap(Map.Entry::getKey, e -> new ArtifactDataDefinition(e.getValue())));
1211 artifactsMap = nodeTemplateOperation.prepareInstDeploymentArtifactPerInstance(artifacts, entry.getKey(), user, NodeTemplateOperation.HEAT_VF_ENV_NAME);
1213 instArtMap.put(entry.getKey(), artifactsMap);
1217 return topologyTemplateOperation.associateInstDeploymentArtifactsToComponent(vertex, instArtMap);
1221 public StorageOperationStatus associateArtifactsToInstances(Map<String, Map<String, ArtifactDefinition>> instArtifacts, String componentId) {
1223 Either<GraphVertex, TitanOperationStatus> getVertexEither = titanDao.getVertexById(componentId, JsonParseFlagEnum.NoParse);
1224 if (getVertexEither.isRight()) {
1225 log.debug(COULDNT_FETCH_COMPONENT_WITH_AND_UNIQUE_ID_ERROR, componentId, getVertexEither.right().value());
1226 return DaoStatusConverter.convertTitanStatusToStorageStatus(getVertexEither.right().value());
1230 GraphVertex vertex = getVertexEither.left().value();
1231 Map<String, MapArtifactDataDefinition> instArtMap = new HashMap<>();
1232 if (instArtifacts != null) {
1234 MapArtifactDataDefinition artifactsMap;
1235 for (Entry<String, Map<String, ArtifactDefinition>> entry : instArtifacts.entrySet()) {
1236 Map<String, ArtifactDefinition> artList = entry.getValue();
1237 Map<String, ArtifactDataDefinition> artifacts = artList.entrySet().stream().collect(Collectors.toMap(Map.Entry::getKey, e -> new ArtifactDataDefinition(e.getValue())));
1238 artifactsMap = new MapArtifactDataDefinition(artifacts);
1240 instArtMap.put(entry.getKey(), artifactsMap);
1244 return topologyTemplateOperation.associateInstArtifactsToComponent(vertex, instArtMap);
1248 public StorageOperationStatus associateInstAttributeToComponentToInstances(Map<String, List<PropertyDefinition>> instArttributes, String componentId) {
1250 Either<GraphVertex, TitanOperationStatus> getVertexEither = titanDao.getVertexById(componentId, JsonParseFlagEnum.NoParse);
1251 if (getVertexEither.isRight()) {
1252 log.debug(COULDNT_FETCH_COMPONENT_WITH_AND_UNIQUE_ID_ERROR, componentId, getVertexEither.right().value());
1253 return DaoStatusConverter.convertTitanStatusToStorageStatus(getVertexEither.right().value());
1257 GraphVertex vertex = getVertexEither.left().value();
1258 Map<String, MapPropertiesDataDefinition> instAttr = new HashMap<>();
1259 if (instArttributes != null) {
1261 MapPropertiesDataDefinition attributesMap;
1262 for (Entry<String, List<PropertyDefinition>> entry : instArttributes.entrySet()) {
1263 attributesMap = new MapPropertiesDataDefinition();
1264 attributesMap.setMapToscaDataDefinition(entry.getValue().stream().map(PropertyDataDefinition::new).collect(Collectors.toMap(PropertyDataDefinition::getName, e -> e)));
1265 instAttr.put(entry.getKey(), attributesMap);
1269 return topologyTemplateOperation.associateInstAttributeToComponent(vertex, instAttr);
1274 public StorageOperationStatus associateOrAddCalculatedCapReq(Map<ComponentInstance, Map<String, List<CapabilityDefinition>>> instCapabilties, Map<ComponentInstance, Map<String, List<RequirementDefinition>>> instReg, String componentId) {
1275 Either<GraphVertex, TitanOperationStatus> getVertexEither = titanDao.getVertexById(componentId, JsonParseFlagEnum.NoParse);
1276 if (getVertexEither.isRight()) {
1277 log.debug(COULDNT_FETCH_COMPONENT_WITH_AND_UNIQUE_ID_ERROR, componentId, getVertexEither.right().value());
1278 return DaoStatusConverter.convertTitanStatusToStorageStatus(getVertexEither.right().value());
1282 GraphVertex vertex = getVertexEither.left().value();
1284 Map<String, MapListRequirementDataDefinition> calcRequirements = new HashMap<>();
1286 Map<String, MapListCapabilityDataDefinition> calcCapabilty = new HashMap<>();
1287 Map<String, MapCapabilityProperty> calculatedCapabilitiesProperties = new HashMap<>();
1288 if (instCapabilties != null) {
1289 for (Entry<ComponentInstance, Map<String, List<CapabilityDefinition>>> entry : instCapabilties.entrySet()) {
1291 Map<String, List<CapabilityDefinition>> caps = entry.getValue();
1292 Map<String, ListCapabilityDataDefinition> mapToscaDataDefinition = new HashMap<>();
1293 for (Entry<String, List<CapabilityDefinition>> instCapability : caps.entrySet()) {
1294 mapToscaDataDefinition.put(instCapability.getKey(), new ListCapabilityDataDefinition(instCapability.getValue().stream().map(CapabilityDataDefinition::new).collect(Collectors.toList())));
1297 ComponentInstanceDataDefinition componentInstance = new ComponentInstanceDataDefinition(entry.getKey());
1298 MapListCapabilityDataDefinition capMap = nodeTemplateOperation.prepareCalculatedCapabiltyForNodeType(mapToscaDataDefinition, componentInstance);
1300 MapCapabilityProperty mapCapabilityProperty = ModelConverter.convertToMapOfMapCapabiltyProperties(caps, componentInstance.getUniqueId(), true);
1302 calcCapabilty.put(entry.getKey().getUniqueId(), capMap);
1303 calculatedCapabilitiesProperties.put(entry.getKey().getUniqueId(), mapCapabilityProperty);
1307 if (instReg != null) {
1308 for (Entry<ComponentInstance, Map<String, List<RequirementDefinition>>> entry : instReg.entrySet()) {
1310 Map<String, List<RequirementDefinition>> req = entry.getValue();
1311 Map<String, ListRequirementDataDefinition> mapToscaDataDefinition = new HashMap<>();
1312 for (Entry<String, List<RequirementDefinition>> instReq : req.entrySet()) {
1313 mapToscaDataDefinition.put(instReq.getKey(), new ListRequirementDataDefinition(instReq.getValue().stream().map(RequirementDataDefinition::new).collect(Collectors.toList())));
1316 MapListRequirementDataDefinition capMap = nodeTemplateOperation.prepareCalculatedRequirementForNodeType(mapToscaDataDefinition, new ComponentInstanceDataDefinition(entry.getKey()));
1318 calcRequirements.put(entry.getKey().getUniqueId(), capMap);
1322 return topologyTemplateOperation.associateOrAddCalcCapReqToComponent(vertex, calcRequirements, calcCapabilty, calculatedCapabilitiesProperties);
1325 private Either<List<Service>, StorageOperationStatus> getLatestVersionNonCheckoutServicesMetadataOnly(Map<GraphPropertyEnum, Object> hasProps, Map<GraphPropertyEnum, Object> hasNotProps) {
1326 List<Service> services = new ArrayList<>();
1327 List<LifecycleStateEnum> states = new ArrayList<>();
1329 hasProps.put(GraphPropertyEnum.COMPONENT_TYPE, ComponentTypeEnum.SERVICE.name());
1330 hasProps.put(GraphPropertyEnum.IS_HIGHEST_VERSION, true);
1333 states.add(LifecycleStateEnum.NOT_CERTIFIED_CHECKOUT);
1334 hasNotProps.put(GraphPropertyEnum.STATE, states);
1335 hasNotProps.put(GraphPropertyEnum.IS_DELETED, true);
1336 hasNotProps.put(GraphPropertyEnum.IS_ARCHIVED, true);
1337 return fetchServicesByCriteria(services, hasProps, hasNotProps);
1340 private Either<List<Component>, StorageOperationStatus> getLatestVersionNotAbstractToscaElementsMetadataOnly(boolean isAbstract, ComponentTypeEnum componentTypeEnum, String internalComponentType, VertexTypeEnum vertexType) {
1341 List<Service> services = null;
1342 Map<GraphPropertyEnum, Object> hasProps = new EnumMap<>(GraphPropertyEnum.class);
1343 Map<GraphPropertyEnum, Object> hasNotProps = new EnumMap<>(GraphPropertyEnum.class);
1344 fillPropsMap(hasProps, hasNotProps, internalComponentType, componentTypeEnum, isAbstract, vertexType);
1345 Either<List<GraphVertex>, TitanOperationStatus> getRes = titanDao.getByCriteria(vertexType, hasProps, hasNotProps, JsonParseFlagEnum.ParseMetadata);
1346 if (getRes.isRight()) {
1347 if (getRes.right().value().equals(TitanOperationStatus.NOT_FOUND)) {
1348 return Either.left(new ArrayList<>());
1350 return Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(getRes.right().value()));
1353 // region -> Fetch non checked-out services
1354 if (internalComponentType != null && internalComponentType.toLowerCase().trim().equals(SERVICE) && VertexTypeEnum.NODE_TYPE == vertexType) {
1355 Either<List<Service>, StorageOperationStatus> result = getLatestVersionNonCheckoutServicesMetadataOnly(new EnumMap<>(GraphPropertyEnum.class), new EnumMap<>(GraphPropertyEnum.class));
1356 if (result.isRight()) {
1357 log.debug("Failed to fetch services for");
1358 return Either.right(result.right().value());
1360 services = result.left().value();
1361 if (log.isTraceEnabled() && isEmpty(services))
1362 log.trace("No relevant services available");
1365 List<Component> nonAbstractLatestComponents = new ArrayList<>();
1366 ComponentParametersView params = new ComponentParametersView(true);
1367 params.setIgnoreAllVersions(false);
1368 for (GraphVertex vertexComponent : getRes.left().value()) {
1369 Either<ToscaElement, StorageOperationStatus> componentRes = topologyTemplateOperation.getLightComponent(vertexComponent, componentTypeEnum, params);
1370 if (componentRes.isRight()) {
1371 log.debug("Failed to fetch light element for {} error {}", vertexComponent.getUniqueId(), componentRes.right().value());
1372 return Either.right(componentRes.right().value());
1374 Component component = ModelConverter.convertFromToscaElement(componentRes.left().value());
1375 nonAbstractLatestComponents.add(component);
1378 if (CollectionUtils.isNotEmpty(services)) {
1379 nonAbstractLatestComponents.addAll(services);
1381 return Either.left(nonAbstractLatestComponents);
1384 public Either<ComponentMetadataData, StorageOperationStatus> getLatestComponentMetadataByUuid(String componentUuid, JsonParseFlagEnum parseFlag, Boolean isHighest) {
1386 Either<ComponentMetadataData, StorageOperationStatus> result;
1387 Map<GraphPropertyEnum, Object> hasProperties = new EnumMap<>(GraphPropertyEnum.class);
1388 hasProperties.put(GraphPropertyEnum.UUID, componentUuid);
1389 if (isHighest != null) {
1390 hasProperties.put(GraphPropertyEnum.IS_HIGHEST_VERSION, isHighest);
1392 Map<GraphPropertyEnum, Object> propertiesNotToMatch = new EnumMap<>(GraphPropertyEnum.class);
1393 propertiesNotToMatch.put(GraphPropertyEnum.IS_DELETED, true);
1394 propertiesNotToMatch.put(GraphPropertyEnum.IS_ARCHIVED, true); //US382674, US382683
1396 Either<List<GraphVertex>, TitanOperationStatus> getRes = titanDao.getByCriteria(null, hasProperties, propertiesNotToMatch, parseFlag);
1397 if (getRes.isRight()) {
1398 result = Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(getRes.right().value()));
1400 List<ComponentMetadataData> latestVersionList = getRes.left().value().stream().map(ModelConverter::convertToComponentMetadata).collect(Collectors.toList());
1401 ComponentMetadataData latestVersion = latestVersionList.size() == 1 ? latestVersionList.get(0)
1402 : latestVersionList.stream().max((c1, c2) -> Double.compare(Double.parseDouble(c1.getMetadataDataDefinition().getVersion()), Double.parseDouble(c2.getMetadataDataDefinition().getVersion()))).get();
1403 result = Either.left(latestVersion);
1408 public Either<ComponentMetadataData, StorageOperationStatus> getComponentMetadata(String componentId) {
1409 Either<ComponentMetadataData, StorageOperationStatus> result;
1410 Either<GraphVertex, TitanOperationStatus> getRes = titanDao.getVertexById(componentId, JsonParseFlagEnum.ParseMetadata);
1411 if (getRes.isRight()) {
1412 result = Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(getRes.right().value()));
1414 ComponentMetadataData componentMetadata = ModelConverter.convertToComponentMetadata(getRes.left().value());
1415 result = Either.left(componentMetadata);
1420 public Either<List<Component>, StorageOperationStatus> getLatestVersionNotAbstractComponents(boolean isAbstract, ComponentTypeEnum componentTypeEnum,
1421 String internalComponentType, List<String> componentUids) {
1423 List<Component> components = new ArrayList<>();
1424 if (componentUids == null) {
1425 Either<List<String>, StorageOperationStatus> componentUidsRes = getComponentUids(isAbstract, componentTypeEnum, internalComponentType);
1426 if (componentUidsRes.isRight()) {
1427 return Either.right(componentUidsRes.right().value());
1429 componentUids = componentUidsRes.left().value();
1431 if (!isEmpty(componentUids)) {
1432 for (String componentUid : componentUids) {
1433 ComponentParametersView componentParametersView = buildComponentViewForNotAbstract();
1434 if ("vl".equalsIgnoreCase(internalComponentType)) {
1435 componentParametersView.setIgnoreCapabilities(false);
1436 componentParametersView.setIgnoreRequirements(false);
1438 Either<ToscaElement, StorageOperationStatus> getToscaElementRes = nodeTemplateOperation.getToscaElementOperation(componentTypeEnum).getLightComponent(componentUid, componentTypeEnum, componentParametersView);
1439 if (getToscaElementRes.isRight()) {
1440 log.debug("Failed to fetch resource for error is {}", getToscaElementRes.right().value());
1441 return Either.right(getToscaElementRes.right().value());
1443 Component component = ModelConverter.convertFromToscaElement(getToscaElementRes.left().value());
1444 nullifySomeComponentProperties(component);
1445 components.add(component);
1448 return Either.left(components);
1451 public void nullifySomeComponentProperties(Component component) {
1452 component.setContactId(null);
1453 component.setCreationDate(null);
1454 component.setCreatorUserId(null);
1455 component.setCreatorFullName(null);
1456 component.setLastUpdateDate(null);
1457 component.setLastUpdaterUserId(null);
1458 component.setLastUpdaterFullName(null);
1459 component.setNormalizedName(null);
1462 private Either<List<String>, StorageOperationStatus> getComponentUids(boolean isAbstract, ComponentTypeEnum componentTypeEnum, String internalComponentType) {
1464 Either<List<Component>, StorageOperationStatus> getToscaElementsRes = getLatestVersionNotAbstractMetadataOnly(isAbstract, componentTypeEnum, internalComponentType);
1465 if (getToscaElementsRes.isRight()) {
1466 return Either.right(getToscaElementsRes.right().value());
1468 List<Component> collection = getToscaElementsRes.left().value();
1469 List<String> componentUids;
1470 if (collection == null) {
1471 componentUids = new ArrayList<>();
1473 componentUids = collection.stream()
1474 .map(Component::getUniqueId)
1475 .collect(Collectors.toList());
1477 return Either.left(componentUids);
1480 private ComponentParametersView buildComponentViewForNotAbstract() {
1481 ComponentParametersView componentParametersView = new ComponentParametersView();
1482 componentParametersView.disableAll();
1483 componentParametersView.setIgnoreCategories(false);
1484 componentParametersView.setIgnoreAllVersions(false);
1485 return componentParametersView;
1488 public Either<Boolean, StorageOperationStatus> validateComponentNameExists(String name, ResourceTypeEnum resourceType, ComponentTypeEnum componentType) {
1489 Either<Boolean, StorageOperationStatus> result = validateComponentNameUniqueness(name, resourceType, componentType);
1490 if (result.isLeft()) {
1491 result = Either.left(!result.left().value());
1496 public Either<Boolean, StorageOperationStatus> validateComponentNameUniqueness(String name, ResourceTypeEnum resourceType, ComponentTypeEnum componentType) {
1497 VertexTypeEnum vertexType = ModelConverter.isAtomicComponent(resourceType) ? VertexTypeEnum.NODE_TYPE : VertexTypeEnum.TOPOLOGY_TEMPLATE;
1498 String normalizedName = ValidationUtils.normaliseComponentName(name);
1499 Map<GraphPropertyEnum, Object> properties = new EnumMap<>(GraphPropertyEnum.class);
1500 properties.put(GraphPropertyEnum.NORMALIZED_NAME, normalizedName);
1501 properties.put(GraphPropertyEnum.COMPONENT_TYPE, componentType.name());
1503 Either<List<GraphVertex>, TitanOperationStatus> vertexEither = titanDao.getByCriteria(vertexType, properties, JsonParseFlagEnum.NoParse);
1504 if (vertexEither.isRight() && vertexEither.right().value() != TitanOperationStatus.NOT_FOUND) {
1505 log.debug("failed to get vertex from graph with property normalizedName: {}", normalizedName);
1506 return Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(vertexEither.right().value()));
1508 List<GraphVertex> vertexList = vertexEither.isLeft() ? vertexEither.left().value() : null;
1509 if (vertexList != null && !vertexList.isEmpty()) {
1510 return Either.left(false);
1512 return Either.left(true);
1516 private void fillNodeTypePropsMap(Map<GraphPropertyEnum, Object> hasProps, Map<GraphPropertyEnum, Object> hasNotProps, String internalComponentType) {
1517 switch (internalComponentType.toLowerCase()) {
1520 hasNotProps.put(GraphPropertyEnum.RESOURCE_TYPE, Arrays.asList(ResourceTypeEnum.VFCMT.name(), ResourceTypeEnum.Configuration.name()));
1525 hasNotProps.put(GraphPropertyEnum.RESOURCE_TYPE, Arrays.asList(ResourceTypeEnum.VFC.name(), ResourceTypeEnum.VFCMT.name()));
1528 hasProps.put(GraphPropertyEnum.RESOURCE_TYPE, ResourceTypeEnum.VL.name());
1535 private void fillTopologyTemplatePropsMap(Map<GraphPropertyEnum, Object> hasProps, Map<GraphPropertyEnum, Object> hasNotProps, ComponentTypeEnum componentTypeEnum) {
1536 switch (componentTypeEnum) {
1538 hasProps.put(GraphPropertyEnum.COMPONENT_TYPE, ComponentTypeEnum.RESOURCE.name());
1541 hasProps.put(GraphPropertyEnum.COMPONENT_TYPE, ComponentTypeEnum.SERVICE.name());
1546 hasNotProps.put(GraphPropertyEnum.RESOURCE_TYPE, ResourceTypeEnum.CVFC.name());
1549 private void fillPropsMap(Map<GraphPropertyEnum, Object> hasProps, Map<GraphPropertyEnum, Object> hasNotProps, String internalComponentType, ComponentTypeEnum componentTypeEnum, boolean isAbstract, VertexTypeEnum internalVertexType) {
1550 hasNotProps.put(GraphPropertyEnum.STATE, LifecycleStateEnum.NOT_CERTIFIED_CHECKOUT.name());
1552 hasNotProps.put(GraphPropertyEnum.IS_DELETED, true);
1553 hasNotProps.put(GraphPropertyEnum.IS_ARCHIVED, true);
1554 hasProps.put(GraphPropertyEnum.IS_HIGHEST_VERSION, true);
1555 if (VertexTypeEnum.NODE_TYPE == internalVertexType) {
1556 hasProps.put(GraphPropertyEnum.IS_ABSTRACT, isAbstract);
1557 if (internalComponentType != null) {
1558 fillNodeTypePropsMap(hasProps, hasNotProps, internalComponentType);
1561 fillTopologyTemplatePropsMap(hasProps, hasNotProps, componentTypeEnum);
1565 private List<VertexTypeEnum> getInternalVertexTypes(ComponentTypeEnum componentTypeEnum, String internalComponentType) {
1566 List<VertexTypeEnum> internalVertexTypes = new ArrayList<>();
1567 if (ComponentTypeEnum.RESOURCE == componentTypeEnum) {
1568 internalVertexTypes.add(VertexTypeEnum.NODE_TYPE);
1570 if (ComponentTypeEnum.SERVICE == componentTypeEnum || SERVICE.equalsIgnoreCase(internalComponentType)) {
1571 internalVertexTypes.add(VertexTypeEnum.TOPOLOGY_TEMPLATE);
1573 return internalVertexTypes;
1576 public Either<List<Component>, StorageOperationStatus> getLatestVersionNotAbstractMetadataOnly(boolean isAbstract, ComponentTypeEnum componentTypeEnum, String internalComponentType) {
1577 List<VertexTypeEnum> internalVertexTypes = getInternalVertexTypes(componentTypeEnum, internalComponentType);
1578 List<Component> result = new ArrayList<>();
1579 for (VertexTypeEnum vertexType : internalVertexTypes) {
1580 Either<List<Component>, StorageOperationStatus> listByVertexType = getLatestVersionNotAbstractToscaElementsMetadataOnly(isAbstract, componentTypeEnum, internalComponentType, vertexType);
1581 if (listByVertexType.isRight()) {
1582 return listByVertexType;
1584 result.addAll(listByVertexType.left().value());
1586 return Either.left(result);
1590 private Either<List<Component>, StorageOperationStatus> getLatestComponentListByUuid(String componentUuid, Map<GraphPropertyEnum, Object> additionalPropertiesToMatch) {
1591 Map<GraphPropertyEnum, Object> propertiesToMatch = new EnumMap<>(GraphPropertyEnum.class);
1592 if (additionalPropertiesToMatch != null) {
1593 propertiesToMatch.putAll(additionalPropertiesToMatch);
1595 propertiesToMatch.put(GraphPropertyEnum.IS_HIGHEST_VERSION, true);
1596 return getComponentListByUuid(componentUuid, propertiesToMatch);
1599 public Either<Component, StorageOperationStatus> getComponentByUuidAndVersion(String componentUuid, String version) {
1600 Map<GraphPropertyEnum, Object> propertiesToMatch = new EnumMap<>(GraphPropertyEnum.class);
1602 propertiesToMatch.put(GraphPropertyEnum.UUID, componentUuid);
1603 propertiesToMatch.put(GraphPropertyEnum.VERSION, version);
1605 Map<GraphPropertyEnum, Object> propertiesNotToMatch = new EnumMap<>(GraphPropertyEnum.class);
1606 propertiesNotToMatch.put(GraphPropertyEnum.IS_DELETED, true);
1607 Either<List<GraphVertex>, TitanOperationStatus> vertexEither = titanDao.getByCriteria(null, propertiesToMatch, propertiesNotToMatch, JsonParseFlagEnum.ParseAll);
1608 if (vertexEither.isRight()) {
1609 return Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(vertexEither.right().value()));
1612 List<GraphVertex> vertexList = vertexEither.isLeft() ? vertexEither.left().value() : null;
1613 if (vertexList == null || vertexList.isEmpty() || vertexList.size() > 1) {
1614 return Either.right(StorageOperationStatus.NOT_FOUND);
1617 return getToscaElementByOperation(vertexList.get(0));
1620 public Either<List<Component>, StorageOperationStatus> getComponentListByUuid(String componentUuid, Map<GraphPropertyEnum, Object> additionalPropertiesToMatch) {
1622 Map<GraphPropertyEnum, Object> propertiesToMatch = new EnumMap<>(GraphPropertyEnum.class);
1624 if (additionalPropertiesToMatch != null) {
1625 propertiesToMatch.putAll(additionalPropertiesToMatch);
1628 propertiesToMatch.put(GraphPropertyEnum.UUID, componentUuid);
1630 Map<GraphPropertyEnum, Object> propertiesNotToMatch = new EnumMap<>(GraphPropertyEnum.class);
1631 propertiesNotToMatch.put(GraphPropertyEnum.IS_DELETED, true);
1632 propertiesNotToMatch.put(GraphPropertyEnum.IS_ARCHIVED, true); //US382674, US382683
1634 Either<List<GraphVertex>, TitanOperationStatus> vertexEither = titanDao.getByCriteria(null, propertiesToMatch, propertiesNotToMatch, JsonParseFlagEnum.ParseAll);
1636 if (vertexEither.isRight()) {
1637 log.debug("Couldn't fetch metadata for component with uuid {}, error: {}", componentUuid, vertexEither.right().value());
1638 return Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(vertexEither.right().value()));
1640 List<GraphVertex> vertexList = vertexEither.isLeft() ? vertexEither.left().value() : null;
1642 if (vertexList == null || vertexList.isEmpty()) {
1643 log.debug("Component with uuid {} was not found", componentUuid);
1644 return Either.right(StorageOperationStatus.NOT_FOUND);
1647 ArrayList<Component> latestComponents = new ArrayList<>();
1648 for (GraphVertex vertex : vertexList) {
1649 Either<Component, StorageOperationStatus> toscaElementByOperation = getToscaElementByOperation(vertex);
1651 if (toscaElementByOperation.isRight()) {
1652 log.debug("Could not fetch the following Component by UUID {}", vertex.getUniqueId());
1653 return Either.right(toscaElementByOperation.right().value());
1656 latestComponents.add(toscaElementByOperation.left().value());
1659 if (latestComponents.size() > 1) {
1660 for (Component component : latestComponents) {
1661 if (component.isHighestVersion()) {
1662 LinkedList<Component> highestComponent = new LinkedList<>();
1663 highestComponent.add(component);
1664 return Either.left(highestComponent);
1669 return Either.left(latestComponents);
1672 public Either<Component, StorageOperationStatus> getLatestServiceByUuid(String serviceUuid) {
1673 Map<GraphPropertyEnum, Object> propertiesToMatch = new EnumMap<>(GraphPropertyEnum.class);
1674 propertiesToMatch.put(GraphPropertyEnum.COMPONENT_TYPE, ComponentTypeEnum.SERVICE.name());
1675 return getLatestComponentByUuid(serviceUuid, propertiesToMatch);
1678 public Either<Component, StorageOperationStatus> getLatestComponentByUuid(String componentUuid) {
1679 return getLatestComponentByUuid(componentUuid, null);
1682 public Either<Component, StorageOperationStatus> getLatestComponentByUuid(String componentUuid, Map<GraphPropertyEnum, Object> propertiesToMatch) {
1684 Either<List<Component>, StorageOperationStatus> latestVersionListEither = getLatestComponentListByUuid(componentUuid, propertiesToMatch);
1686 if (latestVersionListEither.isRight()) {
1687 return Either.right(latestVersionListEither.right().value());
1690 List<Component> latestVersionList = latestVersionListEither.left().value();
1692 if (latestVersionList.isEmpty()) {
1693 return Either.right(StorageOperationStatus.NOT_FOUND);
1695 Component component = latestVersionList.size() == 1 ? latestVersionList.get(0) : latestVersionList.stream().max((c1, c2) -> Double.compare(Double.parseDouble(c1.getVersion()), Double.parseDouble(c2.getVersion()))).get();
1697 return Either.left(component);
1700 public Either<List<Resource>, StorageOperationStatus> getAllCertifiedResources(boolean isAbstract, Boolean isHighest) {
1702 List<Resource> resources = new ArrayList<>();
1703 Map<GraphPropertyEnum, Object> propertiesToMatch = new EnumMap<>(GraphPropertyEnum.class);
1704 Map<GraphPropertyEnum, Object> propertiesNotToMatch = new EnumMap<>(GraphPropertyEnum.class);
1706 propertiesToMatch.put(GraphPropertyEnum.IS_ABSTRACT, isAbstract);
1707 if (isHighest != null) {
1708 propertiesToMatch.put(GraphPropertyEnum.IS_HIGHEST_VERSION, isHighest);
1710 propertiesToMatch.put(GraphPropertyEnum.STATE, LifecycleStateEnum.CERTIFIED.name());
1711 propertiesToMatch.put(GraphPropertyEnum.COMPONENT_TYPE, ComponentTypeEnum.RESOURCE.name());
1712 propertiesNotToMatch.put(GraphPropertyEnum.IS_DELETED, true);
1714 Either<List<GraphVertex>, TitanOperationStatus> getResourcesRes = titanDao.getByCriteria(null, propertiesToMatch, propertiesNotToMatch, JsonParseFlagEnum.ParseAll);
1716 if (getResourcesRes.isRight()) {
1717 log.debug("Failed to fetch all certified resources. Status is {}", getResourcesRes.right().value());
1718 return Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(getResourcesRes.right().value()));
1720 List<GraphVertex> resourceVerticies = getResourcesRes.left().value();
1721 for (GraphVertex resourceV : resourceVerticies) {
1722 Either<Resource, StorageOperationStatus> getResourceRes = getToscaElement(resourceV);
1723 if (getResourceRes.isRight()) {
1724 return Either.right(getResourceRes.right().value());
1726 resources.add(getResourceRes.left().value());
1728 return Either.left(resources);
1731 public <T extends Component> Either<T, StorageOperationStatus> getLatestByNameAndVersion(String name, String version, JsonParseFlagEnum parseFlag) {
1732 Either<T, StorageOperationStatus> result;
1734 Map<GraphPropertyEnum, Object> hasProperties = new EnumMap<>(GraphPropertyEnum.class);
1735 Map<GraphPropertyEnum, Object> hasNotProperties = new EnumMap<>(GraphPropertyEnum.class);
1737 hasProperties.put(GraphPropertyEnum.NAME, name);
1738 hasProperties.put(GraphPropertyEnum.VERSION, version);
1739 hasProperties.put(GraphPropertyEnum.IS_HIGHEST_VERSION, true);
1741 hasNotProperties.put(GraphPropertyEnum.IS_DELETED, true);
1743 Either<List<GraphVertex>, TitanOperationStatus> getResourceRes = titanDao.getByCriteria(null, hasProperties, hasNotProperties, parseFlag);
1744 if (getResourceRes.isRight()) {
1745 TitanOperationStatus status = getResourceRes.right().value();
1746 log.debug("failed to find resource with name {}, version {}. Status is {} ", name, version, status);
1747 result = Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(status));
1750 return getToscaElementByOperation(getResourceRes.left().value().get(0));
1753 public Either<Resource, StorageOperationStatus> getLatestComponentByCsarOrName(ComponentTypeEnum componentType, String csarUUID, String systemName) {
1754 return getLatestComponentByCsarOrName(componentType, csarUUID, systemName, JsonParseFlagEnum.ParseAll);
1757 public Either<Resource, StorageOperationStatus> getLatestComponentByCsarOrName(ComponentTypeEnum componentType, String csarUUID, String systemName, JsonParseFlagEnum parseFlag) {
1758 Map<GraphPropertyEnum, Object> props = new EnumMap<>(GraphPropertyEnum.class);
1759 Map<GraphPropertyEnum, Object> propsHasNot = new EnumMap<>(GraphPropertyEnum.class);
1760 props.put(GraphPropertyEnum.CSAR_UUID, csarUUID);
1761 props.put(GraphPropertyEnum.IS_HIGHEST_VERSION, true);
1762 if (componentType != null) {
1763 props.put(GraphPropertyEnum.COMPONENT_TYPE, componentType.name());
1765 propsHasNot.put(GraphPropertyEnum.IS_DELETED, true);
1767 GraphVertex resourceMetadataData = null;
1768 List<GraphVertex> resourceMetadataDataList = null;
1769 Either<List<GraphVertex>, TitanOperationStatus> byCsar = titanDao.getByCriteria(null, props, propsHasNot, JsonParseFlagEnum.ParseMetadata);
1770 if (byCsar.isRight()) {
1771 if (TitanOperationStatus.NOT_FOUND == byCsar.right().value()) {
1772 // Fix Defect DE256036
1773 if (StringUtils.isEmpty(systemName)) {
1774 return Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(TitanOperationStatus.NOT_FOUND));
1778 props.put(GraphPropertyEnum.IS_HIGHEST_VERSION, true);
1779 props.put(GraphPropertyEnum.SYSTEM_NAME, systemName);
1780 Either<List<GraphVertex>, TitanOperationStatus> bySystemname = titanDao.getByCriteria(null, props, JsonParseFlagEnum.ParseMetadata);
1781 if (bySystemname.isRight()) {
1782 log.debug("getLatestResourceByCsarOrName - Failed to find by system name {} error {} ", systemName, bySystemname.right().value());
1783 return Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(bySystemname.right().value()));
1785 if (bySystemname.left().value().size() > 2) {
1786 log.debug("getLatestResourceByCsarOrName - getByCriteria(by system name) must return only 2 latest version, but was returned - {}", bySystemname.left().value().size());
1787 return Either.right(StorageOperationStatus.GENERAL_ERROR);
1789 resourceMetadataDataList = bySystemname.left().value();
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 system name) returned 2 latest CERTIFIED versions");
1802 return Either.right(StorageOperationStatus.GENERAL_ERROR);
1804 if (resourceMetadataData.getJsonMetadataField(JsonPresentationFields.CSAR_UUID) != null && !((String) resourceMetadataData.getJsonMetadataField(JsonPresentationFields.CSAR_UUID)).equals(csarUUID)) {
1805 log.debug("getLatestResourceByCsarOrName - same system name {} but different csarUUID. exist {} and new {} ", systemName, resourceMetadataData.getJsonMetadataField(JsonPresentationFields.CSAR_UUID), csarUUID);
1806 // correct error will be returned from create flow. with all
1807 // correct audit records!!!!!
1808 return Either.right(StorageOperationStatus.NOT_FOUND);
1810 return getToscaElement((String) resourceMetadataData.getUniqueId());
1813 resourceMetadataDataList = byCsar.left().value();
1814 if (resourceMetadataDataList.size() > 2) {
1815 log.debug("getLatestResourceByCsarOrName - getByCriteria(by csar) must return only 2 latest version, but was returned - {}", byCsar.left().value().size());
1816 return Either.right(StorageOperationStatus.GENERAL_ERROR);
1818 if (resourceMetadataDataList.size() == 1) {
1819 resourceMetadataData = resourceMetadataDataList.get(0);
1821 for (GraphVertex curResource : resourceMetadataDataList) {
1822 if (!((String) curResource.getJsonMetadataField(JsonPresentationFields.LIFECYCLE_STATE)).equals("CERTIFIED")) {
1823 resourceMetadataData = curResource;
1828 if (resourceMetadataData == null) {
1829 log.debug("getLatestResourceByCsarOrName - getByCriteria(by csar) returned 2 latest CERTIFIED versions");
1830 return Either.right(StorageOperationStatus.GENERAL_ERROR);
1832 return getToscaElement((String) resourceMetadataData.getJsonMetadataField(JsonPresentationFields.UNIQUE_ID), parseFlag);
1837 public Either<Boolean, StorageOperationStatus> validateToscaResourceNameExtends(String templateNameCurrent, String templateNameExtends) {
1839 String currentTemplateNameChecked = templateNameExtends;
1841 while (currentTemplateNameChecked != null && !currentTemplateNameChecked.equalsIgnoreCase(templateNameCurrent)) {
1842 Either<Resource, StorageOperationStatus> latestByToscaResourceName = getLatestByToscaResourceName(currentTemplateNameChecked);
1844 if (latestByToscaResourceName.isRight()) {
1845 return latestByToscaResourceName.right().value() == StorageOperationStatus.NOT_FOUND ? Either.left(false) : Either.right(latestByToscaResourceName.right().value());
1848 Resource value = latestByToscaResourceName.left().value();
1850 if (value.getDerivedFrom() != null) {
1851 currentTemplateNameChecked = value.getDerivedFrom().get(0);
1853 currentTemplateNameChecked = null;
1857 return (currentTemplateNameChecked != null && currentTemplateNameChecked.equalsIgnoreCase(templateNameCurrent)) ? Either.left(true) : Either.left(false);
1860 public Either<List<Component>, StorageOperationStatus> fetchMetaDataByResourceType(String resourceType, ComponentParametersView filterBy) {
1861 Map<GraphPropertyEnum, Object> props = new EnumMap<>(GraphPropertyEnum.class);
1862 props.put(GraphPropertyEnum.RESOURCE_TYPE, resourceType);
1863 props.put(GraphPropertyEnum.IS_HIGHEST_VERSION, true);
1864 Map<GraphPropertyEnum, Object> propsHasNotToMatch = new EnumMap<>(GraphPropertyEnum.class);
1865 propsHasNotToMatch.put(GraphPropertyEnum.IS_DELETED, true);
1866 Either<List<GraphVertex>, TitanOperationStatus> resourcesByTypeEither = titanDao.getByCriteria(null, props, propsHasNotToMatch, JsonParseFlagEnum.ParseMetadata);
1868 if (resourcesByTypeEither.isRight()) {
1869 return Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(resourcesByTypeEither.right().value()));
1872 List<GraphVertex> vertexList = resourcesByTypeEither.left().value();
1873 List<Component> components = new ArrayList<>();
1875 for (GraphVertex vertex : vertexList) {
1876 components.add(getToscaElementByOperation(vertex, filterBy).left().value());
1879 return Either.left(components);
1882 public void commit() {
1886 public Either<Service, StorageOperationStatus> updateDistributionStatus(Service service, User user, DistributionStatusEnum distributionStatus) {
1887 Either<GraphVertex, StorageOperationStatus> updateDistributionStatus = topologyTemplateOperation.updateDistributionStatus(service.getUniqueId(), user, distributionStatus);
1888 if (updateDistributionStatus.isRight()) {
1889 return Either.right(updateDistributionStatus.right().value());
1891 GraphVertex serviceV = updateDistributionStatus.left().value();
1892 service.setDistributionStatus(distributionStatus);
1893 service.setLastUpdateDate((Long) serviceV.getJsonMetadataField(JsonPresentationFields.LAST_UPDATE_DATE));
1894 return Either.left(service);
1897 public Either<ComponentMetadataData, StorageOperationStatus> updateComponentLastUpdateDateOnGraph(Component component) {
1899 Either<ComponentMetadataData, StorageOperationStatus> result = null;
1900 GraphVertex serviceVertex;
1901 Either<GraphVertex, TitanOperationStatus> updateRes = null;
1902 Either<GraphVertex, TitanOperationStatus> getRes = titanDao.getVertexById(component.getUniqueId(), JsonParseFlagEnum.ParseMetadata);
1903 if (getRes.isRight()) {
1904 TitanOperationStatus status = getRes.right().value();
1905 log.error("Failed to fetch component {}. status is {}", component.getUniqueId(), status);
1906 result = Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(status));
1908 if (result == null) {
1909 serviceVertex = getRes.left().value();
1910 long lastUpdateDate = System.currentTimeMillis();
1911 serviceVertex.setJsonMetadataField(JsonPresentationFields.LAST_UPDATE_DATE, lastUpdateDate);
1912 component.setLastUpdateDate(lastUpdateDate);
1913 updateRes = titanDao.updateVertex(serviceVertex);
1914 if (updateRes.isRight()) {
1915 result = Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(updateRes.right().value()));
1918 if (result == null) {
1919 result = Either.left(ModelConverter.convertToComponentMetadata(updateRes.left().value()));
1924 public TitanDao getTitanDao() {
1928 public Either<List<Service>, StorageOperationStatus> getCertifiedServicesWithDistStatus(Set<DistributionStatusEnum> distStatus) {
1929 Map<GraphPropertyEnum, Object> propertiesToMatch = new EnumMap<>(GraphPropertyEnum.class);
1930 propertiesToMatch.put(GraphPropertyEnum.STATE, LifecycleStateEnum.CERTIFIED.name());
1932 return getServicesWithDistStatus(distStatus, propertiesToMatch);
1935 public Either<List<Service>, StorageOperationStatus> getServicesWithDistStatus(Set<DistributionStatusEnum> distStatus, Map<GraphPropertyEnum, Object> additionalPropertiesToMatch) {
1937 List<Service> servicesAll = new ArrayList<>();
1939 Map<GraphPropertyEnum, Object> propertiesToMatch = new EnumMap<>(GraphPropertyEnum.class);
1940 Map<GraphPropertyEnum, Object> propertiesNotToMatch = new EnumMap<>(GraphPropertyEnum.class);
1942 if (additionalPropertiesToMatch != null && !additionalPropertiesToMatch.isEmpty()) {
1943 propertiesToMatch.putAll(additionalPropertiesToMatch);
1946 propertiesToMatch.put(GraphPropertyEnum.COMPONENT_TYPE, ComponentTypeEnum.SERVICE.name());
1948 propertiesNotToMatch.put(GraphPropertyEnum.IS_DELETED, true);
1950 if (distStatus != null && !distStatus.isEmpty()) {
1951 for (DistributionStatusEnum state : distStatus) {
1952 propertiesToMatch.put(GraphPropertyEnum.DISTRIBUTION_STATUS, state.name());
1953 Either<List<Service>, StorageOperationStatus> fetchServicesByCriteria = fetchServicesByCriteria(servicesAll, propertiesToMatch, propertiesNotToMatch);
1954 if (fetchServicesByCriteria.isRight()) {
1955 return fetchServicesByCriteria;
1957 servicesAll = fetchServicesByCriteria.left().value();
1960 return Either.left(servicesAll);
1962 return fetchServicesByCriteria(servicesAll, propertiesToMatch, propertiesNotToMatch);
1966 private Either<List<Service>, StorageOperationStatus> fetchServicesByCriteria(List<Service> servicesAll, Map<GraphPropertyEnum, Object> propertiesToMatch, Map<GraphPropertyEnum, Object> propertiesNotToMatch) {
1967 Either<List<GraphVertex>, TitanOperationStatus> getRes = titanDao.getByCriteria(VertexTypeEnum.TOPOLOGY_TEMPLATE, propertiesToMatch, propertiesNotToMatch, JsonParseFlagEnum.ParseAll);
1968 if (getRes.isRight()) {
1969 if (getRes.right().value() != TitanOperationStatus.NOT_FOUND) {
1970 CommonUtility.addRecordToLog(log, LogLevelEnum.DEBUG, "Failed to fetch certified services by match properties {} not match properties {} . Status is {}. ", propertiesToMatch, propertiesNotToMatch, getRes.right().value());
1971 return Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(getRes.right().value()));
1974 for (GraphVertex vertex : getRes.left().value()) {
1975 Either<ToscaElement, StorageOperationStatus> getServiceRes = topologyTemplateOperation.getLightComponent(vertex, ComponentTypeEnum.SERVICE, new ComponentParametersView(true));
1977 if (getServiceRes.isRight()) {
1978 CommonUtility.addRecordToLog(log, LogLevelEnum.DEBUG, "Failed to fetch certified service {}. Status is {}. ", vertex.getJsonMetadataField(JsonPresentationFields.NAME), getServiceRes.right().value());
1979 return Either.right(getServiceRes.right().value());
1981 servicesAll.add(ModelConverter.convertFromToscaElement(getServiceRes.left().value()));
1985 return Either.left(servicesAll);
1988 public void rollback() {
1989 titanDao.rollback();
1992 public StorageOperationStatus addDeploymentArtifactsToInstance(String componentId, ComponentInstance componentInstance, Map<String, ArtifactDefinition> finalDeploymentArtifacts) {
1993 Map<String, ArtifactDataDefinition> instDeplArtifacts = finalDeploymentArtifacts.entrySet().stream().collect(Collectors.toMap(Map.Entry::getKey, e -> new ArtifactDataDefinition(e.getValue())));
1995 return nodeTemplateOperation.addDeploymentArtifactsToInstance(componentId, componentInstance.getUniqueId(), instDeplArtifacts);
1998 public StorageOperationStatus addInformationalArtifactsToInstance(String componentId, ComponentInstance componentInstance, Map<String, ArtifactDefinition> artifacts) {
1999 StorageOperationStatus status = StorageOperationStatus.OK;
2000 if (MapUtils.isNotEmpty(artifacts)) {
2001 Map<String, ArtifactDataDefinition> instDeplArtifacts = artifacts.entrySet().stream().collect(Collectors.toMap(Map.Entry::getKey, e -> new ArtifactDataDefinition(e.getValue())));
2002 status = nodeTemplateOperation.addInformationalArtifactsToInstance(componentId, componentInstance.getUniqueId(), instDeplArtifacts);
2007 public StorageOperationStatus generateCustomizationUUIDOnInstance(String componentId, String instanceId) {
2008 return nodeTemplateOperation.generateCustomizationUUIDOnInstance(componentId, instanceId);
2011 public StorageOperationStatus generateCustomizationUUIDOnInstanceGroup(String componentId, String instanceId, List<String> groupInstances) {
2012 return nodeTemplateOperation.generateCustomizationUUIDOnInstanceGroup(componentId, instanceId, groupInstances);
2015 public Either<PropertyDefinition, StorageOperationStatus> addPropertyToComponent(String propertyName,
2016 PropertyDefinition newPropertyDefinition,
2017 Component component) {
2019 Either<PropertyDefinition, StorageOperationStatus> result = null;
2020 Either<Component, StorageOperationStatus> getUpdatedComponentRes = null;
2021 newPropertyDefinition.setName(propertyName);
2023 StorageOperationStatus status = getToscaElementOperation(component)
2024 .addToscaDataToToscaElement(component.getUniqueId(), EdgeLabelEnum.PROPERTIES, VertexTypeEnum.PROPERTIES, newPropertyDefinition, JsonPresentationFields.NAME);
2025 if (status != StorageOperationStatus.OK) {
2026 CommonUtility.addRecordToLog(log, LogLevelEnum.DEBUG, "Failed to add the property {} to the component {}. Status is {}. ", propertyName, component.getName(), status);
2027 result = Either.right(status);
2029 if (result == null) {
2030 ComponentParametersView filter = new ComponentParametersView(true);
2031 filter.setIgnoreProperties(false);
2032 filter.setIgnoreInputs(false);
2033 getUpdatedComponentRes = getToscaElement(component.getUniqueId(), filter);
2034 if (getUpdatedComponentRes.isRight()) {
2035 CommonUtility.addRecordToLog(log, LogLevelEnum.DEBUG, "Failed to get updated component {}. Status is {}. ", component.getUniqueId(), getUpdatedComponentRes.right().value());
2036 result = Either.right(status);
2039 if (result == null) {
2040 PropertyDefinition newProperty = null;
2041 List<PropertyDefinition> properties =
2042 (getUpdatedComponentRes.left().value()).getProperties();
2043 if (CollectionUtils.isNotEmpty(properties)) {
2044 Optional<PropertyDefinition> propertyOptional = properties.stream().filter(
2045 propertyEntry -> propertyEntry.getName().equals(propertyName)).findAny();
2046 if (propertyOptional.isPresent()) {
2047 newProperty = propertyOptional.get();
2050 if (newProperty == null) {
2051 CommonUtility.addRecordToLog(log, LogLevelEnum.DEBUG, "Failed to find recently added property {} on the component {}. Status is {}. ", propertyName, component.getUniqueId(), StorageOperationStatus.NOT_FOUND);
2052 result = Either.right(StorageOperationStatus.NOT_FOUND);
2054 result = Either.left(newProperty);
2059 public StorageOperationStatus deletePropertyOfComponent(Component component, String propertyName) {
2060 return getToscaElementOperation(component).deleteToscaDataElement(component.getUniqueId(), EdgeLabelEnum.PROPERTIES, VertexTypeEnum.PROPERTIES, propertyName, JsonPresentationFields.NAME);
2063 public StorageOperationStatus deleteAttributeOfResource(Component component, String attributeName) {
2064 return getToscaElementOperation(component).deleteToscaDataElement(component.getUniqueId(), EdgeLabelEnum.ATTRIBUTES, VertexTypeEnum.ATTRIBUTES, attributeName, JsonPresentationFields.NAME);
2067 public StorageOperationStatus deleteInputOfResource(Component resource, String inputName) {
2068 return getToscaElementOperation(resource).deleteToscaDataElement(resource.getUniqueId(), EdgeLabelEnum.INPUTS, VertexTypeEnum.INPUTS, inputName, JsonPresentationFields.NAME);
2071 public Either<PropertyDefinition, StorageOperationStatus> updatePropertyOfComponent(Component component,
2072 PropertyDefinition newPropertyDefinition) {
2074 Either<Component, StorageOperationStatus> getUpdatedComponentRes = null;
2075 Either<PropertyDefinition, StorageOperationStatus> result = null;
2076 StorageOperationStatus status = getToscaElementOperation(component).updateToscaDataOfToscaElement(component.getUniqueId(), EdgeLabelEnum.PROPERTIES, VertexTypeEnum.PROPERTIES, newPropertyDefinition, JsonPresentationFields.NAME);
2077 if (status != StorageOperationStatus.OK) {
2078 CommonUtility.addRecordToLog(log, LogLevelEnum.DEBUG, "Failed to add the property {} to the resource {}. Status is {}. ", newPropertyDefinition.getName(), component.getName(), status);
2079 result = Either.right(status);
2081 if (result == null) {
2082 ComponentParametersView filter = new ComponentParametersView(true);
2083 filter.setIgnoreProperties(false);
2084 getUpdatedComponentRes = getToscaElement(component.getUniqueId(), filter);
2085 if (getUpdatedComponentRes.isRight()) {
2086 CommonUtility.addRecordToLog(log, LogLevelEnum.DEBUG, "Failed to get updated resource {}. Status is {}. ", component.getUniqueId(), getUpdatedComponentRes.right().value());
2087 result = Either.right(status);
2090 if (result == null) {
2091 Optional<PropertyDefinition> newProperty = (getUpdatedComponentRes.left().value())
2092 .getProperties().stream().filter(p -> p.getName().equals(newPropertyDefinition.getName())).findAny();
2093 if (newProperty.isPresent()) {
2094 result = Either.left(newProperty.get());
2096 CommonUtility.addRecordToLog(log, LogLevelEnum.DEBUG, "Failed to find recently added property {} on the resource {}. Status is {}. ", newPropertyDefinition.getName(), component.getUniqueId(), StorageOperationStatus.NOT_FOUND);
2097 result = Either.right(StorageOperationStatus.NOT_FOUND);
2105 public Either<PropertyDefinition, StorageOperationStatus> addAttributeOfResource(Component component, PropertyDefinition newAttributeDef) {
2107 Either<Component, StorageOperationStatus> getUpdatedComponentRes = null;
2108 Either<PropertyDefinition, StorageOperationStatus> result = null;
2109 if (newAttributeDef.getUniqueId() == null || newAttributeDef.getUniqueId().isEmpty()) {
2110 String attUniqueId = UniqueIdBuilder.buildAttributeUid(component.getUniqueId(), newAttributeDef.getName());
2111 newAttributeDef.setUniqueId(attUniqueId);
2114 StorageOperationStatus status = getToscaElementOperation(component).addToscaDataToToscaElement(component.getUniqueId(), EdgeLabelEnum.ATTRIBUTES, VertexTypeEnum.ATTRIBUTES, newAttributeDef, JsonPresentationFields.NAME);
2115 if (status != StorageOperationStatus.OK) {
2116 CommonUtility.addRecordToLog(log, LogLevelEnum.DEBUG, FAILED_TO_ADD_THE_PROPERTY_TO_THE_RESOURCE_STATUS_IS, newAttributeDef.getName(), component.getName(), status);
2117 result = Either.right(status);
2119 if (result == null) {
2120 ComponentParametersView filter = new ComponentParametersView(true);
2121 filter.setIgnoreAttributesFrom(false);
2122 getUpdatedComponentRes = getToscaElement(component.getUniqueId(), filter);
2123 if (getUpdatedComponentRes.isRight()) {
2124 CommonUtility.addRecordToLog(log, LogLevelEnum.DEBUG, FAILED_TO_GET_UPDATED_RESOURCE_STATUS_IS, component.getUniqueId(), getUpdatedComponentRes.right().value());
2125 result = Either.right(status);
2128 if (result == null) {
2129 Optional<PropertyDefinition> newAttribute = ((Resource) getUpdatedComponentRes.left().value()).getAttributes().stream().filter(p -> p.getName().equals(newAttributeDef.getName())).findAny();
2130 if (newAttribute.isPresent()) {
2131 result = Either.left(newAttribute.get());
2133 CommonUtility.addRecordToLog(log, LogLevelEnum.DEBUG, FAILED_TO_FIND_RECENTLY_ADDED_PROPERTY_ON_THE_RESOURCE_STATUS_IS, newAttributeDef.getName(), component.getUniqueId(), StorageOperationStatus.NOT_FOUND);
2134 result = Either.right(StorageOperationStatus.NOT_FOUND);
2140 public Either<PropertyDefinition, StorageOperationStatus> updateAttributeOfResource(Component component, PropertyDefinition newAttributeDef) {
2142 Either<Component, StorageOperationStatus> getUpdatedComponentRes = null;
2143 Either<PropertyDefinition, StorageOperationStatus> result = null;
2144 StorageOperationStatus status = getToscaElementOperation(component).updateToscaDataOfToscaElement(component.getUniqueId(), EdgeLabelEnum.ATTRIBUTES, VertexTypeEnum.ATTRIBUTES, newAttributeDef, JsonPresentationFields.NAME);
2145 if (status != StorageOperationStatus.OK) {
2146 CommonUtility.addRecordToLog(log, LogLevelEnum.DEBUG, FAILED_TO_ADD_THE_PROPERTY_TO_THE_RESOURCE_STATUS_IS, newAttributeDef.getName(), component.getName(), status);
2147 result = Either.right(status);
2149 if (result == null) {
2150 ComponentParametersView filter = new ComponentParametersView(true);
2151 filter.setIgnoreAttributesFrom(false);
2152 getUpdatedComponentRes = getToscaElement(component.getUniqueId(), filter);
2153 if (getUpdatedComponentRes.isRight()) {
2154 CommonUtility.addRecordToLog(log, LogLevelEnum.DEBUG, FAILED_TO_GET_UPDATED_RESOURCE_STATUS_IS, component.getUniqueId(), getUpdatedComponentRes.right().value());
2155 result = Either.right(status);
2158 if (result == null) {
2159 Optional<PropertyDefinition> newProperty = ((Resource) getUpdatedComponentRes.left().value()).getAttributes().stream().filter(p -> p.getName().equals(newAttributeDef.getName())).findAny();
2160 if (newProperty.isPresent()) {
2161 result = Either.left(newProperty.get());
2163 CommonUtility.addRecordToLog(log, LogLevelEnum.DEBUG, FAILED_TO_FIND_RECENTLY_ADDED_PROPERTY_ON_THE_RESOURCE_STATUS_IS, newAttributeDef.getName(), component.getUniqueId(), StorageOperationStatus.NOT_FOUND);
2164 result = Either.right(StorageOperationStatus.NOT_FOUND);
2170 public Either<InputDefinition, StorageOperationStatus> updateInputOfComponent(Component component, InputDefinition newInputDefinition) {
2172 Either<Component, StorageOperationStatus> getUpdatedComponentRes = null;
2173 Either<InputDefinition, StorageOperationStatus> result = null;
2174 StorageOperationStatus status = getToscaElementOperation(component).updateToscaDataOfToscaElement(component.getUniqueId(), EdgeLabelEnum.INPUTS, VertexTypeEnum.INPUTS, newInputDefinition, JsonPresentationFields.NAME);
2175 if (status != StorageOperationStatus.OK) {
2176 CommonUtility.addRecordToLog(log, LogLevelEnum.DEBUG, "Failed to update the input {} to the component {}. Status is {}. ", newInputDefinition.getName(), component.getName(), status);
2177 result = Either.right(status);
2179 if (result == null) {
2180 ComponentParametersView filter = new ComponentParametersView(true);
2181 filter.setIgnoreInputs(false);
2182 getUpdatedComponentRes = getToscaElement(component.getUniqueId(), filter);
2183 if (getUpdatedComponentRes.isRight()) {
2184 CommonUtility.addRecordToLog(log, LogLevelEnum.DEBUG, FAILED_TO_GET_UPDATED_RESOURCE_STATUS_IS, component.getUniqueId(), getUpdatedComponentRes.right().value());
2185 result = Either.right(status);
2188 if (result == null) {
2189 Optional<InputDefinition> updatedInput = getUpdatedComponentRes.left().value().getInputs().stream().filter(p -> p.getName().equals(newInputDefinition.getName())).findAny();
2190 if (updatedInput.isPresent()) {
2191 result = Either.left(updatedInput.get());
2193 CommonUtility.addRecordToLog(log, LogLevelEnum.DEBUG, "Failed to find recently updated inputs {} on the resource {}. Status is {}. ", newInputDefinition.getName(), component.getUniqueId(), StorageOperationStatus.NOT_FOUND);
2194 result = Either.right(StorageOperationStatus.NOT_FOUND);
2201 * method - ename the group instances after referenced container name renamed flow - VF rename -(triggers)-> Group rename
2203 * @param containerComponent - container such as service
2204 * @param componentInstance - context component
2205 * @param componentInstanceId - id
2206 * @return - successfull/failed status
2208 public Either<StorageOperationStatus, StorageOperationStatus> cleanAndAddGroupInstancesToComponentInstance(Component containerComponent, ComponentInstance componentInstance, String componentInstanceId) {
2209 String uniqueId = componentInstance.getUniqueId();
2210 StorageOperationStatus status = nodeTemplateOperation.deleteToscaDataDeepElementsBlockOfToscaElement(containerComponent.getUniqueId(), EdgeLabelEnum.INST_GROUPS, VertexTypeEnum.INST_GROUPS, uniqueId);
2211 if (status != StorageOperationStatus.OK && status != StorageOperationStatus.NOT_FOUND) {
2212 CommonUtility.addRecordToLog(log, LogLevelEnum.DEBUG, "Failed to delete group instances for container {}. error {] ", componentInstanceId, status);
2213 return Either.right(status);
2215 if (componentInstance.getGroupInstances() != null) {
2216 status = addGroupInstancesToComponentInstance(containerComponent, componentInstance, componentInstance.getGroupInstances());
2217 if (status != StorageOperationStatus.OK && status != StorageOperationStatus.NOT_FOUND) {
2218 CommonUtility.addRecordToLog(log, LogLevelEnum.DEBUG, "Failed to add group instances for container {}. error {] ", componentInstanceId, status);
2219 return Either.right(status);
2222 return Either.left(status);
2225 public StorageOperationStatus addGroupInstancesToComponentInstance(Component containerComponent, ComponentInstance componentInstance, List<GroupDefinition> groups, Map<String, List<ArtifactDefinition>> groupInstancesArtifacts) {
2226 return nodeTemplateOperation.addGroupInstancesToComponentInstance(containerComponent, componentInstance, groups, groupInstancesArtifacts);
2229 public Either<List<GroupDefinition>, StorageOperationStatus> updateGroupsOnComponent(Component component, List<GroupDataDefinition> updatedGroups) {
2230 return groupsOperation.updateGroups(component, updatedGroups, true);
2233 public Either<List<GroupInstance>, StorageOperationStatus> updateGroupInstancesOnComponent(Component component, String instanceId, List<GroupInstance> updatedGroupInstances) {
2234 return groupsOperation.updateGroupInstances(component, instanceId, updatedGroupInstances);
2237 public StorageOperationStatus addGroupInstancesToComponentInstance(Component containerComponent, ComponentInstance componentInstance, List<GroupInstance> groupInstances) {
2238 return nodeTemplateOperation.addGroupInstancesToComponentInstance(containerComponent, componentInstance, groupInstances);
2241 public StorageOperationStatus addDeploymentArtifactsToComponentInstance(Component containerComponent, ComponentInstance componentInstance, Map<String, ArtifactDefinition> deploymentArtifacts) {
2242 return nodeTemplateOperation.addDeploymentArtifactsToComponentInstance(containerComponent, componentInstance, deploymentArtifacts);
2245 public StorageOperationStatus updateComponentInstanceProperty(Component containerComponent, String componentInstanceId, ComponentInstanceProperty property) {
2246 return nodeTemplateOperation.updateComponentInstanceProperty(containerComponent, componentInstanceId, property);
2249 public StorageOperationStatus updateComponentInstanceProperties(Component containerComponent, String componentInstanceId, List<ComponentInstanceProperty> properties) {
2250 return nodeTemplateOperation.updateComponentInstanceProperties(containerComponent, componentInstanceId, properties);
2254 public StorageOperationStatus addComponentInstanceProperty(Component containerComponent, String componentInstanceId, ComponentInstanceProperty property) {
2255 return nodeTemplateOperation.addComponentInstanceProperty(containerComponent, componentInstanceId, property);
2258 public StorageOperationStatus updateComponentInstanceAttribute(Component containerComponent, String componentInstanceId, ComponentInstanceProperty property){
2259 return nodeTemplateOperation.updateComponentInstanceAttribute(containerComponent, componentInstanceId, property);
2262 public StorageOperationStatus addComponentInstanceAttribute(Component containerComponent, String componentInstanceId, ComponentInstanceProperty property){
2263 return nodeTemplateOperation.addComponentInstanceAttribute(containerComponent, componentInstanceId, property);
2266 public StorageOperationStatus updateComponentInstanceInput(Component containerComponent, String componentInstanceId, ComponentInstanceInput property) {
2267 return nodeTemplateOperation.updateComponentInstanceInput(containerComponent, componentInstanceId, property);
2270 public StorageOperationStatus updateComponentInstanceInputs(Component containerComponent, String componentInstanceId, List<ComponentInstanceInput> instanceInputs) {
2271 return nodeTemplateOperation.updateComponentInstanceInputs(containerComponent, componentInstanceId, instanceInputs);
2274 public StorageOperationStatus addComponentInstanceInput(Component containerComponent, String componentInstanceId, ComponentInstanceInput property) {
2275 return nodeTemplateOperation.addComponentInstanceInput(containerComponent, componentInstanceId, property);
2278 public void setNodeTypeOperation(NodeTypeOperation nodeTypeOperation) {
2279 this.nodeTypeOperation = nodeTypeOperation;
2282 public void setTopologyTemplateOperation(TopologyTemplateOperation topologyTemplateOperation) {
2283 this.topologyTemplateOperation = topologyTemplateOperation;
2286 public StorageOperationStatus deleteComponentInstanceInputsFromTopologyTemplate(Component containerComponent, List<InputDefinition> inputsToDelete) {
2287 return topologyTemplateOperation.deleteToscaDataElements(containerComponent.getUniqueId(), EdgeLabelEnum.INPUTS, inputsToDelete.stream().map(PropertyDataDefinition::getName).collect(Collectors.toList()));
2290 public StorageOperationStatus updateComponentInstanceCapabiltyProperty(Component containerComponent, String componentInstanceUniqueId, String capabilityUniqueId, ComponentInstanceProperty property) {
2291 return nodeTemplateOperation.updateComponentInstanceCapabilityProperty(containerComponent, componentInstanceUniqueId, capabilityUniqueId, property);
2294 public StorageOperationStatus updateComponentInstanceCapabilityProperties(Component containerComponent, String componentInstanceUniqueId) {
2295 return convertComponentInstanceProperties(containerComponent, componentInstanceUniqueId)
2296 .map(instanceCapProps -> topologyTemplateOperation.updateComponentInstanceCapabilityProperties(containerComponent, componentInstanceUniqueId, instanceCapProps))
2297 .orElse(StorageOperationStatus.NOT_FOUND);
2300 public StorageOperationStatus updateComponentInstanceInterfaces(Component containerComponent, String componentInstanceUniqueId) {
2301 MapInterfaceDataDefinition mapInterfaceDataDefinition =
2302 convertComponentInstanceInterfaces(containerComponent, componentInstanceUniqueId);
2303 return topologyTemplateOperation
2304 .updateComponentInstanceInterfaces(containerComponent, componentInstanceUniqueId, mapInterfaceDataDefinition);
2307 public StorageOperationStatus updateComponentCalculatedCapabilitiesProperties(Component containerComponent) {
2308 Map<String, MapCapabilityProperty> mapCapabiltyPropertyMap =
2309 convertComponentCapabilitiesProperties(containerComponent);
2310 return nodeTemplateOperation.overrideComponentCapabilitiesProperties(containerComponent, mapCapabiltyPropertyMap);
2313 public StorageOperationStatus deleteAllCalculatedCapabilitiesRequirements(String topologyTemplateId) {
2314 StorageOperationStatus status = topologyTemplateOperation.removeToscaData(topologyTemplateId, EdgeLabelEnum.CALCULATED_CAPABILITIES, VertexTypeEnum.CALCULATED_CAPABILITIES);
2315 if (status == StorageOperationStatus.OK) {
2316 status = topologyTemplateOperation.removeToscaData(topologyTemplateId, EdgeLabelEnum.CALCULATED_REQUIREMENTS, VertexTypeEnum.CALCULATED_REQUIREMENTS);
2318 if (status == StorageOperationStatus.OK) {
2319 status = topologyTemplateOperation.removeToscaData(topologyTemplateId, EdgeLabelEnum.CALCULATED_CAP_PROPERTIES, VertexTypeEnum.CALCULATED_CAP_PROPERTIES);
2324 public Either<Component, StorageOperationStatus> shouldUpgradeToLatestDerived(Resource clonedResource) {
2325 String componentId = clonedResource.getUniqueId();
2326 Either<GraphVertex, TitanOperationStatus> getVertexEither = titanDao.getVertexById(componentId, JsonParseFlagEnum.NoParse);
2327 if (getVertexEither.isRight()) {
2328 log.debug(COULDNT_FETCH_COMPONENT_WITH_AND_UNIQUE_ID_ERROR, componentId, getVertexEither.right().value());
2329 return Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(getVertexEither.right().value()));
2332 GraphVertex nodeTypeV = getVertexEither.left().value();
2334 ToscaElement toscaElementToUpdate = ModelConverter.convertToToscaElement(clonedResource);
2336 Either<ToscaElement, StorageOperationStatus> shouldUpdateDerivedVersion = nodeTypeOperation.shouldUpdateDerivedVersion(toscaElementToUpdate, nodeTypeV);
2337 if (shouldUpdateDerivedVersion.isRight() && StorageOperationStatus.OK != shouldUpdateDerivedVersion.right().value()) {
2338 log.debug("Failed to update derived version for node type {} derived {}, error: {}", componentId, clonedResource.getDerivedFrom().get(0), shouldUpdateDerivedVersion.right().value());
2339 return Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(getVertexEither.right().value()));
2341 if (shouldUpdateDerivedVersion.isLeft()) {
2342 return Either.left(ModelConverter.convertFromToscaElement(shouldUpdateDerivedVersion.left().value()));
2344 return Either.left(clonedResource);
2348 * Returns list of ComponentInstanceProperty belonging to component instance capability specified by name, type and ownerId
2350 public Either<List<ComponentInstanceProperty>, StorageOperationStatus> getComponentInstanceCapabilityProperties(String componentId, String instanceId, String capabilityName, String capabilityType, String ownerId) {
2351 return topologyTemplateOperation.getComponentInstanceCapabilityProperties(componentId, instanceId, capabilityName, capabilityType, ownerId);
2354 private MapInterfaceDataDefinition convertComponentInstanceInterfaces(Component currComponent,
2355 String componentInstanceId) {
2356 MapInterfaceDataDefinition mapInterfaceDataDefinition = new MapInterfaceDataDefinition();
2357 List<ComponentInstanceInterface> componentInterface = currComponent.getComponentInstancesInterfaces().get(componentInstanceId);
2359 if(CollectionUtils.isNotEmpty(componentInterface)) {
2360 componentInterface.stream().forEach(interfaceDef -> mapInterfaceDataDefinition.put
2361 (interfaceDef.getUniqueId(), interfaceDef));
2364 return mapInterfaceDataDefinition;
2367 private Map<String, MapCapabilityProperty> convertComponentCapabilitiesProperties(Component currComponent) {
2368 Map<String, MapCapabilityProperty> map = ModelConverter.extractCapabilityPropertiesFromGroups(currComponent.getGroups(), true);
2369 map.putAll(ModelConverter.extractCapabilityProperteisFromInstances(currComponent.getComponentInstances(), true));
2373 private Optional<MapCapabilityProperty> convertComponentInstanceProperties(Component component, String instanceId) {
2374 return component.fetchInstanceById(instanceId)
2375 .map(ci -> ModelConverter.convertToMapOfMapCapabiltyProperties(ci.getCapabilities(), instanceId));
2378 public Either<PolicyDefinition, StorageOperationStatus> associatePolicyToComponent(String componentId, PolicyDefinition policyDefinition, int counter) {
2379 Either<PolicyDefinition, StorageOperationStatus> result = null;
2380 Either<GraphVertex, TitanOperationStatus> getVertexEither;
2381 getVertexEither = titanDao.getVertexById(componentId, JsonParseFlagEnum.ParseMetadata);
2382 if (getVertexEither.isRight()) {
2383 log.error(COULDNT_FETCH_A_COMPONENT_WITH_AND_UNIQUE_ID_ERROR, componentId, getVertexEither.right().value());
2384 result = Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(getVertexEither.right().value()));
2386 if (getVertexEither.left().value().getLabel() != VertexTypeEnum.TOPOLOGY_TEMPLATE) {
2387 log.error("Policy association to component of Tosca type {} is not allowed. ", getVertexEither.left().value().getLabel());
2388 result = Either.right(StorageOperationStatus.BAD_REQUEST);
2391 if (result == null) {
2392 StorageOperationStatus status = topologyTemplateOperation.addPolicyToToscaElement(getVertexEither.left().value(), policyDefinition, counter);
2393 if (status != StorageOperationStatus.OK) {
2394 return Either.right(status);
2397 if (result == null) {
2398 result = Either.left(policyDefinition);
2403 public StorageOperationStatus associatePoliciesToComponent(String componentId, List<PolicyDefinition> policies) {
2404 log.debug("#associatePoliciesToComponent - associating policies for component {}.", componentId);
2405 return titanDao.getVertexById(componentId, JsonParseFlagEnum.ParseMetadata)
2406 .either(containerVertex -> topologyTemplateOperation.addPoliciesToToscaElement(containerVertex, policies),
2407 DaoStatusConverter::convertTitanStatusToStorageStatus);
2410 public Either<PolicyDefinition, StorageOperationStatus> updatePolicyOfComponent(String componentId, PolicyDefinition policyDefinition) {
2411 Either<PolicyDefinition, StorageOperationStatus> result = null;
2412 Either<GraphVertex, TitanOperationStatus> getVertexEither;
2413 getVertexEither = titanDao.getVertexById(componentId, JsonParseFlagEnum.NoParse);
2414 if (getVertexEither.isRight()) {
2415 log.error(COULDNT_FETCH_A_COMPONENT_WITH_AND_UNIQUE_ID_ERROR, componentId, getVertexEither.right().value());
2416 result = Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(getVertexEither.right().value()));
2418 if (result == null) {
2419 StorageOperationStatus status = topologyTemplateOperation.updatePolicyOfToscaElement(getVertexEither.left().value(), policyDefinition);
2420 if (status != StorageOperationStatus.OK) {
2421 return Either.right(status);
2424 if (result == null) {
2425 result = Either.left(policyDefinition);
2430 public StorageOperationStatus updatePoliciesOfComponent(String componentId, List<PolicyDefinition> policyDefinition) {
2431 log.debug("#updatePoliciesOfComponent - updating policies for component {}", componentId);
2432 return titanDao.getVertexById(componentId, JsonParseFlagEnum.NoParse)
2434 .map(DaoStatusConverter::convertTitanStatusToStorageStatus)
2435 .either(containerVertex -> topologyTemplateOperation.updatePoliciesOfToscaElement(containerVertex, policyDefinition),
2439 public StorageOperationStatus removePolicyFromComponent(String componentId, String policyId) {
2440 StorageOperationStatus status = null;
2441 Either<GraphVertex, TitanOperationStatus> getVertexEither = titanDao.getVertexById(componentId, JsonParseFlagEnum.NoParse);
2442 if (getVertexEither.isRight()) {
2443 log.error(COULDNT_FETCH_A_COMPONENT_WITH_AND_UNIQUE_ID_ERROR, componentId, getVertexEither.right().value());
2444 status = DaoStatusConverter.convertTitanStatusToStorageStatus(getVertexEither.right().value());
2446 if (status == null) {
2447 status = topologyTemplateOperation.removePolicyFromToscaElement(getVertexEither.left().value(), policyId);
2452 public boolean canAddGroups(String componentId) {
2453 GraphVertex vertex = titanDao.getVertexById(componentId)
2455 .on(this::onTitanError);
2456 return topologyTemplateOperation.hasEdgeOfType(vertex, EdgeLabelEnum.GROUPS);
2459 GraphVertex onTitanError(TitanOperationStatus toe) {
2460 throw new StorageException(
2461 DaoStatusConverter.convertTitanStatusToStorageStatus(toe));
2464 public void updateNamesOfCalculatedCapabilitiesRequirements(String componentId){
2465 topologyTemplateOperation
2466 .updateNamesOfCalculatedCapabilitiesRequirements(componentId, getTopologyTemplate(componentId));
2469 public void revertNamesOfCalculatedCapabilitiesRequirements(String componentId) {
2470 topologyTemplateOperation
2471 .revertNamesOfCalculatedCapabilitiesRequirements(componentId, getTopologyTemplate(componentId));
2474 private TopologyTemplate getTopologyTemplate(String componentId) {
2475 return (TopologyTemplate)topologyTemplateOperation
2476 .getToscaElement(componentId, getFilterComponentWithCapProperties())
2478 .on(this::throwStorageException);
2481 private ComponentParametersView getFilterComponentWithCapProperties() {
2482 ComponentParametersView filter = new ComponentParametersView();
2483 filter.setIgnoreCapabiltyProperties(false);
2487 private ToscaElement throwStorageException(StorageOperationStatus status) {
2488 throw new StorageException(status);
2491 public Either<Boolean, StorageOperationStatus> isComponentInUse(String componentId) {
2492 final List<EdgeLabelEnum> forbiddenEdgeLabelEnums = Arrays.asList(EdgeLabelEnum.INSTANCE_OF, EdgeLabelEnum.PROXY_OF, EdgeLabelEnum.ALLOTTED_OF);
2493 Either<GraphVertex, TitanOperationStatus> vertexById = titanDao.getVertexById(componentId);
2494 if (vertexById.isLeft()) {
2495 for (EdgeLabelEnum edgeLabelEnum : forbiddenEdgeLabelEnums) {
2496 Iterator<Edge> edgeItr = vertexById.left().value().getVertex().edges(Direction.IN, edgeLabelEnum.name());
2497 if(edgeItr != null && edgeItr.hasNext()){
2498 return Either.left(true);
2502 return Either.left(false);
2505 public Either<List<Component>, StorageOperationStatus> getComponentListByInvariantUuid
2506 (String componentInvariantUuid, Map<GraphPropertyEnum, Object> additionalPropertiesToMatch) {
2508 Map<GraphPropertyEnum, Object> propertiesToMatch = new EnumMap<>(GraphPropertyEnum.class);
2509 if (MapUtils.isNotEmpty(additionalPropertiesToMatch)) {
2510 propertiesToMatch.putAll(additionalPropertiesToMatch);
2512 propertiesToMatch.put(GraphPropertyEnum.INVARIANT_UUID, componentInvariantUuid);
2514 Either<List<GraphVertex>, TitanOperationStatus> vertexEither = titanDao.getByCriteria(null, propertiesToMatch, JsonParseFlagEnum.ParseMetadata);
2516 if (vertexEither.isRight()) {
2517 log.debug("Couldn't fetch metadata for component with type {} and invariantUUId {}, error: {}", componentInvariantUuid, vertexEither.right().value());
2518 return Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(vertexEither.right().value()));
2520 List<GraphVertex> vertexList = vertexEither.isLeft() ? vertexEither.left().value() : null;
2522 if (vertexList == null || vertexList.isEmpty()) {
2523 log.debug("Component with invariantUUId {} was not found", componentInvariantUuid);
2524 return Either.right(StorageOperationStatus.NOT_FOUND);
2527 ArrayList<Component> components = new ArrayList<>();
2528 for (GraphVertex vertex : vertexList) {
2529 Either<Component, StorageOperationStatus> toscaElementByOperation = getToscaElementByOperation(vertex);
2530 if (toscaElementByOperation.isRight()) {
2531 log.debug("Could not fetch the following Component by Invariant UUID {}", vertex.getUniqueId());
2532 return Either.right(toscaElementByOperation.right().value());
2534 components.add(toscaElementByOperation.left().value());
2537 return Either.left(components);
2540 public Either<List<Component>, StorageOperationStatus> getParentComponents(String componentId) {
2541 List<Component> parentComponents = new ArrayList<>();
2542 final List<EdgeLabelEnum> relationEdgeLabelEnums = Arrays.asList(EdgeLabelEnum.INSTANCE_OF, EdgeLabelEnum.PROXY_OF);
2543 Either<GraphVertex, TitanOperationStatus> vertexById = titanDao.getVertexById(componentId);
2544 if (vertexById.isLeft()) {
2545 for (EdgeLabelEnum edgeLabelEnum : relationEdgeLabelEnums) {
2546 Either<GraphVertex, TitanOperationStatus> parentVertexEither = titanDao.getParentVertex(vertexById.left().value(), edgeLabelEnum, JsonParseFlagEnum.ParseJson);
2547 if(parentVertexEither.isLeft()){
2548 Either<Component, StorageOperationStatus> componentEither = getToscaElement(parentVertexEither.left().value().getUniqueId());
2549 if(componentEither.isLeft()){
2550 parentComponents.add(componentEither.left().value());
2555 return Either.left(parentComponents);
2557 public void updateCapReqOwnerId(String componentId) {
2558 topologyTemplateOperation
2559 .updateCapReqOwnerId(componentId, getTopologyTemplate(componentId));