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.enums.*;
38 import org.openecomp.sdc.be.model.*;
39 import org.openecomp.sdc.be.model.catalog.CatalogComponent;
40 import org.openecomp.sdc.be.model.jsontitan.datamodel.TopologyTemplate;
41 import org.openecomp.sdc.be.model.jsontitan.datamodel.ToscaElement;
42 import org.openecomp.sdc.be.model.jsontitan.utils.ModelConverter;
43 import org.openecomp.sdc.be.model.operations.StorageException;
44 import org.openecomp.sdc.be.model.operations.api.StorageOperationStatus;
45 import org.openecomp.sdc.be.model.operations.impl.DaoStatusConverter;
46 import org.openecomp.sdc.be.model.operations.impl.UniqueIdBuilder;
47 import org.openecomp.sdc.be.resources.data.ComponentMetadataData;
48 import org.openecomp.sdc.common.jsongraph.util.CommonUtility;
49 import org.openecomp.sdc.common.jsongraph.util.CommonUtility.LogLevelEnum;
50 import org.openecomp.sdc.common.log.wrappers.Logger;
51 import org.openecomp.sdc.common.util.ValidationUtils;
52 import org.springframework.beans.factory.annotation.Autowired;
55 import java.util.Map.Entry;
56 import java.util.function.BiPredicate;
57 import java.util.stream.Collectors;
59 import static java.util.Objects.requireNonNull;
60 import static org.apache.commons.collections.CollectionUtils.isEmpty;
61 import static org.apache.commons.collections.CollectionUtils.isNotEmpty;
64 @org.springframework.stereotype.Component("tosca-operation-facade")
65 public class ToscaOperationFacade {
69 private static final String COULDNT_FETCH_A_COMPONENT_WITH_AND_UNIQUE_ID_ERROR = "Couldn't fetch a component with and UniqueId {}, error: {}";
70 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 {}. ";
71 private static final String FAILED_TO_GET_UPDATED_RESOURCE_STATUS_IS = "Failed to get updated resource {}. Status is {}. ";
72 private static final String FAILED_TO_ADD_THE_PROPERTY_TO_THE_RESOURCE_STATUS_IS = "Failed to add the property {} to the resource {}. Status is {}. ";
73 private static final String SERVICE = "service";
74 private static final String NOT_SUPPORTED_COMPONENT_TYPE = "Not supported component type {}";
75 private static final String COMPONENT_CREATED_SUCCESSFULLY = "Component created successfully!!!";
76 private static final String COULDNT_FETCH_COMPONENT_WITH_AND_UNIQUE_ID_ERROR = "Couldn't fetch component with and unique id {}, error: {}";
78 private NodeTypeOperation nodeTypeOperation;
80 private TopologyTemplateOperation topologyTemplateOperation;
82 private NodeTemplateOperation nodeTemplateOperation;
84 private GroupsOperation groupsOperation;
86 private TitanDao titanDao;
88 private static final Logger log = Logger.getLogger(ToscaOperationFacade.class.getName());
91 // region - ToscaElement - GetById
92 public static final String PROXY_SUFFIX = "_proxy";
94 public <T extends Component> Either<T, StorageOperationStatus> getToscaFullElement(String componentId) {
95 ComponentParametersView filters = new ComponentParametersView();
96 filters.setIgnoreCapabiltyProperties(false);
97 filters.setIgnoreForwardingPath(false);
98 return getToscaElement(componentId, filters);
101 public <T extends Component> Either<T, StorageOperationStatus> getToscaElement(String componentId) {
103 return getToscaElement(componentId, JsonParseFlagEnum.ParseAll);
107 public <T extends Component> Either<T, StorageOperationStatus> getToscaElement(String componentId, ComponentParametersView filters) {
109 Either<GraphVertex, TitanOperationStatus> getVertexEither = titanDao.getVertexById(componentId, filters.detectParseFlag());
110 if (getVertexEither.isRight()) {
111 log.debug(COULDNT_FETCH_COMPONENT_WITH_AND_UNIQUE_ID_ERROR, componentId, getVertexEither.right().value());
112 return Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(getVertexEither.right().value()));
115 return getToscaElementByOperation(getVertexEither.left().value(), filters);
118 public <T extends Component> Either<T, StorageOperationStatus> getToscaElement(String componentId, JsonParseFlagEnum parseFlag) {
120 Either<GraphVertex, TitanOperationStatus> getVertexEither = titanDao.getVertexById(componentId, parseFlag);
121 if (getVertexEither.isRight()) {
122 log.debug(COULDNT_FETCH_COMPONENT_WITH_AND_UNIQUE_ID_ERROR, componentId, getVertexEither.right().value());
123 return Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(getVertexEither.right().value()));
126 return getToscaElementByOperation(getVertexEither.left().value());
129 public <T extends Component> Either<T, StorageOperationStatus> getToscaElement(GraphVertex componentVertex) {
130 return getToscaElementByOperation(componentVertex);
133 public Either<Boolean, StorageOperationStatus> validateComponentExists(String componentId) {
135 Either<GraphVertex, TitanOperationStatus> getVertexEither = titanDao.getVertexById(componentId, JsonParseFlagEnum.NoParse);
136 if (getVertexEither.isRight()) {
137 TitanOperationStatus status = getVertexEither.right().value();
138 if (status == TitanOperationStatus.NOT_FOUND) {
139 return Either.left(false);
141 log.debug(COULDNT_FETCH_COMPONENT_WITH_AND_UNIQUE_ID_ERROR, componentId, getVertexEither.right().value());
142 return Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(getVertexEither.right().value()));
145 return Either.left(true);
148 public <T extends Component> Either<T, StorageOperationStatus> findLastCertifiedToscaElementByUUID(T component) {
149 Map<GraphPropertyEnum, Object> props = new EnumMap<>(GraphPropertyEnum.class);
150 props.put(GraphPropertyEnum.UUID, component.getUUID());
151 props.put(GraphPropertyEnum.STATE, LifecycleStateEnum.CERTIFIED.name());
152 props.put(GraphPropertyEnum.IS_HIGHEST_VERSION, true);
154 Either<List<GraphVertex>, TitanOperationStatus> getVertexEither = titanDao.getByCriteria(ModelConverter.getVertexType(component), props);
155 if (getVertexEither.isRight()) {
156 log.debug(COULDNT_FETCH_COMPONENT_WITH_AND_UNIQUE_ID_ERROR, component.getUniqueId(), getVertexEither.right().value());
157 return Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(getVertexEither.right().value()));
160 return getToscaElementByOperation(getVertexEither.left().value().get(0));
164 // region - ToscaElement - GetByOperation
165 private <T extends Component> Either<T, StorageOperationStatus> getToscaElementByOperation(GraphVertex componentV) {
166 return getToscaElementByOperation(componentV, new ComponentParametersView());
169 private <T extends Component> Either<T, StorageOperationStatus> getToscaElementByOperation(GraphVertex componentV, ComponentParametersView filters) {
170 VertexTypeEnum label = componentV.getLabel();
172 ToscaElementOperation toscaOperation = getToscaElementOperation(componentV);
173 Either<ToscaElement, StorageOperationStatus> toscaElement;
174 String componentId = componentV.getUniqueId();
175 if (toscaOperation != null) {
176 log.debug("Need to fetch tosca element for id {}", componentId);
177 toscaElement = toscaOperation.getToscaElement(componentV, filters);
179 log.debug("not supported tosca type {} for id {}", label, componentId);
180 toscaElement = Either.right(StorageOperationStatus.BAD_REQUEST);
182 if (toscaElement.isRight()) {
183 return Either.right(toscaElement.right().value());
185 return Either.left(ModelConverter.convertFromToscaElement(toscaElement.left().value()));
189 private ToscaElementOperation getToscaElementOperation(GraphVertex componentV) {
190 VertexTypeEnum label = componentV.getLabel();
193 return nodeTypeOperation;
194 case TOPOLOGY_TEMPLATE:
195 return topologyTemplateOperation;
201 public <T extends Component> Either<T, StorageOperationStatus> createToscaComponent(T resource) {
202 ToscaElement toscaElement = ModelConverter.convertToToscaElement(resource);
204 ToscaElementOperation toscaElementOperation = getToscaElementOperation(resource);
205 Either<ToscaElement, StorageOperationStatus> createToscaElement = toscaElementOperation.createToscaElement(toscaElement);
206 if (createToscaElement.isLeft()) {
207 log.debug(COMPONENT_CREATED_SUCCESSFULLY);
208 T dataModel = ModelConverter.convertFromToscaElement(createToscaElement.left().value());
209 return Either.left(dataModel);
211 return Either.right(createToscaElement.right().value());
214 // region - ToscaElement Delete
215 public StorageOperationStatus markComponentToDelete(Component componentToDelete) {
217 if ((componentToDelete.getIsDeleted() != null) && componentToDelete.getIsDeleted() && !componentToDelete.isHighestVersion()) {
218 // component already marked for delete
219 return StorageOperationStatus.OK;
222 Either<GraphVertex, TitanOperationStatus> getResponse = titanDao.getVertexById(componentToDelete.getUniqueId(), JsonParseFlagEnum.ParseAll);
223 if (getResponse.isRight()) {
224 log.debug(COULDNT_FETCH_COMPONENT_WITH_AND_UNIQUE_ID_ERROR, componentToDelete.getUniqueId(), getResponse.right().value());
225 return DaoStatusConverter.convertTitanStatusToStorageStatus(getResponse.right().value());
228 GraphVertex componentV = getResponse.left().value();
230 // same operation for node type and topology template operations
231 Either<GraphVertex, StorageOperationStatus> result = nodeTypeOperation.markComponentToDelete(componentV);
232 if (result.isRight()) {
233 return result.right().value();
235 return StorageOperationStatus.OK;
239 public <T extends Component> Either<T, StorageOperationStatus> deleteToscaComponent(String componentId) {
241 Either<GraphVertex, TitanOperationStatus> getVertexEither = titanDao.getVertexById(componentId, JsonParseFlagEnum.ParseAll);
242 if (getVertexEither.isRight()) {
243 log.debug("Couldn't fetch component vertex with and unique id {}, error: {}", componentId, getVertexEither.right().value());
244 return Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(getVertexEither.right().value()));
247 Either<ToscaElement, StorageOperationStatus> deleteElement = deleteToscaElement(getVertexEither.left().value());
248 if (deleteElement.isRight()) {
249 log.debug("Failed to delete component with and unique id {}, error: {}", componentId, deleteElement.right().value());
250 return Either.right(deleteElement.right().value());
252 T dataModel = ModelConverter.convertFromToscaElement(deleteElement.left().value());
254 return Either.left(dataModel);
257 private Either<ToscaElement, StorageOperationStatus> deleteToscaElement(GraphVertex componentV) {
258 VertexTypeEnum label = componentV.getLabel();
259 Either<ToscaElement, StorageOperationStatus> toscaElement;
260 Object componentId = componentV.getUniqueId();
263 log.debug("Need to fetch node type for id {}", componentId);
264 toscaElement = nodeTypeOperation.deleteToscaElement(componentV);
266 case TOPOLOGY_TEMPLATE:
267 log.debug("Need to fetch topology template for id {}", componentId);
268 toscaElement = topologyTemplateOperation.deleteToscaElement(componentV);
271 log.debug("not supported tosca type {} for id {}", label, componentId);
272 toscaElement = Either.right(StorageOperationStatus.BAD_REQUEST);
279 private ToscaElementOperation getToscaElementOperation(Component component) {
280 return ModelConverter.isAtomicComponent(component) ? nodeTypeOperation : topologyTemplateOperation;
283 public <T extends Component> Either<T, StorageOperationStatus> getLatestByToscaResourceName(String toscaResourceName) {
284 return getLatestByName(GraphPropertyEnum.TOSCA_RESOURCE_NAME, toscaResourceName);
287 public <T extends Component> Either<T, StorageOperationStatus> getFullLatestComponentByToscaResourceName(String toscaResourceName) {
288 ComponentParametersView fetchAllFilter = new ComponentParametersView();
289 fetchAllFilter.setIgnoreForwardingPath(true);
290 fetchAllFilter.setIgnoreCapabiltyProperties(false);
291 return getLatestByName(GraphPropertyEnum.TOSCA_RESOURCE_NAME, toscaResourceName, JsonParseFlagEnum.ParseAll, fetchAllFilter);
294 public <T extends Component> Either<T, StorageOperationStatus> getLatestByName(String resourceName) {
295 return getLatestByName(GraphPropertyEnum.NAME, resourceName);
299 public StorageOperationStatus validateCsarUuidUniqueness(String csarUUID) {
301 Map<GraphPropertyEnum, Object> properties = new EnumMap<>(GraphPropertyEnum.class);
302 properties.put(GraphPropertyEnum.CSAR_UUID, csarUUID);
304 Either<List<GraphVertex>, TitanOperationStatus> resources = titanDao.getByCriteria(null, properties, JsonParseFlagEnum.ParseMetadata);
306 if (resources.isRight()) {
307 if (resources.right().value() == TitanOperationStatus.NOT_FOUND) {
308 return StorageOperationStatus.OK;
310 log.debug("failed to get resources from graph with property name: {}", csarUUID);
311 return DaoStatusConverter.convertTitanStatusToStorageStatus(resources.right().value());
314 return StorageOperationStatus.ENTITY_ALREADY_EXISTS;
318 public <T extends Component> Either<Set<T>, StorageOperationStatus> getFollowed(String userId, Set<LifecycleStateEnum> lifecycleStates, Set<LifecycleStateEnum> lastStateStates, ComponentTypeEnum componentType) {
319 Either<List<ToscaElement>, StorageOperationStatus> followedResources;
320 if (componentType == ComponentTypeEnum.RESOURCE) {
321 followedResources = nodeTypeOperation.getFollowedComponent(userId, lifecycleStates, lastStateStates, componentType);
323 followedResources = topologyTemplateOperation.getFollowedComponent(userId, lifecycleStates, lastStateStates, componentType);
326 Set<T> components = new HashSet<>();
327 if (followedResources.isRight() && followedResources.right().value() != StorageOperationStatus.NOT_FOUND) {
328 return Either.right(followedResources.right().value());
330 if (followedResources.isLeft()) {
331 List<ToscaElement> toscaElements = followedResources.left().value();
332 toscaElements.forEach(te -> {
333 T component = ModelConverter.convertFromToscaElement(te);
334 components.add(component);
337 return Either.left(components);
340 public Either<Resource, StorageOperationStatus> getLatestCertifiedNodeTypeByToscaResourceName(String toscaResourceName) {
342 return getLatestCertifiedByToscaResourceName(toscaResourceName, VertexTypeEnum.NODE_TYPE, JsonParseFlagEnum.ParseMetadata);
345 public Either<Resource, StorageOperationStatus> getLatestCertifiedByToscaResourceName(String toscaResourceName, VertexTypeEnum vertexType, JsonParseFlagEnum parseFlag) {
347 Either<Resource, StorageOperationStatus> result = null;
348 Map<GraphPropertyEnum, Object> props = new EnumMap<>(GraphPropertyEnum.class);
349 props.put(GraphPropertyEnum.TOSCA_RESOURCE_NAME, toscaResourceName);
350 props.put(GraphPropertyEnum.IS_HIGHEST_VERSION, true);
351 props.put(GraphPropertyEnum.STATE, LifecycleStateEnum.CERTIFIED.name());
352 Either<List<GraphVertex>, TitanOperationStatus> getLatestRes = titanDao.getByCriteria(vertexType, props, parseFlag);
354 if (getLatestRes.isRight()) {
355 TitanOperationStatus status = getLatestRes.right().value();
356 CommonUtility.addRecordToLog(log, LogLevelEnum.DEBUG, "Failed to fetch {} with name {}. status={} ", vertexType, toscaResourceName, status);
357 result = Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(status));
359 if (result == null) {
360 List<GraphVertex> resources = getLatestRes.left().value();
361 double version = 0.0;
362 GraphVertex highestResource = null;
363 for (GraphVertex resource : resources) {
364 double resourceVersion = Double.parseDouble((String) resource.getJsonMetadataField(JsonPresentationFields.VERSION));
365 if (resourceVersion > version) {
366 version = resourceVersion;
367 highestResource = resource;
370 result = getToscaFullElement(highestResource.getUniqueId());
375 public Either<Boolean, StorageOperationStatus> validateToscaResourceNameExists(String templateName) {
376 Either<Boolean, StorageOperationStatus> validateUniquenessRes = validateToscaResourceNameUniqueness(templateName);
377 if (validateUniquenessRes.isLeft()) {
378 return Either.left(!validateUniquenessRes.left().value());
380 return validateUniquenessRes;
383 public Either<RequirementCapabilityRelDef, StorageOperationStatus> dissociateResourceInstances(String componentId, RequirementCapabilityRelDef requirementDef) {
384 return nodeTemplateOperation.dissociateResourceInstances(componentId, requirementDef);
388 * Allows to get fulfilled requirement by relation and received predicate
390 public Either<RequirementDataDefinition, StorageOperationStatus> getFulfilledRequirementByRelation(String componentId, String instanceId, RequirementCapabilityRelDef relation, BiPredicate<RelationshipInfo, RequirementDataDefinition> predicate) {
391 return nodeTemplateOperation.getFulfilledRequirementByRelation(componentId, instanceId, relation, predicate);
395 * Allows to get fulfilled capability by relation and received predicate
397 public Either<CapabilityDataDefinition, StorageOperationStatus> getFulfilledCapabilityByRelation(String componentId, String instanceId, RequirementCapabilityRelDef relation, BiPredicate<RelationshipInfo, CapabilityDataDefinition> predicate) {
398 return nodeTemplateOperation.getFulfilledCapabilityByRelation(componentId, instanceId, relation, predicate);
401 public StorageOperationStatus associateResourceInstances(String componentId, List<RequirementCapabilityRelDef> relations) {
402 Either<List<RequirementCapabilityRelDef>, StorageOperationStatus> status = nodeTemplateOperation.associateResourceInstances(componentId, relations);
403 if (status.isRight()) {
404 return status.right().value();
406 return StorageOperationStatus.OK;
409 protected Either<Boolean, StorageOperationStatus> validateToscaResourceNameUniqueness(String name) {
411 Map<GraphPropertyEnum, Object> properties = new EnumMap<>(GraphPropertyEnum.class);
412 properties.put(GraphPropertyEnum.TOSCA_RESOURCE_NAME, name);
414 Either<List<GraphVertex>, TitanOperationStatus> resources = titanDao.getByCriteria(null, properties, JsonParseFlagEnum.ParseMetadata);
416 if (resources.isRight() && resources.right().value() != TitanOperationStatus.NOT_FOUND) {
417 log.debug("failed to get resources from graph with property name: {}", name);
418 return Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(resources.right().value()));
420 List<GraphVertex> resourceList = (resources.isLeft() ? resources.left().value() : null);
421 if (isNotEmpty(resourceList)) {
422 if (log.isDebugEnabled()) {
423 StringBuilder builder = new StringBuilder();
424 for (GraphVertex resourceData : resourceList) {
425 builder.append(resourceData.getUniqueId() + "|");
427 log.debug("resources with property name:{} exists in graph. found {}", name, builder);
429 return Either.left(false);
431 log.debug("resources with property name:{} does not exists in graph", name);
432 return Either.left(true);
437 // region - Component Update
439 public Either<Resource, StorageOperationStatus> overrideComponent(Resource newComponent, Resource oldComponent) {
441 copyArtifactsToNewComponent(newComponent, oldComponent);
443 Either<GraphVertex, TitanOperationStatus> componentVEither = titanDao.getVertexById(oldComponent.getUniqueId(), JsonParseFlagEnum.NoParse);
444 if (componentVEither.isRight()) {
445 log.debug("Falied to fetch component {} error {}", oldComponent.getUniqueId(), componentVEither.right().value());
446 return Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(componentVEither.right().value()));
448 GraphVertex componentv = componentVEither.left().value();
449 Either<GraphVertex, TitanOperationStatus> parentVertexEither = titanDao.getParentVertex(componentv, EdgeLabelEnum.VERSION, JsonParseFlagEnum.NoParse);
450 if (parentVertexEither.isRight() && parentVertexEither.right().value() != TitanOperationStatus.NOT_FOUND) {
451 log.debug("Falied to fetch parent version for component {} error {}", oldComponent.getUniqueId(), parentVertexEither.right().value());
452 return Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(parentVertexEither.right().value()));
455 Either<ToscaElement, StorageOperationStatus> deleteToscaComponent = deleteToscaElement(componentv);
456 if (deleteToscaComponent.isRight()) {
457 log.debug("Falied to remove old component {} error {}", oldComponent.getUniqueId(), deleteToscaComponent.right().value());
458 return Either.right(deleteToscaComponent.right().value());
460 Either<Resource, StorageOperationStatus> createToscaComponent = createToscaComponent(newComponent);
461 if (createToscaComponent.isRight()) {
462 log.debug("Falied to create tosca element component {} error {}", newComponent.getUniqueId(), createToscaComponent.right().value());
463 return Either.right(createToscaComponent.right().value());
465 Resource newElement = createToscaComponent.left().value();
466 Either<GraphVertex, TitanOperationStatus> newVersionEither = titanDao.getVertexById(newElement.getUniqueId(), JsonParseFlagEnum.NoParse);
467 if (newVersionEither.isRight()) {
468 log.debug("Falied to fetch new tosca element component {} error {}", newComponent.getUniqueId(), newVersionEither.right().value());
469 return Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(newVersionEither.right().value()));
471 if (parentVertexEither.isLeft()) {
472 GraphVertex previousVersionV = parentVertexEither.left().value();
473 TitanOperationStatus createEdge = titanDao.createEdge(previousVersionV, newVersionEither.left().value(), EdgeLabelEnum.VERSION, null);
474 if (createEdge != TitanOperationStatus.OK) {
475 log.debug("Falied to associate to previous version {} new version {} error {}", previousVersionV.getUniqueId(), newVersionEither.right().value(), createEdge);
476 return Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(createEdge));
479 return Either.left(newElement);
482 void copyArtifactsToNewComponent(Resource newComponent, Resource oldComponent) {
483 // TODO - check if required
484 Map<String, ArtifactDefinition> toscaArtifacts = oldComponent.getToscaArtifacts();
485 if (toscaArtifacts != null && !toscaArtifacts.isEmpty()) {
486 toscaArtifacts.values().stream().forEach(a -> a.setDuplicated(Boolean.TRUE));
488 newComponent.setToscaArtifacts(toscaArtifacts);
490 Map<String, ArtifactDefinition> artifacts = oldComponent.getArtifacts();
491 if (artifacts != null && !artifacts.isEmpty()) {
492 artifacts.values().stream().forEach(a -> a.setDuplicated(Boolean.TRUE));
494 newComponent.setArtifacts(artifacts);
496 Map<String, ArtifactDefinition> depArtifacts = oldComponent.getDeploymentArtifacts();
497 if (depArtifacts != null && !depArtifacts.isEmpty()) {
498 depArtifacts.values().stream().forEach(a -> a.setDuplicated(Boolean.TRUE));
500 newComponent.setDeploymentArtifacts(depArtifacts);
502 newComponent.setGroups(oldComponent.getGroups());
503 newComponent.setLastUpdateDate(null);
504 newComponent.setHighestVersion(true);
507 public <T extends Component> Either<T, StorageOperationStatus> updateToscaElement(T componentToUpdate) {
508 return updateToscaElement(componentToUpdate, new ComponentParametersView());
511 public <T extends Component> Either<T, StorageOperationStatus> updateToscaElement(T componentToUpdate, ComponentParametersView filterResult) {
512 String componentId = componentToUpdate.getUniqueId();
513 Either<GraphVertex, TitanOperationStatus> getVertexEither = titanDao.getVertexById(componentId, JsonParseFlagEnum.ParseAll);
514 if (getVertexEither.isRight()) {
515 log.debug(COULDNT_FETCH_COMPONENT_WITH_AND_UNIQUE_ID_ERROR, componentId, getVertexEither.right().value());
516 return Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(getVertexEither.right().value()));
518 GraphVertex elementV = getVertexEither.left().value();
519 ToscaElementOperation toscaElementOperation = getToscaElementOperation(elementV);
521 ToscaElement toscaElementToUpdate = ModelConverter.convertToToscaElement(componentToUpdate);
522 Either<ToscaElement, StorageOperationStatus> updateToscaElement = toscaElementOperation.updateToscaElement(toscaElementToUpdate, elementV, filterResult);
523 if (updateToscaElement.isRight()) {
524 log.debug("Failed to update tosca element {} error {}", componentId, updateToscaElement.right().value());
525 return Either.right(updateToscaElement.right().value());
527 return Either.left(ModelConverter.convertFromToscaElement(updateToscaElement.left().value()));
530 private <T extends Component> Either<T, StorageOperationStatus> getLatestByName(GraphPropertyEnum property, String nodeName, JsonParseFlagEnum parseFlag) {
531 return getLatestByName(property, nodeName, parseFlag, new ComponentParametersView());
534 private <T extends Component> Either<T, StorageOperationStatus> getLatestByName(GraphPropertyEnum property, String nodeName, JsonParseFlagEnum parseFlag, ComponentParametersView filter) {
535 Either<T, StorageOperationStatus> result;
537 Map<GraphPropertyEnum, Object> propertiesToMatch = new EnumMap<>(GraphPropertyEnum.class);
538 Map<GraphPropertyEnum, Object> propertiesNotToMatch = new EnumMap<>(GraphPropertyEnum.class);
540 propertiesToMatch.put(property, nodeName);
541 propertiesToMatch.put(GraphPropertyEnum.IS_HIGHEST_VERSION, true);
543 propertiesNotToMatch.put(GraphPropertyEnum.IS_DELETED, true);
545 Either<List<GraphVertex>, TitanOperationStatus> highestResources = titanDao.getByCriteria(null, propertiesToMatch, propertiesNotToMatch, parseFlag);
546 if (highestResources.isRight()) {
547 TitanOperationStatus status = highestResources.right().value();
548 log.debug("failed to find resource with name {}. status={} ", nodeName, status);
549 result = Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(status));
553 List<GraphVertex> resources = highestResources.left().value();
554 double version = 0.0;
555 GraphVertex highestResource = null;
556 for (GraphVertex vertex : resources) {
557 Object versionObj = vertex.getMetadataProperty(GraphPropertyEnum.VERSION);
558 double resourceVersion = Double.parseDouble((String) versionObj);
559 if (resourceVersion > version) {
560 version = resourceVersion;
561 highestResource = vertex;
564 return getToscaElementByOperation(highestResource, filter);
568 // region - Component Get By ..
569 private <T extends Component> Either<T, StorageOperationStatus> getLatestByName(GraphPropertyEnum property, String nodeName) {
570 return getLatestByName(property, nodeName, JsonParseFlagEnum.ParseMetadata);
573 public <T extends Component> Either<List<T>, StorageOperationStatus> getBySystemName(ComponentTypeEnum componentType, String systemName) {
575 Either<List<T>, StorageOperationStatus> result = null;
576 Either<T, StorageOperationStatus> getComponentRes;
577 List<T> components = new ArrayList<>();
578 List<GraphVertex> componentVertices;
579 Map<GraphPropertyEnum, Object> propertiesToMatch = new EnumMap<>(GraphPropertyEnum.class);
580 Map<GraphPropertyEnum, Object> propertiesNotToMatch = new EnumMap<>(GraphPropertyEnum.class);
582 propertiesToMatch.put(GraphPropertyEnum.SYSTEM_NAME, systemName);
583 if (componentType != null)
584 propertiesToMatch.put(GraphPropertyEnum.COMPONENT_TYPE, componentType.name());
586 propertiesNotToMatch.put(GraphPropertyEnum.IS_DELETED, true);
588 Either<List<GraphVertex>, TitanOperationStatus> getComponentsRes = titanDao.getByCriteria(null, propertiesToMatch, propertiesNotToMatch, JsonParseFlagEnum.ParseAll);
589 if (getComponentsRes.isRight()) {
590 TitanOperationStatus status = getComponentsRes.right().value();
591 log.debug("Failed to fetch the component with system name {}. Status is {} ", systemName, status);
592 result = Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(status));
594 if (result == null) {
595 componentVertices = getComponentsRes.left().value();
596 for (GraphVertex componentVertex : componentVertices) {
597 getComponentRes = getToscaElementByOperation(componentVertex);
598 if (getComponentRes.isRight()) {
599 log.debug("Failed to get the component {}. Status is {} ", componentVertex.getJsonMetadataField(JsonPresentationFields.NAME), getComponentRes.right().value());
600 result = Either.right(getComponentRes.right().value());
603 T componentBySystemName = getComponentRes.left().value();
604 log.debug("Found component, id: {}", componentBySystemName.getUniqueId());
605 components.add(componentBySystemName);
608 if (result == null) {
609 result = Either.left(components);
614 public <T extends Component> Either<T, StorageOperationStatus> getComponentByNameAndVersion(ComponentTypeEnum componentType, String name, String version) {
615 return getComponentByNameAndVersion(componentType, name, version, JsonParseFlagEnum.ParseAll);
618 public <T extends Component> Either<T, StorageOperationStatus> getComponentByNameAndVersion(ComponentTypeEnum componentType, String name, String version, JsonParseFlagEnum parseFlag) {
619 Either<T, StorageOperationStatus> result;
621 Map<GraphPropertyEnum, Object> hasProperties = new EnumMap<>(GraphPropertyEnum.class);
622 Map<GraphPropertyEnum, Object> hasNotProperties = new EnumMap<>(GraphPropertyEnum.class);
624 hasProperties.put(GraphPropertyEnum.NAME, name);
625 hasProperties.put(GraphPropertyEnum.VERSION, version);
626 hasNotProperties.put(GraphPropertyEnum.IS_DELETED, true);
627 if (componentType != null) {
628 hasProperties.put(GraphPropertyEnum.COMPONENT_TYPE, componentType.name());
630 Either<List<GraphVertex>, TitanOperationStatus> getResourceRes = titanDao.getByCriteria(null, hasProperties, hasNotProperties, parseFlag);
631 if (getResourceRes.isRight()) {
632 TitanOperationStatus status = getResourceRes.right().value();
633 log.debug("failed to find resource with name {}, version {}. Status is {} ", name, version, status);
634 result = Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(status));
637 return getToscaElementByOperation(getResourceRes.left().value().get(0));
640 public Either<List<CatalogComponent>, StorageOperationStatus> getCatalogOrArchiveComponents(boolean isCatalog, List<OriginTypeEnum> excludeTypes) {
641 List<ResourceTypeEnum> excludedResourceTypes = Optional.ofNullable(excludeTypes).orElse(Collections.emptyList()).stream().filter(type -> !type.equals(OriginTypeEnum.SERVICE)).map(type -> ResourceTypeEnum.getTypeByName(type.name()))
642 .collect(Collectors.toList());
643 return topologyTemplateOperation.getElementCatalogData(isCatalog, excludedResourceTypes);
647 public <T extends Component> Either<List<T>, StorageOperationStatus> getCatalogComponents(ComponentTypeEnum componentType, List<OriginTypeEnum> excludeTypes, boolean isHighestVersions) {
648 List<T> components = new ArrayList<>();
649 Either<List<ToscaElement>, StorageOperationStatus> catalogDataResult;
650 List<ToscaElement> toscaElements = new ArrayList<>();
651 List<ResourceTypeEnum> excludedResourceTypes = Optional.ofNullable(excludeTypes).orElse(Collections.emptyList()).stream().filter(type -> !type.equals(OriginTypeEnum.SERVICE)).map(type -> ResourceTypeEnum.getTypeByName(type.name()))
652 .collect(Collectors.toList());
654 switch (componentType) {
656 catalogDataResult = nodeTypeOperation.getElementCatalogData(ComponentTypeEnum.RESOURCE, excludedResourceTypes, isHighestVersions);
657 if (catalogDataResult.isRight()) {
658 return Either.right(catalogDataResult.right().value());
660 toscaElements = catalogDataResult.left().value();
663 if (excludeTypes != null && excludeTypes.contains(OriginTypeEnum.SERVICE)) {
666 catalogDataResult = topologyTemplateOperation.getElementCatalogData(ComponentTypeEnum.SERVICE, null, isHighestVersions);
667 if (catalogDataResult.isRight()) {
668 return Either.right(catalogDataResult.right().value());
670 toscaElements = catalogDataResult.left().value();
673 log.debug(NOT_SUPPORTED_COMPONENT_TYPE, componentType);
674 return Either.right(StorageOperationStatus.BAD_REQUEST);
676 toscaElements.forEach(te -> {
677 T component = ModelConverter.convertFromToscaElement(te);
678 components.add(component);
680 return Either.left(components);
683 public Either<List<String>, StorageOperationStatus> deleteMarkedElements(ComponentTypeEnum componentType) {
684 Either<List<GraphVertex>, StorageOperationStatus> allComponentsMarkedForDeletion;
685 switch (componentType) {
687 allComponentsMarkedForDeletion = nodeTypeOperation.getAllComponentsMarkedForDeletion(componentType);
691 allComponentsMarkedForDeletion = topologyTemplateOperation.getAllComponentsMarkedForDeletion(componentType);
694 log.debug(NOT_SUPPORTED_COMPONENT_TYPE, componentType);
695 return Either.right(StorageOperationStatus.BAD_REQUEST);
697 if (allComponentsMarkedForDeletion.isRight()) {
698 return Either.right(allComponentsMarkedForDeletion.right().value());
700 List<GraphVertex> allMarked = allComponentsMarkedForDeletion.left().value();
701 return Either.left(checkIfInUseAndDelete(allMarked));
704 private List<String> checkIfInUseAndDelete(List<GraphVertex> allMarked) {
705 final List<EdgeLabelEnum> forbiddenEdgeLabelEnums = Arrays.asList(EdgeLabelEnum.INSTANCE_OF, EdgeLabelEnum.PROXY_OF, EdgeLabelEnum.ALLOTTED_OF);
706 List<String> deleted = new ArrayList<>();
708 for (GraphVertex elementV : allMarked) {
709 boolean isAllowedToDelete = true;
711 for (EdgeLabelEnum edgeLabelEnum : forbiddenEdgeLabelEnums) {
712 Either<Edge, TitanOperationStatus> belongingEdgeByCriteria = titanDao.getBelongingEdgeByCriteria(elementV, edgeLabelEnum, null);
713 if (belongingEdgeByCriteria.isLeft()){
714 log.debug("Marked element {} in use. don't delete it", elementV.getUniqueId());
715 isAllowedToDelete = false;
720 if (isAllowedToDelete) {
721 Either<ToscaElement, StorageOperationStatus> deleteToscaElement = deleteToscaElement(elementV);
722 if (deleteToscaElement.isRight()) {
723 log.debug("Failed to delete marked element UniqueID {}, Name {}, error {}", elementV.getUniqueId(), elementV.getMetadataProperties().get(GraphPropertyEnum.NAME), deleteToscaElement.right().value());
726 deleted.add(elementV.getUniqueId());
732 public Either<List<String>, StorageOperationStatus> getAllComponentsMarkedForDeletion(ComponentTypeEnum componentType) {
733 Either<List<GraphVertex>, StorageOperationStatus> allComponentsMarkedForDeletion;
734 switch (componentType) {
736 allComponentsMarkedForDeletion = nodeTypeOperation.getAllComponentsMarkedForDeletion(componentType);
740 allComponentsMarkedForDeletion = topologyTemplateOperation.getAllComponentsMarkedForDeletion(componentType);
743 log.debug(NOT_SUPPORTED_COMPONENT_TYPE, componentType);
744 return Either.right(StorageOperationStatus.BAD_REQUEST);
746 if (allComponentsMarkedForDeletion.isRight()) {
747 return Either.right(allComponentsMarkedForDeletion.right().value());
749 return Either.left(allComponentsMarkedForDeletion.left().value().stream().map(GraphVertex::getUniqueId).collect(Collectors.toList()));
752 // region - Component Update
753 public Either<ImmutablePair<Component, String>, StorageOperationStatus> addComponentInstanceToTopologyTemplate(Component containerComponent, Component origComponent, ComponentInstance componentInstance, boolean allowDeleted, User user) {
755 Either<ImmutablePair<Component, String>, StorageOperationStatus> result = null;
756 Either<ToscaElement, StorageOperationStatus> updateContainerComponentRes = null;
757 if (StringUtils.isEmpty(componentInstance.getIcon())) {
758 componentInstance.setIcon(origComponent.getIcon());
760 String nameToFindForCounter = componentInstance.getOriginType() == OriginTypeEnum.ServiceProxy ? componentInstance.getSourceModelName() + PROXY_SUFFIX : origComponent.getName();
761 String nextComponentInstanceCounter = getNextComponentInstanceCounter(containerComponent, nameToFindForCounter);
762 Either<ImmutablePair<TopologyTemplate, String>, StorageOperationStatus> addResult = nodeTemplateOperation.addComponentInstanceToTopologyTemplate(ModelConverter.convertToToscaElement(containerComponent),
763 ModelConverter.convertToToscaElement(origComponent), nextComponentInstanceCounter, componentInstance, allowDeleted, user);
765 if (addResult.isRight()) {
766 CommonUtility.addRecordToLog(log, LogLevelEnum.DEBUG, "Failed to add the component instance {} to container component {}. ", componentInstance.getName(), containerComponent.getName());
767 result = Either.right(addResult.right().value());
769 if (result == null) {
770 updateContainerComponentRes = topologyTemplateOperation.getToscaElement(containerComponent.getUniqueId());
771 if (updateContainerComponentRes.isRight()) {
772 CommonUtility.addRecordToLog(log, LogLevelEnum.DEBUG, "Failed to fetch updated topology template {} with updated component instance {}. ", containerComponent.getName(), componentInstance.getName());
773 result = Either.right(updateContainerComponentRes.right().value());
776 if (result == null) {
777 Component updatedComponent = ModelConverter.convertFromToscaElement(updateContainerComponentRes.left().value());
778 String createdInstanceId = addResult.left().value().getRight();
779 CommonUtility.addRecordToLog(log, LogLevelEnum.TRACE, "The component instance {} has been added to container component {}. ", createdInstanceId, updatedComponent.getName());
780 result = Either.left(new ImmutablePair<>(updatedComponent, createdInstanceId));
785 public StorageOperationStatus associateComponentInstancesToComponent(Component containerComponent, Map<ComponentInstance, Resource> resourcesInstancesMap, boolean allowDeleted) {
787 StorageOperationStatus result = null;
788 CommonUtility.addRecordToLog(log, LogLevelEnum.DEBUG, "Going to add component instances to component {}", containerComponent.getUniqueId());
790 Either<GraphVertex, TitanOperationStatus> metadataVertex = titanDao.getVertexById(containerComponent.getUniqueId(), JsonParseFlagEnum.ParseAll);
791 if (metadataVertex.isRight()) {
792 TitanOperationStatus status = metadataVertex.right().value();
793 if (status == TitanOperationStatus.NOT_FOUND) {
794 status = TitanOperationStatus.INVALID_ID;
796 result = DaoStatusConverter.convertTitanStatusToStorageStatus(status);
798 if (result == null) {
799 result = nodeTemplateOperation.associateComponentInstancesToComponent(containerComponent, resourcesInstancesMap, metadataVertex.left().value(), allowDeleted);
804 public Either<ImmutablePair<Component, String>, StorageOperationStatus> updateComponentInstanceMetadataOfTopologyTemplate(Component containerComponent, Component origComponent, ComponentInstance componentInstance) {
806 Either<ImmutablePair<Component, String>, StorageOperationStatus> result = null;
808 CommonUtility.addRecordToLog(log, LogLevelEnum.TRACE, "Going to update the metadata of the component instance {} belonging to container component {}. ", componentInstance.getName(), containerComponent.getName());
809 componentInstance.setIcon(origComponent.getIcon());
810 Either<ImmutablePair<TopologyTemplate, String>, StorageOperationStatus> updateResult = nodeTemplateOperation.updateComponentInstanceMetadataOfTopologyTemplate(ModelConverter.convertToToscaElement(containerComponent),
811 ModelConverter.convertToToscaElement(origComponent), componentInstance);
812 if (updateResult.isRight()) {
813 CommonUtility.addRecordToLog(log, LogLevelEnum.DEBUG, "Failed to update the metadata of the component instance {} belonging to container component {}. ", componentInstance.getName(), containerComponent.getName());
814 result = Either.right(updateResult.right().value());
816 if (result == null) {
817 Component updatedComponent = ModelConverter.convertFromToscaElement(updateResult.left().value().getLeft());
818 String createdInstanceId = updateResult.left().value().getRight();
819 CommonUtility.addRecordToLog(log, LogLevelEnum.TRACE, "The metadata of the component instance {} has been updated to container component {}. ", createdInstanceId, updatedComponent.getName());
820 result = Either.left(new ImmutablePair<>(updatedComponent, createdInstanceId));
825 public Either<Component, StorageOperationStatus> updateComponentInstanceMetadataOfTopologyTemplate(Component containerComponent) {
826 return updateComponentInstanceMetadataOfTopologyTemplate(containerComponent, new ComponentParametersView());
829 public Either<Component, StorageOperationStatus> updateComponentInstanceMetadataOfTopologyTemplate(Component containerComponent, ComponentParametersView filter) {
831 Either<Component, StorageOperationStatus> result = null;
833 CommonUtility.addRecordToLog(log, LogLevelEnum.TRACE, "Going to update the metadata belonging to container component {}. ", containerComponent.getName());
835 Either<TopologyTemplate, StorageOperationStatus> updateResult = nodeTemplateOperation.updateComponentInstanceMetadataOfTopologyTemplate(ModelConverter.convertToToscaElement(containerComponent), filter);
836 if (updateResult.isRight()) {
837 CommonUtility.addRecordToLog(log, LogLevelEnum.DEBUG, "Failed to update the metadata belonging to container component {}. ", containerComponent.getName());
838 result = Either.right(updateResult.right().value());
840 if (result == null) {
841 Component updatedComponent = ModelConverter.convertFromToscaElement(updateResult.left().value());
842 CommonUtility.addRecordToLog(log, LogLevelEnum.TRACE, "The metadata has been updated to container component {}. ", updatedComponent.getName());
843 result = Either.left(updatedComponent);
849 public Either<ImmutablePair<Component, String>, StorageOperationStatus> deleteComponentInstanceFromTopologyTemplate(Component containerComponent, String resourceInstanceId) {
851 Either<ImmutablePair<Component, String>, StorageOperationStatus> result = null;
853 CommonUtility.addRecordToLog(log, LogLevelEnum.TRACE, "Going to delete the component instance {} belonging to container component {}. ", resourceInstanceId, containerComponent.getName());
855 Either<ImmutablePair<TopologyTemplate, String>, StorageOperationStatus> updateResult = nodeTemplateOperation.deleteComponentInstanceFromTopologyTemplate(ModelConverter.convertToToscaElement(containerComponent), resourceInstanceId);
856 if (updateResult.isRight()) {
857 CommonUtility.addRecordToLog(log, LogLevelEnum.DEBUG, "Failed to delete the component instance {} belonging to container component {}. ", resourceInstanceId, containerComponent.getName());
858 result = Either.right(updateResult.right().value());
860 if (result == null) {
861 Component updatedComponent = ModelConverter.convertFromToscaElement(updateResult.left().value().getLeft());
862 String deletedInstanceId = updateResult.left().value().getRight();
863 CommonUtility.addRecordToLog(log, LogLevelEnum.TRACE, "The component instance {} has been deleted from container component {}. ", deletedInstanceId, updatedComponent.getName());
864 result = Either.left(new ImmutablePair<>(updatedComponent, deletedInstanceId));
869 private String getNextComponentInstanceCounter(Component containerComponent, String originResourceName) {
870 Integer nextCounter = 0;
871 if (CollectionUtils.isNotEmpty(containerComponent.getComponentInstances())) {
872 String normalizedName = ValidationUtils.normalizeComponentInstanceName(originResourceName);
873 Integer maxCounter = getMaxCounterFromNamesAndIds(containerComponent, normalizedName);
874 if (maxCounter != null) {
875 nextCounter = maxCounter + 1;
878 return nextCounter.toString();
882 * @return max counter of component instance Id's, null if not found
884 private Integer getMaxCounterFromNamesAndIds(Component containerComponent, String normalizedName) {
885 List<String> countersInNames = containerComponent.getComponentInstances().stream()
886 .filter(ci -> ci.getNormalizedName() != null && ci.getNormalizedName().startsWith(normalizedName))
887 .map(ci -> ci.getNormalizedName().split(normalizedName)[1])
888 .collect(Collectors.toList());
889 List<String> countersInIds = containerComponent.getComponentInstances().stream()
890 .filter(ci -> ci.getUniqueId() != null && ci.getUniqueId().contains(normalizedName))
891 .map(ci -> ci.getUniqueId().split(normalizedName)[1])
892 .collect(Collectors.toList());
893 List<String> namesAndIdsList = new ArrayList<>(countersInNames);
894 namesAndIdsList.addAll(countersInIds);
895 return getMaxInteger(namesAndIdsList);
898 private Integer getMaxInteger(List<String> counters) {
899 Integer maxCounter = 0;
900 Integer currCounter = null;
901 for (String counter : counters) {
903 currCounter = Integer.parseInt(counter);
904 if (maxCounter < currCounter) {
905 maxCounter = currCounter;
907 } catch (NumberFormatException e) {
911 return currCounter == null ? null : maxCounter;
914 public Either<RequirementCapabilityRelDef, StorageOperationStatus> associateResourceInstances(String componentId, RequirementCapabilityRelDef requirementDef) {
915 return nodeTemplateOperation.associateResourceInstances(componentId, requirementDef);
919 public Either<List<InputDefinition>, StorageOperationStatus> createAndAssociateInputs(Map<String, InputDefinition> inputs, String componentId) {
921 Either<GraphVertex, TitanOperationStatus> getVertexEither = titanDao.getVertexById(componentId, JsonParseFlagEnum.NoParse);
922 if (getVertexEither.isRight()) {
923 log.debug(COULDNT_FETCH_COMPONENT_WITH_AND_UNIQUE_ID_ERROR, componentId, getVertexEither.right().value());
924 return Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(getVertexEither.right().value()));
928 GraphVertex vertex = getVertexEither.left().value();
929 Map<String, PropertyDataDefinition> inputsMap = inputs.entrySet().stream().collect(Collectors.toMap(Map.Entry::getKey, e -> new PropertyDataDefinition(e.getValue())));
931 StorageOperationStatus status = topologyTemplateOperation.associateInputsToComponent(vertex, inputsMap, componentId);
933 if (StorageOperationStatus.OK == status) {
934 log.debug(COMPONENT_CREATED_SUCCESSFULLY);
935 List<InputDefinition> inputsResList = null;
936 if (inputsMap != null && !inputsMap.isEmpty()) {
937 inputsResList = inputsMap.values().stream()
938 .map(InputDefinition::new)
939 .collect(Collectors.toList());
941 return Either.left(inputsResList);
943 return Either.right(status);
947 public Either<List<InputDefinition>, StorageOperationStatus> addInputsToComponent(Map<String, InputDefinition> inputs, String componentId) {
949 Either<GraphVertex, TitanOperationStatus> getVertexEither = titanDao.getVertexById(componentId, JsonParseFlagEnum.NoParse);
950 if (getVertexEither.isRight()) {
951 log.debug(COULDNT_FETCH_COMPONENT_WITH_AND_UNIQUE_ID_ERROR, componentId, getVertexEither.right().value());
952 return Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(getVertexEither.right().value()));
956 GraphVertex vertex = getVertexEither.left().value();
957 Map<String, PropertyDataDefinition> inputsMap = inputs.entrySet().stream().collect(Collectors.toMap(Map.Entry::getKey, e -> new PropertyDataDefinition(e.getValue())));
959 StorageOperationStatus status = topologyTemplateOperation.addToscaDataToToscaElement(vertex, EdgeLabelEnum.INPUTS, VertexTypeEnum.INPUTS, inputsMap, JsonPresentationFields.NAME);
961 if (StorageOperationStatus.OK == status) {
962 log.debug(COMPONENT_CREATED_SUCCESSFULLY);
963 List<InputDefinition> inputsResList = null;
964 if (inputsMap != null && !inputsMap.isEmpty()) {
965 inputsResList = inputsMap.values().stream().map(InputDefinition::new).collect(Collectors.toList());
967 return Either.left(inputsResList);
969 return Either.right(status);
973 public Either<List<InputDefinition>, StorageOperationStatus> getComponentInputs(String componentId) {
975 Either<GraphVertex, TitanOperationStatus> getVertexEither = titanDao.getVertexById(componentId, JsonParseFlagEnum.NoParse);
976 if (getVertexEither.isRight()) {
977 log.debug("Couldn't fetch component with and unique id {}, error: {}", componentId, getVertexEither.right().value());
978 return Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(getVertexEither.right().value()));
982 Either<ToscaElement, StorageOperationStatus> toscaElement =
983 topologyTemplateOperation.getToscaElement(componentId);
984 if(toscaElement.isRight()) {
985 return Either.right(toscaElement.right().value());
988 TopologyTemplate topologyTemplate = (TopologyTemplate) toscaElement.left().value();
990 Map<String, PropertyDataDefinition> inputsMap = topologyTemplate.getInputs();
992 List<InputDefinition> inputs = new ArrayList<>();
993 if(MapUtils.isNotEmpty(inputsMap)) {
995 inputsMap.values().stream().map(p -> new InputDefinition(p)).collect(Collectors.toList());
998 return Either.left(inputs);
1001 public Either<List<InputDefinition>, StorageOperationStatus> updateInputsToComponent(List<InputDefinition> inputs, String componentId) {
1003 Either<GraphVertex, TitanOperationStatus> getVertexEither = titanDao.getVertexById(componentId, JsonParseFlagEnum.NoParse);
1004 if (getVertexEither.isRight()) {
1005 log.debug(COULDNT_FETCH_COMPONENT_WITH_AND_UNIQUE_ID_ERROR, componentId, getVertexEither.right().value());
1006 return Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(getVertexEither.right().value()));
1010 GraphVertex vertex = getVertexEither.left().value();
1011 List<PropertyDataDefinition> inputsAsDataDef = inputs.stream().map(PropertyDataDefinition::new).collect(Collectors.toList());
1013 StorageOperationStatus status = topologyTemplateOperation.updateToscaDataOfToscaElement(vertex, EdgeLabelEnum.INPUTS, VertexTypeEnum.INPUTS, inputsAsDataDef, JsonPresentationFields.NAME);
1015 if (StorageOperationStatus.OK == status) {
1016 log.debug(COMPONENT_CREATED_SUCCESSFULLY);
1017 List<InputDefinition> inputsResList = null;
1018 if (inputsAsDataDef != null && !inputsAsDataDef.isEmpty()) {
1019 inputsResList = inputsAsDataDef.stream().map(InputDefinition::new).collect(Collectors.toList());
1021 return Either.left(inputsResList);
1023 return Either.right(status);
1027 // region - ComponentInstance
1028 public Either<Map<String, List<ComponentInstanceProperty>>, StorageOperationStatus> associateComponentInstancePropertiesToComponent(Map<String, List<ComponentInstanceProperty>> instProperties, String componentId) {
1030 Either<GraphVertex, TitanOperationStatus> getVertexEither = titanDao.getVertexById(componentId, JsonParseFlagEnum.NoParse);
1031 if (getVertexEither.isRight()) {
1032 log.debug(COULDNT_FETCH_COMPONENT_WITH_AND_UNIQUE_ID_ERROR, componentId, getVertexEither.right().value());
1033 return Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(getVertexEither.right().value()));
1037 GraphVertex vertex = getVertexEither.left().value();
1038 Map<String, MapPropertiesDataDefinition> instPropsMap = new HashMap<>();
1039 if (instProperties != null) {
1041 MapPropertiesDataDefinition propertiesMap;
1042 for (Entry<String, List<ComponentInstanceProperty>> entry : instProperties.entrySet()) {
1043 propertiesMap = new MapPropertiesDataDefinition();
1045 propertiesMap.setMapToscaDataDefinition(entry.getValue().stream().map(PropertyDataDefinition::new).collect(Collectors.toMap(PropertyDataDefinition::getName, e -> e)));
1047 instPropsMap.put(entry.getKey(), propertiesMap);
1051 StorageOperationStatus status = topologyTemplateOperation.associateInstPropertiesToComponent(vertex, instPropsMap);
1053 if (StorageOperationStatus.OK == status) {
1054 log.debug(COMPONENT_CREATED_SUCCESSFULLY);
1055 return Either.left(instProperties);
1057 return Either.right(status);
1062 * saves the instInputs as the updated instance inputs of the component container in DB
1064 public Either<Map<String, List<ComponentInstanceInput>>, StorageOperationStatus> updateComponentInstanceInputsToComponent(Map<String, List<ComponentInstanceInput>> instInputs, String componentId) {
1065 if (instInputs == null || instInputs.isEmpty()) {
1066 return Either.left(instInputs);
1068 StorageOperationStatus status;
1069 for (Entry<String, List<ComponentInstanceInput>> inputsPerIntance : instInputs.entrySet()) {
1070 List<ComponentInstanceInput> toscaDataListPerInst = inputsPerIntance.getValue();
1071 List<String> pathKeysPerInst = new ArrayList<>();
1072 pathKeysPerInst.add(inputsPerIntance.getKey());
1073 status = topologyTemplateOperation.updateToscaDataDeepElementsOfToscaElement(componentId, EdgeLabelEnum.INST_INPUTS, VertexTypeEnum.INST_INPUTS, toscaDataListPerInst, pathKeysPerInst, JsonPresentationFields.NAME);
1074 if (status != StorageOperationStatus.OK) {
1075 log.debug("Failed to update component instance inputs for instance {} in component {} edge type {} error {}", inputsPerIntance.getKey(), componentId, EdgeLabelEnum.INST_INPUTS, status);
1076 return Either.right(status);
1080 return Either.left(instInputs);
1084 * saves the instProps as the updated instance properties of the component container in DB
1086 public Either<Map<String, List<ComponentInstanceProperty>>, StorageOperationStatus> updateComponentInstancePropsToComponent(Map<String, List<ComponentInstanceProperty>> instProps, String componentId) {
1087 if (instProps == null || instProps.isEmpty()) {
1088 return Either.left(instProps);
1090 StorageOperationStatus status;
1091 for (Entry<String, List<ComponentInstanceProperty>> propsPerIntance : instProps.entrySet()) {
1092 List<ComponentInstanceProperty> toscaDataListPerInst = propsPerIntance.getValue();
1093 List<String> pathKeysPerInst = new ArrayList<>();
1094 pathKeysPerInst.add(propsPerIntance.getKey());
1095 status = topologyTemplateOperation.updateToscaDataDeepElementsOfToscaElement(componentId, EdgeLabelEnum.INST_PROPERTIES, VertexTypeEnum.INST_PROPERTIES, toscaDataListPerInst, pathKeysPerInst, JsonPresentationFields.NAME);
1096 if (status != StorageOperationStatus.OK) {
1097 log.debug("Failed to update component instance inputs for instance {} in component {} edge type {} error {}", propsPerIntance.getKey(), componentId, EdgeLabelEnum.INST_PROPERTIES, status);
1098 return Either.right(status);
1102 return Either.left(instProps);
1105 public Either<Map<String, List<ComponentInstanceInput>>, StorageOperationStatus> associateComponentInstanceInputsToComponent(Map<String, List<ComponentInstanceInput>> instInputs, String componentId) {
1107 Either<GraphVertex, TitanOperationStatus> getVertexEither = titanDao.getVertexById(componentId, JsonParseFlagEnum.NoParse);
1108 if (getVertexEither.isRight()) {
1109 log.debug(COULDNT_FETCH_COMPONENT_WITH_AND_UNIQUE_ID_ERROR, componentId, getVertexEither.right().value());
1110 return Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(getVertexEither.right().value()));
1113 GraphVertex vertex = getVertexEither.left().value();
1114 Map<String, MapPropertiesDataDefinition> instPropsMap = new HashMap<>();
1115 if (instInputs != null) {
1117 MapPropertiesDataDefinition propertiesMap;
1118 for (Entry<String, List<ComponentInstanceInput>> entry : instInputs.entrySet()) {
1119 propertiesMap = new MapPropertiesDataDefinition();
1121 propertiesMap.setMapToscaDataDefinition(entry.getValue().stream().map(PropertyDataDefinition::new).collect(Collectors.toMap(PropertyDataDefinition::getName, e -> e)));
1123 instPropsMap.put(entry.getKey(), propertiesMap);
1127 StorageOperationStatus status = topologyTemplateOperation.associateInstInputsToComponent(vertex, instPropsMap);
1129 if (StorageOperationStatus.OK == status) {
1130 log.debug(COMPONENT_CREATED_SUCCESSFULLY);
1131 return Either.left(instInputs);
1133 return Either.right(status);
1137 public Either<Map<String, List<ComponentInstanceInput>>, StorageOperationStatus> addComponentInstanceInputsToComponent(Component containerComponent, Map<String, List<ComponentInstanceInput>> instProperties) {
1138 requireNonNull(instProperties);
1139 StorageOperationStatus status;
1140 for (Entry<String, List<ComponentInstanceInput>> entry : instProperties.entrySet()) {
1141 List<ComponentInstanceInput> props = entry.getValue();
1142 String componentInstanceId = entry.getKey();
1143 if (!isEmpty(props)) {
1144 for (ComponentInstanceInput property : props) {
1145 List<ComponentInstanceInput> componentInstancesInputs = containerComponent.getComponentInstancesInputs().get(componentInstanceId);
1146 Optional<ComponentInstanceInput> instanceProperty = componentInstancesInputs.stream()
1147 .filter(p -> p.getName().equals(property.getName()))
1149 if (instanceProperty.isPresent()) {
1150 status = updateComponentInstanceInput(containerComponent, componentInstanceId, property);
1152 status = addComponentInstanceInput(containerComponent, componentInstanceId, property);
1154 if (status != StorageOperationStatus.OK) {
1155 log.debug("Failed to update instance input {} for instance {} error {} ", property, componentInstanceId, status);
1156 return Either.right(status);
1158 log.trace("instance input {} for instance {} updated", property, componentInstanceId);
1163 return Either.left(instProperties);
1166 public Either<Map<String, List<ComponentInstanceProperty>>, StorageOperationStatus> addComponentInstancePropertiesToComponent(Component containerComponent, Map<String, List<ComponentInstanceProperty>> instProperties) {
1167 requireNonNull(instProperties);
1168 StorageOperationStatus status;
1169 for (Entry<String, List<ComponentInstanceProperty>> entry : instProperties.entrySet()) {
1170 List<ComponentInstanceProperty> props = entry.getValue();
1171 String componentInstanceId = entry.getKey();
1172 List<ComponentInstanceProperty> instanceProperties = containerComponent.getComponentInstancesProperties().get(componentInstanceId);
1173 if (!isEmpty(props)) {
1174 for (ComponentInstanceProperty property : props) {
1175 Optional<ComponentInstanceProperty> instanceProperty = instanceProperties.stream()
1176 .filter(p -> p.getUniqueId().equals(property.getUniqueId()))
1178 if (instanceProperty.isPresent()) {
1179 status = updateComponentInstanceProperty(containerComponent, componentInstanceId, property);
1181 status = addComponentInstanceProperty(containerComponent, componentInstanceId, property);
1183 if (status != StorageOperationStatus.OK) {
1184 log.debug("Failed to update instance property {} for instance {} error {} ", property, componentInstanceId, status);
1185 return Either.right(status);
1190 return Either.left(instProperties);
1193 public StorageOperationStatus associateDeploymentArtifactsToInstances(Map<String, Map<String, ArtifactDefinition>> instDeploymentArtifacts, String componentId, User user) {
1195 Either<GraphVertex, TitanOperationStatus> getVertexEither = titanDao.getVertexById(componentId, JsonParseFlagEnum.NoParse);
1196 if (getVertexEither.isRight()) {
1197 log.debug(COULDNT_FETCH_COMPONENT_WITH_AND_UNIQUE_ID_ERROR, componentId, getVertexEither.right().value());
1198 return DaoStatusConverter.convertTitanStatusToStorageStatus(getVertexEither.right().value());
1202 GraphVertex vertex = getVertexEither.left().value();
1203 Map<String, MapArtifactDataDefinition> instArtMap = new HashMap<>();
1204 if (instDeploymentArtifacts != null) {
1206 MapArtifactDataDefinition artifactsMap;
1207 for (Entry<String, Map<String, ArtifactDefinition>> entry : instDeploymentArtifacts.entrySet()) {
1208 Map<String, ArtifactDefinition> artList = entry.getValue();
1209 Map<String, ArtifactDataDefinition> artifacts = artList.entrySet().stream().collect(Collectors.toMap(Map.Entry::getKey, e -> new ArtifactDataDefinition(e.getValue())));
1210 artifactsMap = nodeTemplateOperation.prepareInstDeploymentArtifactPerInstance(artifacts, entry.getKey(), user, NodeTemplateOperation.HEAT_VF_ENV_NAME);
1212 instArtMap.put(entry.getKey(), artifactsMap);
1216 return topologyTemplateOperation.associateInstDeploymentArtifactsToComponent(vertex, instArtMap);
1220 public StorageOperationStatus associateArtifactsToInstances(Map<String, Map<String, ArtifactDefinition>> instArtifacts, String componentId) {
1222 Either<GraphVertex, TitanOperationStatus> getVertexEither = titanDao.getVertexById(componentId, JsonParseFlagEnum.NoParse);
1223 if (getVertexEither.isRight()) {
1224 log.debug(COULDNT_FETCH_COMPONENT_WITH_AND_UNIQUE_ID_ERROR, componentId, getVertexEither.right().value());
1225 return DaoStatusConverter.convertTitanStatusToStorageStatus(getVertexEither.right().value());
1229 GraphVertex vertex = getVertexEither.left().value();
1230 Map<String, MapArtifactDataDefinition> instArtMap = new HashMap<>();
1231 if (instArtifacts != null) {
1233 MapArtifactDataDefinition artifactsMap;
1234 for (Entry<String, Map<String, ArtifactDefinition>> entry : instArtifacts.entrySet()) {
1235 Map<String, ArtifactDefinition> artList = entry.getValue();
1236 Map<String, ArtifactDataDefinition> artifacts = artList.entrySet().stream().collect(Collectors.toMap(Map.Entry::getKey, e -> new ArtifactDataDefinition(e.getValue())));
1237 artifactsMap = new MapArtifactDataDefinition(artifacts);
1239 instArtMap.put(entry.getKey(), artifactsMap);
1243 return topologyTemplateOperation.associateInstArtifactsToComponent(vertex, instArtMap);
1247 public StorageOperationStatus associateInstAttributeToComponentToInstances(Map<String, List<PropertyDefinition>> instArttributes, String componentId) {
1249 Either<GraphVertex, TitanOperationStatus> getVertexEither = titanDao.getVertexById(componentId, JsonParseFlagEnum.NoParse);
1250 if (getVertexEither.isRight()) {
1251 log.debug(COULDNT_FETCH_COMPONENT_WITH_AND_UNIQUE_ID_ERROR, componentId, getVertexEither.right().value());
1252 return DaoStatusConverter.convertTitanStatusToStorageStatus(getVertexEither.right().value());
1256 GraphVertex vertex = getVertexEither.left().value();
1257 Map<String, MapPropertiesDataDefinition> instAttr = new HashMap<>();
1258 if (instArttributes != null) {
1260 MapPropertiesDataDefinition attributesMap;
1261 for (Entry<String, List<PropertyDefinition>> entry : instArttributes.entrySet()) {
1262 attributesMap = new MapPropertiesDataDefinition();
1263 attributesMap.setMapToscaDataDefinition(entry.getValue().stream().map(PropertyDataDefinition::new).collect(Collectors.toMap(PropertyDataDefinition::getName, e -> e)));
1264 instAttr.put(entry.getKey(), attributesMap);
1268 return topologyTemplateOperation.associateInstAttributeToComponent(vertex, instAttr);
1273 public StorageOperationStatus associateOrAddCalculatedCapReq(Map<ComponentInstance, Map<String, List<CapabilityDefinition>>> instCapabilties, Map<ComponentInstance, Map<String, List<RequirementDefinition>>> instReg, String componentId) {
1274 Either<GraphVertex, TitanOperationStatus> getVertexEither = titanDao.getVertexById(componentId, JsonParseFlagEnum.NoParse);
1275 if (getVertexEither.isRight()) {
1276 log.debug(COULDNT_FETCH_COMPONENT_WITH_AND_UNIQUE_ID_ERROR, componentId, getVertexEither.right().value());
1277 return DaoStatusConverter.convertTitanStatusToStorageStatus(getVertexEither.right().value());
1281 GraphVertex vertex = getVertexEither.left().value();
1283 Map<String, MapListRequirementDataDefinition> calcRequirements = new HashMap<>();
1285 Map<String, MapListCapabilityDataDefinition> calcCapabilty = new HashMap<>();
1286 Map<String, MapCapabilityProperty> calculatedCapabilitiesProperties = new HashMap<>();
1287 if (instCapabilties != null) {
1288 for (Entry<ComponentInstance, Map<String, List<CapabilityDefinition>>> entry : instCapabilties.entrySet()) {
1290 Map<String, List<CapabilityDefinition>> caps = entry.getValue();
1291 Map<String, ListCapabilityDataDefinition> mapToscaDataDefinition = new HashMap<>();
1292 for (Entry<String, List<CapabilityDefinition>> instCapability : caps.entrySet()) {
1293 mapToscaDataDefinition.put(instCapability.getKey(), new ListCapabilityDataDefinition(instCapability.getValue().stream().map(CapabilityDataDefinition::new).collect(Collectors.toList())));
1296 ComponentInstanceDataDefinition componentInstance = new ComponentInstanceDataDefinition(entry.getKey());
1297 MapListCapabilityDataDefinition capMap = nodeTemplateOperation.prepareCalculatedCapabiltyForNodeType(mapToscaDataDefinition, componentInstance);
1299 MapCapabilityProperty mapCapabilityProperty = ModelConverter.convertToMapOfMapCapabiltyProperties(caps, componentInstance.getUniqueId(), true);
1301 calcCapabilty.put(entry.getKey().getUniqueId(), capMap);
1302 calculatedCapabilitiesProperties.put(entry.getKey().getUniqueId(), mapCapabilityProperty);
1306 if (instReg != null) {
1307 for (Entry<ComponentInstance, Map<String, List<RequirementDefinition>>> entry : instReg.entrySet()) {
1309 Map<String, List<RequirementDefinition>> req = entry.getValue();
1310 Map<String, ListRequirementDataDefinition> mapToscaDataDefinition = new HashMap<>();
1311 for (Entry<String, List<RequirementDefinition>> instReq : req.entrySet()) {
1312 mapToscaDataDefinition.put(instReq.getKey(), new ListRequirementDataDefinition(instReq.getValue().stream().map(RequirementDataDefinition::new).collect(Collectors.toList())));
1315 MapListRequirementDataDefinition capMap = nodeTemplateOperation.prepareCalculatedRequirementForNodeType(mapToscaDataDefinition, new ComponentInstanceDataDefinition(entry.getKey()));
1317 calcRequirements.put(entry.getKey().getUniqueId(), capMap);
1321 return topologyTemplateOperation.associateOrAddCalcCapReqToComponent(vertex, calcRequirements, calcCapabilty, calculatedCapabilitiesProperties);
1324 private Either<List<Service>, StorageOperationStatus> getLatestVersionNonCheckoutServicesMetadataOnly(Map<GraphPropertyEnum, Object> hasProps, Map<GraphPropertyEnum, Object> hasNotProps) {
1325 List<Service> services = new ArrayList<>();
1326 List<LifecycleStateEnum> states = new ArrayList<>();
1328 hasProps.put(GraphPropertyEnum.COMPONENT_TYPE, ComponentTypeEnum.SERVICE.name());
1329 hasProps.put(GraphPropertyEnum.IS_HIGHEST_VERSION, true);
1332 states.add(LifecycleStateEnum.NOT_CERTIFIED_CHECKOUT);
1333 hasNotProps.put(GraphPropertyEnum.STATE, states);
1334 hasNotProps.put(GraphPropertyEnum.IS_DELETED, true);
1335 hasNotProps.put(GraphPropertyEnum.IS_ARCHIVED, true);
1336 return fetchServicesByCriteria(services, hasProps, hasNotProps);
1339 private Either<List<Component>, StorageOperationStatus> getLatestVersionNotAbstractToscaElementsMetadataOnly(boolean isAbstract, ComponentTypeEnum componentTypeEnum, String internalComponentType, VertexTypeEnum vertexType) {
1340 List<Service> services = null;
1341 Map<GraphPropertyEnum, Object> hasProps = new EnumMap<>(GraphPropertyEnum.class);
1342 Map<GraphPropertyEnum, Object> hasNotProps = new EnumMap<>(GraphPropertyEnum.class);
1343 fillPropsMap(hasProps, hasNotProps, internalComponentType, componentTypeEnum, isAbstract, vertexType);
1344 Either<List<GraphVertex>, TitanOperationStatus> getRes = titanDao.getByCriteria(vertexType, hasProps, hasNotProps, JsonParseFlagEnum.ParseMetadata);
1345 if (getRes.isRight()) {
1346 if (getRes.right().value().equals(TitanOperationStatus.NOT_FOUND)) {
1347 return Either.left(new ArrayList<>());
1349 return Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(getRes.right().value()));
1352 // region -> Fetch non checked-out services
1353 if (internalComponentType != null && internalComponentType.toLowerCase().trim().equals(SERVICE) && VertexTypeEnum.NODE_TYPE == vertexType) {
1354 Either<List<Service>, StorageOperationStatus> result = getLatestVersionNonCheckoutServicesMetadataOnly(new EnumMap<>(GraphPropertyEnum.class), new EnumMap<>(GraphPropertyEnum.class));
1355 if (result.isRight()) {
1356 log.debug("Failed to fetch services for");
1357 return Either.right(result.right().value());
1359 services = result.left().value();
1360 if (log.isTraceEnabled() && isEmpty(services))
1361 log.trace("No relevant services available");
1364 List<Component> nonAbstractLatestComponents = new ArrayList<>();
1365 ComponentParametersView params = new ComponentParametersView(true);
1366 params.setIgnoreAllVersions(false);
1367 for (GraphVertex vertexComponent : getRes.left().value()) {
1368 Either<ToscaElement, StorageOperationStatus> componentRes = topologyTemplateOperation.getLightComponent(vertexComponent, componentTypeEnum, params);
1369 if (componentRes.isRight()) {
1370 log.debug("Failed to fetch light element for {} error {}", vertexComponent.getUniqueId(), componentRes.right().value());
1371 return Either.right(componentRes.right().value());
1373 Component component = ModelConverter.convertFromToscaElement(componentRes.left().value());
1374 nonAbstractLatestComponents.add(component);
1377 if (CollectionUtils.isNotEmpty(services)) {
1378 nonAbstractLatestComponents.addAll(services);
1380 return Either.left(nonAbstractLatestComponents);
1383 public Either<ComponentMetadataData, StorageOperationStatus> getLatestComponentMetadataByUuid(String componentUuid, JsonParseFlagEnum parseFlag, Boolean isHighest) {
1385 Either<ComponentMetadataData, StorageOperationStatus> result;
1386 Map<GraphPropertyEnum, Object> hasProperties = new EnumMap<>(GraphPropertyEnum.class);
1387 hasProperties.put(GraphPropertyEnum.UUID, componentUuid);
1388 if (isHighest != null) {
1389 hasProperties.put(GraphPropertyEnum.IS_HIGHEST_VERSION, isHighest);
1391 Map<GraphPropertyEnum, Object> propertiesNotToMatch = new EnumMap<>(GraphPropertyEnum.class);
1392 propertiesNotToMatch.put(GraphPropertyEnum.IS_DELETED, true);
1393 propertiesNotToMatch.put(GraphPropertyEnum.IS_ARCHIVED, true); //US382674, US382683
1395 Either<List<GraphVertex>, TitanOperationStatus> getRes = titanDao.getByCriteria(null, hasProperties, propertiesNotToMatch, parseFlag);
1396 if (getRes.isRight()) {
1397 result = Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(getRes.right().value()));
1399 List<ComponentMetadataData> latestVersionList = getRes.left().value().stream().map(ModelConverter::convertToComponentMetadata).collect(Collectors.toList());
1400 ComponentMetadataData latestVersion = latestVersionList.size() == 1 ? latestVersionList.get(0)
1401 : latestVersionList.stream().max((c1, c2) -> Double.compare(Double.parseDouble(c1.getMetadataDataDefinition().getVersion()), Double.parseDouble(c2.getMetadataDataDefinition().getVersion()))).get();
1402 result = Either.left(latestVersion);
1407 public Either<ComponentMetadataData, StorageOperationStatus> getComponentMetadata(String componentId) {
1408 Either<ComponentMetadataData, StorageOperationStatus> result;
1409 Either<GraphVertex, TitanOperationStatus> getRes = titanDao.getVertexById(componentId, JsonParseFlagEnum.ParseMetadata);
1410 if (getRes.isRight()) {
1411 result = Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(getRes.right().value()));
1413 ComponentMetadataData componentMetadata = ModelConverter.convertToComponentMetadata(getRes.left().value());
1414 result = Either.left(componentMetadata);
1419 public Either<List<Component>, StorageOperationStatus> getLatestVersionNotAbstractComponents(boolean isAbstract, ComponentTypeEnum componentTypeEnum,
1420 String internalComponentType, List<String> componentUids) {
1422 List<Component> components = new ArrayList<>();
1423 if (componentUids == null) {
1424 Either<List<String>, StorageOperationStatus> componentUidsRes = getComponentUids(isAbstract, componentTypeEnum, internalComponentType);
1425 if (componentUidsRes.isRight()) {
1426 return Either.right(componentUidsRes.right().value());
1428 componentUids = componentUidsRes.left().value();
1430 if (!isEmpty(componentUids)) {
1431 for (String componentUid : componentUids) {
1432 ComponentParametersView componentParametersView = buildComponentViewForNotAbstract();
1433 if ("vl".equalsIgnoreCase(internalComponentType)) {
1434 componentParametersView.setIgnoreCapabilities(false);
1435 componentParametersView.setIgnoreRequirements(false);
1437 Either<ToscaElement, StorageOperationStatus> getToscaElementRes = nodeTemplateOperation.getToscaElementOperation(componentTypeEnum).getLightComponent(componentUid, componentTypeEnum, componentParametersView);
1438 if (getToscaElementRes.isRight()) {
1439 log.debug("Failed to fetch resource for error is {}", getToscaElementRes.right().value());
1440 return Either.right(getToscaElementRes.right().value());
1442 Component component = ModelConverter.convertFromToscaElement(getToscaElementRes.left().value());
1443 nullifySomeComponentProperties(component);
1444 components.add(component);
1447 return Either.left(components);
1450 public void nullifySomeComponentProperties(Component component) {
1451 component.setContactId(null);
1452 component.setCreationDate(null);
1453 component.setCreatorUserId(null);
1454 component.setCreatorFullName(null);
1455 component.setLastUpdateDate(null);
1456 component.setLastUpdaterUserId(null);
1457 component.setLastUpdaterFullName(null);
1458 component.setNormalizedName(null);
1461 private Either<List<String>, StorageOperationStatus> getComponentUids(boolean isAbstract, ComponentTypeEnum componentTypeEnum, String internalComponentType) {
1463 Either<List<Component>, StorageOperationStatus> getToscaElementsRes = getLatestVersionNotAbstractMetadataOnly(isAbstract, componentTypeEnum, internalComponentType);
1464 if (getToscaElementsRes.isRight()) {
1465 return Either.right(getToscaElementsRes.right().value());
1467 List<Component> collection = getToscaElementsRes.left().value();
1468 List<String> componentUids;
1469 if (collection == null) {
1470 componentUids = new ArrayList<>();
1472 componentUids = collection.stream()
1473 .map(Component::getUniqueId)
1474 .collect(Collectors.toList());
1476 return Either.left(componentUids);
1479 private ComponentParametersView buildComponentViewForNotAbstract() {
1480 ComponentParametersView componentParametersView = new ComponentParametersView();
1481 componentParametersView.disableAll();
1482 componentParametersView.setIgnoreCategories(false);
1483 componentParametersView.setIgnoreAllVersions(false);
1484 return componentParametersView;
1487 public Either<Boolean, StorageOperationStatus> validateComponentNameExists(String name, ResourceTypeEnum resourceType, ComponentTypeEnum componentType) {
1488 Either<Boolean, StorageOperationStatus> result = validateComponentNameUniqueness(name, resourceType, componentType);
1489 if (result.isLeft()) {
1490 result = Either.left(!result.left().value());
1495 public Either<Boolean, StorageOperationStatus> validateComponentNameUniqueness(String name, ResourceTypeEnum resourceType, ComponentTypeEnum componentType) {
1496 VertexTypeEnum vertexType = ModelConverter.isAtomicComponent(resourceType) ? VertexTypeEnum.NODE_TYPE : VertexTypeEnum.TOPOLOGY_TEMPLATE;
1497 String normalizedName = ValidationUtils.normaliseComponentName(name);
1498 Map<GraphPropertyEnum, Object> properties = new EnumMap<>(GraphPropertyEnum.class);
1499 properties.put(GraphPropertyEnum.NORMALIZED_NAME, normalizedName);
1500 properties.put(GraphPropertyEnum.COMPONENT_TYPE, componentType.name());
1502 Either<List<GraphVertex>, TitanOperationStatus> vertexEither = titanDao.getByCriteria(vertexType, properties, JsonParseFlagEnum.NoParse);
1503 if (vertexEither.isRight() && vertexEither.right().value() != TitanOperationStatus.NOT_FOUND) {
1504 log.debug("failed to get vertex from graph with property normalizedName: {}", normalizedName);
1505 return Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(vertexEither.right().value()));
1507 List<GraphVertex> vertexList = vertexEither.isLeft() ? vertexEither.left().value() : null;
1508 if (vertexList != null && !vertexList.isEmpty()) {
1509 return Either.left(false);
1511 return Either.left(true);
1515 private void fillNodeTypePropsMap(Map<GraphPropertyEnum, Object> hasProps, Map<GraphPropertyEnum, Object> hasNotProps, String internalComponentType) {
1516 switch (internalComponentType.toLowerCase()) {
1519 hasNotProps.put(GraphPropertyEnum.RESOURCE_TYPE, Arrays.asList(ResourceTypeEnum.VFCMT.name(), ResourceTypeEnum.Configuration.name()));
1524 hasNotProps.put(GraphPropertyEnum.RESOURCE_TYPE, Arrays.asList(ResourceTypeEnum.VFC.name(), ResourceTypeEnum.VFCMT.name()));
1527 hasProps.put(GraphPropertyEnum.RESOURCE_TYPE, ResourceTypeEnum.VL.name());
1534 private void fillTopologyTemplatePropsMap(Map<GraphPropertyEnum, Object> hasProps, Map<GraphPropertyEnum, Object> hasNotProps, ComponentTypeEnum componentTypeEnum) {
1535 switch (componentTypeEnum) {
1537 hasProps.put(GraphPropertyEnum.COMPONENT_TYPE, ComponentTypeEnum.RESOURCE.name());
1540 hasProps.put(GraphPropertyEnum.COMPONENT_TYPE, ComponentTypeEnum.SERVICE.name());
1545 hasNotProps.put(GraphPropertyEnum.RESOURCE_TYPE, ResourceTypeEnum.CVFC.name());
1548 private void fillPropsMap(Map<GraphPropertyEnum, Object> hasProps, Map<GraphPropertyEnum, Object> hasNotProps, String internalComponentType, ComponentTypeEnum componentTypeEnum, boolean isAbstract, VertexTypeEnum internalVertexType) {
1549 hasNotProps.put(GraphPropertyEnum.STATE, LifecycleStateEnum.NOT_CERTIFIED_CHECKOUT.name());
1551 hasNotProps.put(GraphPropertyEnum.IS_DELETED, true);
1552 hasNotProps.put(GraphPropertyEnum.IS_ARCHIVED, true);
1553 hasProps.put(GraphPropertyEnum.IS_HIGHEST_VERSION, true);
1554 if (VertexTypeEnum.NODE_TYPE == internalVertexType) {
1555 hasProps.put(GraphPropertyEnum.IS_ABSTRACT, isAbstract);
1556 if (internalComponentType != null) {
1557 fillNodeTypePropsMap(hasProps, hasNotProps, internalComponentType);
1560 fillTopologyTemplatePropsMap(hasProps, hasNotProps, componentTypeEnum);
1564 private List<VertexTypeEnum> getInternalVertexTypes(ComponentTypeEnum componentTypeEnum, String internalComponentType) {
1565 List<VertexTypeEnum> internalVertexTypes = new ArrayList<>();
1566 if (ComponentTypeEnum.RESOURCE == componentTypeEnum) {
1567 internalVertexTypes.add(VertexTypeEnum.NODE_TYPE);
1569 if (ComponentTypeEnum.SERVICE == componentTypeEnum || SERVICE.equalsIgnoreCase(internalComponentType)) {
1570 internalVertexTypes.add(VertexTypeEnum.TOPOLOGY_TEMPLATE);
1572 return internalVertexTypes;
1575 public Either<List<Component>, StorageOperationStatus> getLatestVersionNotAbstractMetadataOnly(boolean isAbstract, ComponentTypeEnum componentTypeEnum, String internalComponentType) {
1576 List<VertexTypeEnum> internalVertexTypes = getInternalVertexTypes(componentTypeEnum, internalComponentType);
1577 List<Component> result = new ArrayList<>();
1578 for (VertexTypeEnum vertexType : internalVertexTypes) {
1579 Either<List<Component>, StorageOperationStatus> listByVertexType = getLatestVersionNotAbstractToscaElementsMetadataOnly(isAbstract, componentTypeEnum, internalComponentType, vertexType);
1580 if (listByVertexType.isRight()) {
1581 return listByVertexType;
1583 result.addAll(listByVertexType.left().value());
1585 return Either.left(result);
1589 private Either<List<Component>, StorageOperationStatus> getLatestComponentListByUuid(String componentUuid, Map<GraphPropertyEnum, Object> additionalPropertiesToMatch) {
1590 Map<GraphPropertyEnum, Object> propertiesToMatch = new EnumMap<>(GraphPropertyEnum.class);
1591 if (additionalPropertiesToMatch != null) {
1592 propertiesToMatch.putAll(additionalPropertiesToMatch);
1594 propertiesToMatch.put(GraphPropertyEnum.IS_HIGHEST_VERSION, true);
1595 return getComponentListByUuid(componentUuid, propertiesToMatch);
1598 public Either<Component, StorageOperationStatus> getComponentByUuidAndVersion(String componentUuid, String version) {
1599 Map<GraphPropertyEnum, Object> propertiesToMatch = new EnumMap<>(GraphPropertyEnum.class);
1601 propertiesToMatch.put(GraphPropertyEnum.UUID, componentUuid);
1602 propertiesToMatch.put(GraphPropertyEnum.VERSION, version);
1604 Map<GraphPropertyEnum, Object> propertiesNotToMatch = new EnumMap<>(GraphPropertyEnum.class);
1605 propertiesNotToMatch.put(GraphPropertyEnum.IS_DELETED, true);
1606 Either<List<GraphVertex>, TitanOperationStatus> vertexEither = titanDao.getByCriteria(null, propertiesToMatch, propertiesNotToMatch, JsonParseFlagEnum.ParseAll);
1607 if (vertexEither.isRight()) {
1608 return Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(vertexEither.right().value()));
1611 List<GraphVertex> vertexList = vertexEither.isLeft() ? vertexEither.left().value() : null;
1612 if (vertexList == null || vertexList.isEmpty() || vertexList.size() > 1) {
1613 return Either.right(StorageOperationStatus.NOT_FOUND);
1616 return getToscaElementByOperation(vertexList.get(0));
1619 public Either<List<Component>, StorageOperationStatus> getComponentListByUuid(String componentUuid, Map<GraphPropertyEnum, Object> additionalPropertiesToMatch) {
1621 Map<GraphPropertyEnum, Object> propertiesToMatch = new EnumMap<>(GraphPropertyEnum.class);
1623 if (additionalPropertiesToMatch != null) {
1624 propertiesToMatch.putAll(additionalPropertiesToMatch);
1627 propertiesToMatch.put(GraphPropertyEnum.UUID, componentUuid);
1629 Map<GraphPropertyEnum, Object> propertiesNotToMatch = new EnumMap<>(GraphPropertyEnum.class);
1630 propertiesNotToMatch.put(GraphPropertyEnum.IS_DELETED, true);
1631 propertiesNotToMatch.put(GraphPropertyEnum.IS_ARCHIVED, true); //US382674, US382683
1633 Either<List<GraphVertex>, TitanOperationStatus> vertexEither = titanDao.getByCriteria(null, propertiesToMatch, propertiesNotToMatch, JsonParseFlagEnum.ParseAll);
1635 if (vertexEither.isRight()) {
1636 log.debug("Couldn't fetch metadata for component with uuid {}, error: {}", componentUuid, vertexEither.right().value());
1637 return Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(vertexEither.right().value()));
1639 List<GraphVertex> vertexList = vertexEither.isLeft() ? vertexEither.left().value() : null;
1641 if (vertexList == null || vertexList.isEmpty()) {
1642 log.debug("Component with uuid {} was not found", componentUuid);
1643 return Either.right(StorageOperationStatus.NOT_FOUND);
1646 ArrayList<Component> latestComponents = new ArrayList<>();
1647 for (GraphVertex vertex : vertexList) {
1648 Either<Component, StorageOperationStatus> toscaElementByOperation = getToscaElementByOperation(vertex);
1650 if (toscaElementByOperation.isRight()) {
1651 log.debug("Could not fetch the following Component by UUID {}", vertex.getUniqueId());
1652 return Either.right(toscaElementByOperation.right().value());
1655 latestComponents.add(toscaElementByOperation.left().value());
1658 if (latestComponents.size() > 1) {
1659 for (Component component : latestComponents) {
1660 if (component.isHighestVersion()) {
1661 LinkedList<Component> highestComponent = new LinkedList<>();
1662 highestComponent.add(component);
1663 return Either.left(highestComponent);
1668 return Either.left(latestComponents);
1671 public Either<Component, StorageOperationStatus> getLatestServiceByUuid(String serviceUuid) {
1672 Map<GraphPropertyEnum, Object> propertiesToMatch = new EnumMap<>(GraphPropertyEnum.class);
1673 propertiesToMatch.put(GraphPropertyEnum.COMPONENT_TYPE, ComponentTypeEnum.SERVICE.name());
1674 return getLatestComponentByUuid(serviceUuid, propertiesToMatch);
1677 public Either<Component, StorageOperationStatus> getLatestComponentByUuid(String componentUuid) {
1678 return getLatestComponentByUuid(componentUuid, null);
1681 public Either<Component, StorageOperationStatus> getLatestComponentByUuid(String componentUuid, Map<GraphPropertyEnum, Object> propertiesToMatch) {
1683 Either<List<Component>, StorageOperationStatus> latestVersionListEither = getLatestComponentListByUuid(componentUuid, propertiesToMatch);
1685 if (latestVersionListEither.isRight()) {
1686 return Either.right(latestVersionListEither.right().value());
1689 List<Component> latestVersionList = latestVersionListEither.left().value();
1691 if (latestVersionList.isEmpty()) {
1692 return Either.right(StorageOperationStatus.NOT_FOUND);
1694 Component component = latestVersionList.size() == 1 ? latestVersionList.get(0) : latestVersionList.stream().max((c1, c2) -> Double.compare(Double.parseDouble(c1.getVersion()), Double.parseDouble(c2.getVersion()))).get();
1696 return Either.left(component);
1699 public Either<List<Resource>, StorageOperationStatus> getAllCertifiedResources(boolean isAbstract, Boolean isHighest) {
1701 List<Resource> resources = new ArrayList<>();
1702 Map<GraphPropertyEnum, Object> propertiesToMatch = new EnumMap<>(GraphPropertyEnum.class);
1703 Map<GraphPropertyEnum, Object> propertiesNotToMatch = new EnumMap<>(GraphPropertyEnum.class);
1705 propertiesToMatch.put(GraphPropertyEnum.IS_ABSTRACT, isAbstract);
1706 if (isHighest != null) {
1707 propertiesToMatch.put(GraphPropertyEnum.IS_HIGHEST_VERSION, isHighest);
1709 propertiesToMatch.put(GraphPropertyEnum.STATE, LifecycleStateEnum.CERTIFIED.name());
1710 propertiesToMatch.put(GraphPropertyEnum.COMPONENT_TYPE, ComponentTypeEnum.RESOURCE.name());
1711 propertiesNotToMatch.put(GraphPropertyEnum.IS_DELETED, true);
1713 Either<List<GraphVertex>, TitanOperationStatus> getResourcesRes = titanDao.getByCriteria(null, propertiesToMatch, propertiesNotToMatch, JsonParseFlagEnum.ParseAll);
1715 if (getResourcesRes.isRight()) {
1716 log.debug("Failed to fetch all certified resources. Status is {}", getResourcesRes.right().value());
1717 return Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(getResourcesRes.right().value()));
1719 List<GraphVertex> resourceVerticies = getResourcesRes.left().value();
1720 for (GraphVertex resourceV : resourceVerticies) {
1721 Either<Resource, StorageOperationStatus> getResourceRes = getToscaElement(resourceV);
1722 if (getResourceRes.isRight()) {
1723 return Either.right(getResourceRes.right().value());
1725 resources.add(getResourceRes.left().value());
1727 return Either.left(resources);
1730 public <T extends Component> Either<T, StorageOperationStatus> getLatestByNameAndVersion(String name, String version, JsonParseFlagEnum parseFlag) {
1731 Either<T, StorageOperationStatus> result;
1733 Map<GraphPropertyEnum, Object> hasProperties = new EnumMap<>(GraphPropertyEnum.class);
1734 Map<GraphPropertyEnum, Object> hasNotProperties = new EnumMap<>(GraphPropertyEnum.class);
1736 hasProperties.put(GraphPropertyEnum.NAME, name);
1737 hasProperties.put(GraphPropertyEnum.VERSION, version);
1738 hasProperties.put(GraphPropertyEnum.IS_HIGHEST_VERSION, true);
1740 hasNotProperties.put(GraphPropertyEnum.IS_DELETED, true);
1742 Either<List<GraphVertex>, TitanOperationStatus> getResourceRes = titanDao.getByCriteria(null, hasProperties, hasNotProperties, parseFlag);
1743 if (getResourceRes.isRight()) {
1744 TitanOperationStatus status = getResourceRes.right().value();
1745 log.debug("failed to find resource with name {}, version {}. Status is {} ", name, version, status);
1746 result = Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(status));
1749 return getToscaElementByOperation(getResourceRes.left().value().get(0));
1752 public Either<Resource, StorageOperationStatus> getLatestComponentByCsarOrName(ComponentTypeEnum componentType, String csarUUID, String systemName) {
1753 return getLatestComponentByCsarOrName(componentType, csarUUID, systemName, JsonParseFlagEnum.ParseAll);
1756 public Either<Resource, StorageOperationStatus> getLatestComponentByCsarOrName(ComponentTypeEnum componentType, String csarUUID, String systemName, JsonParseFlagEnum parseFlag) {
1757 Map<GraphPropertyEnum, Object> props = new EnumMap<>(GraphPropertyEnum.class);
1758 Map<GraphPropertyEnum, Object> propsHasNot = new EnumMap<>(GraphPropertyEnum.class);
1759 props.put(GraphPropertyEnum.CSAR_UUID, csarUUID);
1760 props.put(GraphPropertyEnum.IS_HIGHEST_VERSION, true);
1761 if (componentType != null) {
1762 props.put(GraphPropertyEnum.COMPONENT_TYPE, componentType.name());
1764 propsHasNot.put(GraphPropertyEnum.IS_DELETED, true);
1766 GraphVertex resourceMetadataData = null;
1767 List<GraphVertex> resourceMetadataDataList = null;
1768 Either<List<GraphVertex>, TitanOperationStatus> byCsar = titanDao.getByCriteria(null, props, propsHasNot, JsonParseFlagEnum.ParseMetadata);
1769 if (byCsar.isRight()) {
1770 if (TitanOperationStatus.NOT_FOUND == byCsar.right().value()) {
1771 // Fix Defect DE256036
1772 if (StringUtils.isEmpty(systemName)) {
1773 return Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(TitanOperationStatus.NOT_FOUND));
1777 props.put(GraphPropertyEnum.IS_HIGHEST_VERSION, true);
1778 props.put(GraphPropertyEnum.SYSTEM_NAME, systemName);
1779 Either<List<GraphVertex>, TitanOperationStatus> bySystemname = titanDao.getByCriteria(null, props, JsonParseFlagEnum.ParseMetadata);
1780 if (bySystemname.isRight()) {
1781 log.debug("getLatestResourceByCsarOrName - Failed to find by system name {} error {} ", systemName, bySystemname.right().value());
1782 return Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(bySystemname.right().value()));
1784 if (bySystemname.left().value().size() > 2) {
1785 log.debug("getLatestResourceByCsarOrName - getByCriteria(by system name) must return only 2 latest version, but was returned - {}", bySystemname.left().value().size());
1786 return Either.right(StorageOperationStatus.GENERAL_ERROR);
1788 resourceMetadataDataList = bySystemname.left().value();
1789 if (resourceMetadataDataList.size() == 1) {
1790 resourceMetadataData = resourceMetadataDataList.get(0);
1792 for (GraphVertex curResource : resourceMetadataDataList) {
1793 if (!((String) curResource.getJsonMetadataField(JsonPresentationFields.LIFECYCLE_STATE)).equals("CERTIFIED")) {
1794 resourceMetadataData = curResource;
1799 if (resourceMetadataData == null) {
1800 log.debug("getLatestResourceByCsarOrName - getByCriteria(by system name) returned 2 latest CERTIFIED versions");
1801 return Either.right(StorageOperationStatus.GENERAL_ERROR);
1803 if (resourceMetadataData.getJsonMetadataField(JsonPresentationFields.CSAR_UUID) != null && !((String) resourceMetadataData.getJsonMetadataField(JsonPresentationFields.CSAR_UUID)).equals(csarUUID)) {
1804 log.debug("getLatestResourceByCsarOrName - same system name {} but different csarUUID. exist {} and new {} ", systemName, resourceMetadataData.getJsonMetadataField(JsonPresentationFields.CSAR_UUID), csarUUID);
1805 // correct error will be returned from create flow. with all
1806 // correct audit records!!!!!
1807 return Either.right(StorageOperationStatus.NOT_FOUND);
1809 return getToscaElement((String) resourceMetadataData.getUniqueId());
1812 resourceMetadataDataList = byCsar.left().value();
1813 if (resourceMetadataDataList.size() > 2) {
1814 log.debug("getLatestResourceByCsarOrName - getByCriteria(by csar) must return only 2 latest version, but was returned - {}", byCsar.left().value().size());
1815 return Either.right(StorageOperationStatus.GENERAL_ERROR);
1817 if (resourceMetadataDataList.size() == 1) {
1818 resourceMetadataData = resourceMetadataDataList.get(0);
1820 for (GraphVertex curResource : resourceMetadataDataList) {
1821 if (!((String) curResource.getJsonMetadataField(JsonPresentationFields.LIFECYCLE_STATE)).equals("CERTIFIED")) {
1822 resourceMetadataData = curResource;
1827 if (resourceMetadataData == null) {
1828 log.debug("getLatestResourceByCsarOrName - getByCriteria(by csar) returned 2 latest CERTIFIED versions");
1829 return Either.right(StorageOperationStatus.GENERAL_ERROR);
1831 return getToscaElement((String) resourceMetadataData.getJsonMetadataField(JsonPresentationFields.UNIQUE_ID), parseFlag);
1836 public Either<Boolean, StorageOperationStatus> validateToscaResourceNameExtends(String templateNameCurrent, String templateNameExtends) {
1838 String currentTemplateNameChecked = templateNameExtends;
1840 while (currentTemplateNameChecked != null && !currentTemplateNameChecked.equalsIgnoreCase(templateNameCurrent)) {
1841 Either<Resource, StorageOperationStatus> latestByToscaResourceName = getLatestByToscaResourceName(currentTemplateNameChecked);
1843 if (latestByToscaResourceName.isRight()) {
1844 return latestByToscaResourceName.right().value() == StorageOperationStatus.NOT_FOUND ? Either.left(false) : Either.right(latestByToscaResourceName.right().value());
1847 Resource value = latestByToscaResourceName.left().value();
1849 if (value.getDerivedFrom() != null) {
1850 currentTemplateNameChecked = value.getDerivedFrom().get(0);
1852 currentTemplateNameChecked = null;
1856 return (currentTemplateNameChecked != null && currentTemplateNameChecked.equalsIgnoreCase(templateNameCurrent)) ? Either.left(true) : Either.left(false);
1859 public Either<List<Component>, StorageOperationStatus> fetchMetaDataByResourceType(String resourceType, ComponentParametersView filterBy) {
1860 Map<GraphPropertyEnum, Object> props = new EnumMap<>(GraphPropertyEnum.class);
1861 props.put(GraphPropertyEnum.RESOURCE_TYPE, resourceType);
1862 props.put(GraphPropertyEnum.IS_HIGHEST_VERSION, true);
1863 Map<GraphPropertyEnum, Object> propsHasNotToMatch = new EnumMap<>(GraphPropertyEnum.class);
1864 propsHasNotToMatch.put(GraphPropertyEnum.IS_DELETED, true);
1865 Either<List<GraphVertex>, TitanOperationStatus> resourcesByTypeEither = titanDao.getByCriteria(null, props, propsHasNotToMatch, JsonParseFlagEnum.ParseMetadata);
1867 if (resourcesByTypeEither.isRight()) {
1868 return Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(resourcesByTypeEither.right().value()));
1871 List<GraphVertex> vertexList = resourcesByTypeEither.left().value();
1872 List<Component> components = new ArrayList<>();
1874 for (GraphVertex vertex : vertexList) {
1875 components.add(getToscaElementByOperation(vertex, filterBy).left().value());
1878 return Either.left(components);
1881 public void commit() {
1885 public Either<Service, StorageOperationStatus> updateDistributionStatus(Service service, User user, DistributionStatusEnum distributionStatus) {
1886 Either<GraphVertex, StorageOperationStatus> updateDistributionStatus = topologyTemplateOperation.updateDistributionStatus(service.getUniqueId(), user, distributionStatus);
1887 if (updateDistributionStatus.isRight()) {
1888 return Either.right(updateDistributionStatus.right().value());
1890 GraphVertex serviceV = updateDistributionStatus.left().value();
1891 service.setDistributionStatus(distributionStatus);
1892 service.setLastUpdateDate((Long) serviceV.getJsonMetadataField(JsonPresentationFields.LAST_UPDATE_DATE));
1893 return Either.left(service);
1896 public Either<ComponentMetadataData, StorageOperationStatus> updateComponentLastUpdateDateOnGraph(Component component) {
1898 Either<ComponentMetadataData, StorageOperationStatus> result = null;
1899 GraphVertex serviceVertex;
1900 Either<GraphVertex, TitanOperationStatus> updateRes = null;
1901 Either<GraphVertex, TitanOperationStatus> getRes = titanDao.getVertexById(component.getUniqueId(), JsonParseFlagEnum.ParseMetadata);
1902 if (getRes.isRight()) {
1903 TitanOperationStatus status = getRes.right().value();
1904 log.error("Failed to fetch component {}. status is {}", component.getUniqueId(), status);
1905 result = Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(status));
1907 if (result == null) {
1908 serviceVertex = getRes.left().value();
1909 long lastUpdateDate = System.currentTimeMillis();
1910 serviceVertex.setJsonMetadataField(JsonPresentationFields.LAST_UPDATE_DATE, lastUpdateDate);
1911 component.setLastUpdateDate(lastUpdateDate);
1912 updateRes = titanDao.updateVertex(serviceVertex);
1913 if (updateRes.isRight()) {
1914 result = Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(updateRes.right().value()));
1917 if (result == null) {
1918 result = Either.left(ModelConverter.convertToComponentMetadata(updateRes.left().value()));
1923 public TitanDao getTitanDao() {
1927 public Either<List<Service>, StorageOperationStatus> getCertifiedServicesWithDistStatus(Set<DistributionStatusEnum> distStatus) {
1928 Map<GraphPropertyEnum, Object> propertiesToMatch = new EnumMap<>(GraphPropertyEnum.class);
1929 propertiesToMatch.put(GraphPropertyEnum.STATE, LifecycleStateEnum.CERTIFIED.name());
1931 return getServicesWithDistStatus(distStatus, propertiesToMatch);
1934 public Either<List<Service>, StorageOperationStatus> getServicesWithDistStatus(Set<DistributionStatusEnum> distStatus, Map<GraphPropertyEnum, Object> additionalPropertiesToMatch) {
1936 List<Service> servicesAll = new ArrayList<>();
1938 Map<GraphPropertyEnum, Object> propertiesToMatch = new EnumMap<>(GraphPropertyEnum.class);
1939 Map<GraphPropertyEnum, Object> propertiesNotToMatch = new EnumMap<>(GraphPropertyEnum.class);
1941 if (additionalPropertiesToMatch != null && !additionalPropertiesToMatch.isEmpty()) {
1942 propertiesToMatch.putAll(additionalPropertiesToMatch);
1945 propertiesToMatch.put(GraphPropertyEnum.COMPONENT_TYPE, ComponentTypeEnum.SERVICE.name());
1947 propertiesNotToMatch.put(GraphPropertyEnum.IS_DELETED, true);
1949 if (distStatus != null && !distStatus.isEmpty()) {
1950 for (DistributionStatusEnum state : distStatus) {
1951 propertiesToMatch.put(GraphPropertyEnum.DISTRIBUTION_STATUS, state.name());
1952 Either<List<Service>, StorageOperationStatus> fetchServicesByCriteria = fetchServicesByCriteria(servicesAll, propertiesToMatch, propertiesNotToMatch);
1953 if (fetchServicesByCriteria.isRight()) {
1954 return fetchServicesByCriteria;
1956 servicesAll = fetchServicesByCriteria.left().value();
1959 return Either.left(servicesAll);
1961 return fetchServicesByCriteria(servicesAll, propertiesToMatch, propertiesNotToMatch);
1965 private Either<List<Service>, StorageOperationStatus> fetchServicesByCriteria(List<Service> servicesAll, Map<GraphPropertyEnum, Object> propertiesToMatch, Map<GraphPropertyEnum, Object> propertiesNotToMatch) {
1966 Either<List<GraphVertex>, TitanOperationStatus> getRes = titanDao.getByCriteria(VertexTypeEnum.TOPOLOGY_TEMPLATE, propertiesToMatch, propertiesNotToMatch, JsonParseFlagEnum.ParseAll);
1967 if (getRes.isRight()) {
1968 if (getRes.right().value() != TitanOperationStatus.NOT_FOUND) {
1969 CommonUtility.addRecordToLog(log, LogLevelEnum.DEBUG, "Failed to fetch certified services by match properties {} not match properties {} . Status is {}. ", propertiesToMatch, propertiesNotToMatch, getRes.right().value());
1970 return Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(getRes.right().value()));
1973 for (GraphVertex vertex : getRes.left().value()) {
1974 Either<ToscaElement, StorageOperationStatus> getServiceRes = topologyTemplateOperation.getLightComponent(vertex, ComponentTypeEnum.SERVICE, new ComponentParametersView(true));
1976 if (getServiceRes.isRight()) {
1977 CommonUtility.addRecordToLog(log, LogLevelEnum.DEBUG, "Failed to fetch certified service {}. Status is {}. ", vertex.getJsonMetadataField(JsonPresentationFields.NAME), getServiceRes.right().value());
1978 return Either.right(getServiceRes.right().value());
1980 servicesAll.add(ModelConverter.convertFromToscaElement(getServiceRes.left().value()));
1984 return Either.left(servicesAll);
1987 public void rollback() {
1988 titanDao.rollback();
1991 public StorageOperationStatus addDeploymentArtifactsToInstance(String componentId, ComponentInstance componentInstance, Map<String, ArtifactDefinition> finalDeploymentArtifacts) {
1992 Map<String, ArtifactDataDefinition> instDeplArtifacts = finalDeploymentArtifacts.entrySet().stream().collect(Collectors.toMap(Map.Entry::getKey, e -> new ArtifactDataDefinition(e.getValue())));
1994 return nodeTemplateOperation.addDeploymentArtifactsToInstance(componentId, componentInstance.getUniqueId(), instDeplArtifacts);
1997 public StorageOperationStatus addInformationalArtifactsToInstance(String componentId, ComponentInstance componentInstance, Map<String, ArtifactDefinition> artifacts) {
1998 StorageOperationStatus status = StorageOperationStatus.OK;
1999 if (MapUtils.isNotEmpty(artifacts)) {
2000 Map<String, ArtifactDataDefinition> instDeplArtifacts = artifacts.entrySet().stream().collect(Collectors.toMap(Map.Entry::getKey, e -> new ArtifactDataDefinition(e.getValue())));
2001 status = nodeTemplateOperation.addInformationalArtifactsToInstance(componentId, componentInstance.getUniqueId(), instDeplArtifacts);
2006 public StorageOperationStatus generateCustomizationUUIDOnInstance(String componentId, String instanceId) {
2007 return nodeTemplateOperation.generateCustomizationUUIDOnInstance(componentId, instanceId);
2010 public StorageOperationStatus generateCustomizationUUIDOnInstanceGroup(String componentId, String instanceId, List<String> groupInstances) {
2011 return nodeTemplateOperation.generateCustomizationUUIDOnInstanceGroup(componentId, instanceId, groupInstances);
2014 public Either<PropertyDefinition, StorageOperationStatus> addPropertyToComponent(String propertyName,
2015 PropertyDefinition newPropertyDefinition,
2016 Component component) {
2018 Either<PropertyDefinition, StorageOperationStatus> result = null;
2019 Either<Component, StorageOperationStatus> getUpdatedComponentRes = null;
2020 newPropertyDefinition.setName(propertyName);
2022 StorageOperationStatus status = getToscaElementOperation(component)
2023 .addToscaDataToToscaElement(component.getUniqueId(), EdgeLabelEnum.PROPERTIES, VertexTypeEnum.PROPERTIES, newPropertyDefinition, JsonPresentationFields.NAME);
2024 if (status != StorageOperationStatus.OK) {
2025 CommonUtility.addRecordToLog(log, LogLevelEnum.DEBUG, "Failed to add the property {} to the component {}. Status is {}. ", propertyName, component.getName(), status);
2026 result = Either.right(status);
2028 if (result == null) {
2029 ComponentParametersView filter = new ComponentParametersView(true);
2030 filter.setIgnoreProperties(false);
2031 filter.setIgnoreInputs(false);
2032 getUpdatedComponentRes = getToscaElement(component.getUniqueId(), filter);
2033 if (getUpdatedComponentRes.isRight()) {
2034 CommonUtility.addRecordToLog(log, LogLevelEnum.DEBUG, "Failed to get updated component {}. Status is {}. ", component.getUniqueId(), getUpdatedComponentRes.right().value());
2035 result = Either.right(status);
2038 if (result == null) {
2039 PropertyDefinition newProperty = null;
2040 List<PropertyDefinition> properties =
2041 (getUpdatedComponentRes.left().value()).getProperties();
2042 if (CollectionUtils.isNotEmpty(properties)) {
2043 Optional<PropertyDefinition> propertyOptional = properties.stream().filter(
2044 propertyEntry -> propertyEntry.getName().equals(propertyName)).findAny();
2045 if (propertyOptional.isPresent()) {
2046 newProperty = propertyOptional.get();
2049 if (newProperty == null) {
2050 CommonUtility.addRecordToLog(log, LogLevelEnum.DEBUG, "Failed to find recently added property {} on the component {}. Status is {}. ", propertyName, component.getUniqueId(), StorageOperationStatus.NOT_FOUND);
2051 result = Either.right(StorageOperationStatus.NOT_FOUND);
2053 result = Either.left(newProperty);
2058 public StorageOperationStatus deletePropertyOfComponent(Component component, String propertyName) {
2059 return getToscaElementOperation(component).deleteToscaDataElement(component.getUniqueId(), EdgeLabelEnum.PROPERTIES, VertexTypeEnum.PROPERTIES, propertyName, JsonPresentationFields.NAME);
2062 public StorageOperationStatus deleteAttributeOfResource(Component component, String attributeName) {
2063 return getToscaElementOperation(component).deleteToscaDataElement(component.getUniqueId(), EdgeLabelEnum.ATTRIBUTES, VertexTypeEnum.ATTRIBUTES, attributeName, JsonPresentationFields.NAME);
2066 public StorageOperationStatus deleteInputOfResource(Component resource, String inputName) {
2067 return getToscaElementOperation(resource).deleteToscaDataElement(resource.getUniqueId(), EdgeLabelEnum.INPUTS, VertexTypeEnum.INPUTS, inputName, JsonPresentationFields.NAME);
2070 public Either<PropertyDefinition, StorageOperationStatus> updatePropertyOfComponent(Component component,
2071 PropertyDefinition newPropertyDefinition) {
2073 Either<Component, StorageOperationStatus> getUpdatedComponentRes = null;
2074 Either<PropertyDefinition, StorageOperationStatus> result = null;
2075 StorageOperationStatus status = getToscaElementOperation(component).updateToscaDataOfToscaElement(component.getUniqueId(), EdgeLabelEnum.PROPERTIES, VertexTypeEnum.PROPERTIES, newPropertyDefinition, JsonPresentationFields.NAME);
2076 if (status != StorageOperationStatus.OK) {
2077 CommonUtility.addRecordToLog(log, LogLevelEnum.DEBUG, "Failed to add the property {} to the resource {}. Status is {}. ", newPropertyDefinition.getName(), component.getName(), status);
2078 result = Either.right(status);
2080 if (result == null) {
2081 ComponentParametersView filter = new ComponentParametersView(true);
2082 filter.setIgnoreProperties(false);
2083 getUpdatedComponentRes = getToscaElement(component.getUniqueId(), filter);
2084 if (getUpdatedComponentRes.isRight()) {
2085 CommonUtility.addRecordToLog(log, LogLevelEnum.DEBUG, "Failed to get updated resource {}. Status is {}. ", component.getUniqueId(), getUpdatedComponentRes.right().value());
2086 result = Either.right(status);
2089 if (result == null) {
2090 Optional<PropertyDefinition> newProperty = (getUpdatedComponentRes.left().value())
2091 .getProperties().stream().filter(p -> p.getName().equals(newPropertyDefinition.getName())).findAny();
2092 if (newProperty.isPresent()) {
2093 result = Either.left(newProperty.get());
2095 CommonUtility.addRecordToLog(log, LogLevelEnum.DEBUG, "Failed to find recently added property {} on the resource {}. Status is {}. ", newPropertyDefinition.getName(), component.getUniqueId(), StorageOperationStatus.NOT_FOUND);
2096 result = Either.right(StorageOperationStatus.NOT_FOUND);
2104 public Either<PropertyDefinition, StorageOperationStatus> addAttributeOfResource(Component component, PropertyDefinition newAttributeDef) {
2106 Either<Component, StorageOperationStatus> getUpdatedComponentRes = null;
2107 Either<PropertyDefinition, StorageOperationStatus> result = null;
2108 if (newAttributeDef.getUniqueId() == null || newAttributeDef.getUniqueId().isEmpty()) {
2109 String attUniqueId = UniqueIdBuilder.buildAttributeUid(component.getUniqueId(), newAttributeDef.getName());
2110 newAttributeDef.setUniqueId(attUniqueId);
2113 StorageOperationStatus status = getToscaElementOperation(component).addToscaDataToToscaElement(component.getUniqueId(), EdgeLabelEnum.ATTRIBUTES, VertexTypeEnum.ATTRIBUTES, newAttributeDef, JsonPresentationFields.NAME);
2114 if (status != StorageOperationStatus.OK) {
2115 CommonUtility.addRecordToLog(log, LogLevelEnum.DEBUG, FAILED_TO_ADD_THE_PROPERTY_TO_THE_RESOURCE_STATUS_IS, newAttributeDef.getName(), component.getName(), status);
2116 result = Either.right(status);
2118 if (result == null) {
2119 ComponentParametersView filter = new ComponentParametersView(true);
2120 filter.setIgnoreAttributesFrom(false);
2121 getUpdatedComponentRes = getToscaElement(component.getUniqueId(), filter);
2122 if (getUpdatedComponentRes.isRight()) {
2123 CommonUtility.addRecordToLog(log, LogLevelEnum.DEBUG, FAILED_TO_GET_UPDATED_RESOURCE_STATUS_IS, component.getUniqueId(), getUpdatedComponentRes.right().value());
2124 result = Either.right(status);
2127 if (result == null) {
2128 Optional<PropertyDefinition> newAttribute = ((Resource) getUpdatedComponentRes.left().value()).getAttributes().stream().filter(p -> p.getName().equals(newAttributeDef.getName())).findAny();
2129 if (newAttribute.isPresent()) {
2130 result = Either.left(newAttribute.get());
2132 CommonUtility.addRecordToLog(log, LogLevelEnum.DEBUG, FAILED_TO_FIND_RECENTLY_ADDED_PROPERTY_ON_THE_RESOURCE_STATUS_IS, newAttributeDef.getName(), component.getUniqueId(), StorageOperationStatus.NOT_FOUND);
2133 result = Either.right(StorageOperationStatus.NOT_FOUND);
2139 public Either<PropertyDefinition, StorageOperationStatus> updateAttributeOfResource(Component component, PropertyDefinition newAttributeDef) {
2141 Either<Component, StorageOperationStatus> getUpdatedComponentRes = null;
2142 Either<PropertyDefinition, StorageOperationStatus> result = null;
2143 StorageOperationStatus status = getToscaElementOperation(component).updateToscaDataOfToscaElement(component.getUniqueId(), EdgeLabelEnum.ATTRIBUTES, VertexTypeEnum.ATTRIBUTES, newAttributeDef, JsonPresentationFields.NAME);
2144 if (status != StorageOperationStatus.OK) {
2145 CommonUtility.addRecordToLog(log, LogLevelEnum.DEBUG, FAILED_TO_ADD_THE_PROPERTY_TO_THE_RESOURCE_STATUS_IS, newAttributeDef.getName(), component.getName(), status);
2146 result = Either.right(status);
2148 if (result == null) {
2149 ComponentParametersView filter = new ComponentParametersView(true);
2150 filter.setIgnoreAttributesFrom(false);
2151 getUpdatedComponentRes = getToscaElement(component.getUniqueId(), filter);
2152 if (getUpdatedComponentRes.isRight()) {
2153 CommonUtility.addRecordToLog(log, LogLevelEnum.DEBUG, FAILED_TO_GET_UPDATED_RESOURCE_STATUS_IS, component.getUniqueId(), getUpdatedComponentRes.right().value());
2154 result = Either.right(status);
2157 if (result == null) {
2158 Optional<PropertyDefinition> newProperty = ((Resource) getUpdatedComponentRes.left().value()).getAttributes().stream().filter(p -> p.getName().equals(newAttributeDef.getName())).findAny();
2159 if (newProperty.isPresent()) {
2160 result = Either.left(newProperty.get());
2162 CommonUtility.addRecordToLog(log, LogLevelEnum.DEBUG, FAILED_TO_FIND_RECENTLY_ADDED_PROPERTY_ON_THE_RESOURCE_STATUS_IS, newAttributeDef.getName(), component.getUniqueId(), StorageOperationStatus.NOT_FOUND);
2163 result = Either.right(StorageOperationStatus.NOT_FOUND);
2169 public Either<InputDefinition, StorageOperationStatus> updateInputOfComponent(Component component, InputDefinition newInputDefinition) {
2171 Either<Component, StorageOperationStatus> getUpdatedComponentRes = null;
2172 Either<InputDefinition, StorageOperationStatus> result = null;
2173 StorageOperationStatus status = getToscaElementOperation(component).updateToscaDataOfToscaElement(component.getUniqueId(), EdgeLabelEnum.INPUTS, VertexTypeEnum.INPUTS, newInputDefinition, JsonPresentationFields.NAME);
2174 if (status != StorageOperationStatus.OK) {
2175 CommonUtility.addRecordToLog(log, LogLevelEnum.DEBUG, "Failed to update the input {} to the component {}. Status is {}. ", newInputDefinition.getName(), component.getName(), status);
2176 result = Either.right(status);
2178 if (result == null) {
2179 ComponentParametersView filter = new ComponentParametersView(true);
2180 filter.setIgnoreInputs(false);
2181 getUpdatedComponentRes = getToscaElement(component.getUniqueId(), filter);
2182 if (getUpdatedComponentRes.isRight()) {
2183 CommonUtility.addRecordToLog(log, LogLevelEnum.DEBUG, FAILED_TO_GET_UPDATED_RESOURCE_STATUS_IS, component.getUniqueId(), getUpdatedComponentRes.right().value());
2184 result = Either.right(status);
2187 if (result == null) {
2188 Optional<InputDefinition> updatedInput = getUpdatedComponentRes.left().value().getInputs().stream().filter(p -> p.getName().equals(newInputDefinition.getName())).findAny();
2189 if (updatedInput.isPresent()) {
2190 result = Either.left(updatedInput.get());
2192 CommonUtility.addRecordToLog(log, LogLevelEnum.DEBUG, "Failed to find recently updated inputs {} on the resource {}. Status is {}. ", newInputDefinition.getName(), component.getUniqueId(), StorageOperationStatus.NOT_FOUND);
2193 result = Either.right(StorageOperationStatus.NOT_FOUND);
2200 * method - ename the group instances after referenced container name renamed flow - VF rename -(triggers)-> Group rename
2202 * @param containerComponent - container such as service
2203 * @param componentInstance - context component
2204 * @param componentInstanceId - id
2205 * @return - successfull/failed status
2207 public Either<StorageOperationStatus, StorageOperationStatus> cleanAndAddGroupInstancesToComponentInstance(Component containerComponent, ComponentInstance componentInstance, String componentInstanceId) {
2208 String uniqueId = componentInstance.getUniqueId();
2209 StorageOperationStatus status = nodeTemplateOperation.deleteToscaDataDeepElementsBlockOfToscaElement(containerComponent.getUniqueId(), EdgeLabelEnum.INST_GROUPS, VertexTypeEnum.INST_GROUPS, uniqueId);
2210 if (status != StorageOperationStatus.OK && status != StorageOperationStatus.NOT_FOUND) {
2211 CommonUtility.addRecordToLog(log, LogLevelEnum.DEBUG, "Failed to delete group instances for container {}. error {] ", componentInstanceId, status);
2212 return Either.right(status);
2214 if (componentInstance.getGroupInstances() != null) {
2215 status = addGroupInstancesToComponentInstance(containerComponent, componentInstance, componentInstance.getGroupInstances());
2216 if (status != StorageOperationStatus.OK && status != StorageOperationStatus.NOT_FOUND) {
2217 CommonUtility.addRecordToLog(log, LogLevelEnum.DEBUG, "Failed to add group instances for container {}. error {] ", componentInstanceId, status);
2218 return Either.right(status);
2221 return Either.left(status);
2224 public StorageOperationStatus addGroupInstancesToComponentInstance(Component containerComponent, ComponentInstance componentInstance, List<GroupDefinition> groups, Map<String, List<ArtifactDefinition>> groupInstancesArtifacts) {
2225 return nodeTemplateOperation.addGroupInstancesToComponentInstance(containerComponent, componentInstance, groups, groupInstancesArtifacts);
2228 public Either<List<GroupDefinition>, StorageOperationStatus> updateGroupsOnComponent(Component component, List<GroupDataDefinition> updatedGroups) {
2229 return groupsOperation.updateGroups(component, updatedGroups, true);
2232 public Either<List<GroupInstance>, StorageOperationStatus> updateGroupInstancesOnComponent(Component component, String instanceId, List<GroupInstance> updatedGroupInstances) {
2233 return groupsOperation.updateGroupInstances(component, instanceId, updatedGroupInstances);
2236 public StorageOperationStatus addGroupInstancesToComponentInstance(Component containerComponent, ComponentInstance componentInstance, List<GroupInstance> groupInstances) {
2237 return nodeTemplateOperation.addGroupInstancesToComponentInstance(containerComponent, componentInstance, groupInstances);
2240 public StorageOperationStatus addDeploymentArtifactsToComponentInstance(Component containerComponent, ComponentInstance componentInstance, Map<String, ArtifactDefinition> deploymentArtifacts) {
2241 return nodeTemplateOperation.addDeploymentArtifactsToComponentInstance(containerComponent, componentInstance, deploymentArtifacts);
2244 public StorageOperationStatus updateComponentInstanceProperty(Component containerComponent, String componentInstanceId, ComponentInstanceProperty property) {
2245 return nodeTemplateOperation.updateComponentInstanceProperty(containerComponent, componentInstanceId, property);
2248 public StorageOperationStatus updateComponentInstanceProperties(Component containerComponent, String componentInstanceId, List<ComponentInstanceProperty> properties) {
2249 return nodeTemplateOperation.updateComponentInstanceProperties(containerComponent, componentInstanceId, properties);
2253 public StorageOperationStatus addComponentInstanceProperty(Component containerComponent, String componentInstanceId, ComponentInstanceProperty property) {
2254 return nodeTemplateOperation.addComponentInstanceProperty(containerComponent, componentInstanceId, property);
2257 public StorageOperationStatus updateComponentInstanceAttribute(Component containerComponent, String componentInstanceId, ComponentInstanceProperty property){
2258 return nodeTemplateOperation.updateComponentInstanceAttribute(containerComponent, componentInstanceId, property);
2261 public StorageOperationStatus addComponentInstanceAttribute(Component containerComponent, String componentInstanceId, ComponentInstanceProperty property){
2262 return nodeTemplateOperation.addComponentInstanceAttribute(containerComponent, componentInstanceId, property);
2265 public StorageOperationStatus updateComponentInstanceInput(Component containerComponent, String componentInstanceId, ComponentInstanceInput property) {
2266 return nodeTemplateOperation.updateComponentInstanceInput(containerComponent, componentInstanceId, property);
2269 public StorageOperationStatus updateComponentInstanceInputs(Component containerComponent, String componentInstanceId, List<ComponentInstanceInput> instanceInputs) {
2270 return nodeTemplateOperation.updateComponentInstanceInputs(containerComponent, componentInstanceId, instanceInputs);
2273 public StorageOperationStatus addComponentInstanceInput(Component containerComponent, String componentInstanceId, ComponentInstanceInput property) {
2274 return nodeTemplateOperation.addComponentInstanceInput(containerComponent, componentInstanceId, property);
2277 public void setNodeTypeOperation(NodeTypeOperation nodeTypeOperation) {
2278 this.nodeTypeOperation = nodeTypeOperation;
2281 public void setTopologyTemplateOperation(TopologyTemplateOperation topologyTemplateOperation) {
2282 this.topologyTemplateOperation = topologyTemplateOperation;
2285 public StorageOperationStatus deleteComponentInstanceInputsFromTopologyTemplate(Component containerComponent, List<InputDefinition> inputsToDelete) {
2286 return topologyTemplateOperation.deleteToscaDataElements(containerComponent.getUniqueId(), EdgeLabelEnum.INPUTS, inputsToDelete.stream().map(PropertyDataDefinition::getName).collect(Collectors.toList()));
2289 public StorageOperationStatus updateComponentInstanceCapabiltyProperty(Component containerComponent, String componentInstanceUniqueId, String capabilityUniqueId, ComponentInstanceProperty property) {
2290 return nodeTemplateOperation.updateComponentInstanceCapabilityProperty(containerComponent, componentInstanceUniqueId, capabilityUniqueId, property);
2293 public StorageOperationStatus updateComponentInstanceCapabilityProperties(Component containerComponent, String componentInstanceUniqueId) {
2294 return convertComponentInstanceProperties(containerComponent, componentInstanceUniqueId)
2295 .map(instanceCapProps -> topologyTemplateOperation.updateComponentInstanceCapabilityProperties(containerComponent, componentInstanceUniqueId, instanceCapProps))
2296 .orElse(StorageOperationStatus.NOT_FOUND);
2299 public StorageOperationStatus updateComponentCalculatedCapabilitiesProperties(Component containerComponent) {
2300 Map<String, MapCapabilityProperty> mapCapabiltyPropertyMap =
2301 convertComponentCapabilitiesProperties(containerComponent);
2302 return nodeTemplateOperation.overrideComponentCapabilitiesProperties(containerComponent, mapCapabiltyPropertyMap);
2305 public StorageOperationStatus deleteAllCalculatedCapabilitiesRequirements(String topologyTemplateId) {
2306 StorageOperationStatus status = topologyTemplateOperation.removeToscaData(topologyTemplateId, EdgeLabelEnum.CALCULATED_CAPABILITIES, VertexTypeEnum.CALCULATED_CAPABILITIES);
2307 if (status == StorageOperationStatus.OK) {
2308 status = topologyTemplateOperation.removeToscaData(topologyTemplateId, EdgeLabelEnum.CALCULATED_REQUIREMENTS, VertexTypeEnum.CALCULATED_REQUIREMENTS);
2310 if (status == StorageOperationStatus.OK) {
2311 status = topologyTemplateOperation.removeToscaData(topologyTemplateId, EdgeLabelEnum.CALCULATED_CAP_PROPERTIES, VertexTypeEnum.CALCULATED_CAP_PROPERTIES);
2316 public Either<Component, StorageOperationStatus> shouldUpgradeToLatestDerived(Resource clonedResource) {
2317 String componentId = clonedResource.getUniqueId();
2318 Either<GraphVertex, TitanOperationStatus> getVertexEither = titanDao.getVertexById(componentId, JsonParseFlagEnum.NoParse);
2319 if (getVertexEither.isRight()) {
2320 log.debug(COULDNT_FETCH_COMPONENT_WITH_AND_UNIQUE_ID_ERROR, componentId, getVertexEither.right().value());
2321 return Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(getVertexEither.right().value()));
2324 GraphVertex nodeTypeV = getVertexEither.left().value();
2326 ToscaElement toscaElementToUpdate = ModelConverter.convertToToscaElement(clonedResource);
2328 Either<ToscaElement, StorageOperationStatus> shouldUpdateDerivedVersion = nodeTypeOperation.shouldUpdateDerivedVersion(toscaElementToUpdate, nodeTypeV);
2329 if (shouldUpdateDerivedVersion.isRight() && StorageOperationStatus.OK != shouldUpdateDerivedVersion.right().value()) {
2330 log.debug("Failed to update derived version for node type {} derived {}, error: {}", componentId, clonedResource.getDerivedFrom().get(0), shouldUpdateDerivedVersion.right().value());
2331 return Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(getVertexEither.right().value()));
2333 if (shouldUpdateDerivedVersion.isLeft()) {
2334 return Either.left(ModelConverter.convertFromToscaElement(shouldUpdateDerivedVersion.left().value()));
2336 return Either.left(clonedResource);
2340 * Returns list of ComponentInstanceProperty belonging to component instance capability specified by name, type and ownerId
2342 public Either<List<ComponentInstanceProperty>, StorageOperationStatus> getComponentInstanceCapabilityProperties(String componentId, String instanceId, String capabilityName, String capabilityType, String ownerId) {
2343 return topologyTemplateOperation.getComponentInstanceCapabilityProperties(componentId, instanceId, capabilityName, capabilityType, ownerId);
2346 private MapInterfaceDataDefinition convertComponentInstanceInterfaces(Component currComponent,
2347 String componentInstanceId) {
2348 MapInterfaceDataDefinition mapInterfaceDataDefinition = new MapInterfaceDataDefinition();
2349 List<ComponentInstanceInterface> componentInterface = currComponent.getComponentInstancesInterfaces().get(componentInstanceId);
2351 if(CollectionUtils.isNotEmpty(componentInterface)) {
2352 componentInterface.stream().forEach(interfaceDef -> mapInterfaceDataDefinition.put
2353 (interfaceDef.getUniqueId(), interfaceDef));
2356 return mapInterfaceDataDefinition;
2359 private Map<String, MapCapabilityProperty> convertComponentCapabilitiesProperties(Component currComponent) {
2360 Map<String, MapCapabilityProperty> map = ModelConverter.extractCapabilityPropertiesFromGroups(currComponent.getGroups(), true);
2361 map.putAll(ModelConverter.extractCapabilityProperteisFromInstances(currComponent.getComponentInstances(), true));
2365 private Optional<MapCapabilityProperty> convertComponentInstanceProperties(Component component, String instanceId) {
2366 return component.fetchInstanceById(instanceId)
2367 .map(ci -> ModelConverter.convertToMapOfMapCapabiltyProperties(ci.getCapabilities(), instanceId));
2370 public Either<PolicyDefinition, StorageOperationStatus> associatePolicyToComponent(String componentId, PolicyDefinition policyDefinition, int counter) {
2371 Either<PolicyDefinition, StorageOperationStatus> result = null;
2372 Either<GraphVertex, TitanOperationStatus> getVertexEither;
2373 getVertexEither = titanDao.getVertexById(componentId, JsonParseFlagEnum.ParseMetadata);
2374 if (getVertexEither.isRight()) {
2375 log.error(COULDNT_FETCH_A_COMPONENT_WITH_AND_UNIQUE_ID_ERROR, componentId, getVertexEither.right().value());
2376 result = Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(getVertexEither.right().value()));
2378 if (getVertexEither.left().value().getLabel() != VertexTypeEnum.TOPOLOGY_TEMPLATE) {
2379 log.error("Policy association to component of Tosca type {} is not allowed. ", getVertexEither.left().value().getLabel());
2380 result = Either.right(StorageOperationStatus.BAD_REQUEST);
2383 if (result == null) {
2384 StorageOperationStatus status = topologyTemplateOperation.addPolicyToToscaElement(getVertexEither.left().value(), policyDefinition, counter);
2385 if (status != StorageOperationStatus.OK) {
2386 return Either.right(status);
2389 if (result == null) {
2390 result = Either.left(policyDefinition);
2395 public StorageOperationStatus associatePoliciesToComponent(String componentId, List<PolicyDefinition> policies) {
2396 log.debug("#associatePoliciesToComponent - associating policies for component {}.", componentId);
2397 return titanDao.getVertexById(componentId, JsonParseFlagEnum.ParseMetadata)
2398 .either(containerVertex -> topologyTemplateOperation.addPoliciesToToscaElement(containerVertex, policies),
2399 DaoStatusConverter::convertTitanStatusToStorageStatus);
2402 public Either<PolicyDefinition, StorageOperationStatus> updatePolicyOfComponent(String componentId, PolicyDefinition policyDefinition) {
2403 Either<PolicyDefinition, StorageOperationStatus> result = null;
2404 Either<GraphVertex, TitanOperationStatus> getVertexEither;
2405 getVertexEither = titanDao.getVertexById(componentId, JsonParseFlagEnum.NoParse);
2406 if (getVertexEither.isRight()) {
2407 log.error(COULDNT_FETCH_A_COMPONENT_WITH_AND_UNIQUE_ID_ERROR, componentId, getVertexEither.right().value());
2408 result = Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(getVertexEither.right().value()));
2410 if (result == null) {
2411 StorageOperationStatus status = topologyTemplateOperation.updatePolicyOfToscaElement(getVertexEither.left().value(), policyDefinition);
2412 if (status != StorageOperationStatus.OK) {
2413 return Either.right(status);
2416 if (result == null) {
2417 result = Either.left(policyDefinition);
2422 public StorageOperationStatus updatePoliciesOfComponent(String componentId, List<PolicyDefinition> policyDefinition) {
2423 log.debug("#updatePoliciesOfComponent - updating policies for component {}", componentId);
2424 return titanDao.getVertexById(componentId, JsonParseFlagEnum.NoParse)
2426 .map(DaoStatusConverter::convertTitanStatusToStorageStatus)
2427 .either(containerVertex -> topologyTemplateOperation.updatePoliciesOfToscaElement(containerVertex, policyDefinition),
2431 public StorageOperationStatus removePolicyFromComponent(String componentId, String policyId) {
2432 StorageOperationStatus status = null;
2433 Either<GraphVertex, TitanOperationStatus> getVertexEither = titanDao.getVertexById(componentId, JsonParseFlagEnum.NoParse);
2434 if (getVertexEither.isRight()) {
2435 log.error(COULDNT_FETCH_A_COMPONENT_WITH_AND_UNIQUE_ID_ERROR, componentId, getVertexEither.right().value());
2436 status = DaoStatusConverter.convertTitanStatusToStorageStatus(getVertexEither.right().value());
2438 if (status == null) {
2439 status = topologyTemplateOperation.removePolicyFromToscaElement(getVertexEither.left().value(), policyId);
2444 public boolean canAddGroups(String componentId) {
2445 GraphVertex vertex = titanDao.getVertexById(componentId)
2447 .on(this::onTitanError);
2448 return topologyTemplateOperation.hasEdgeOfType(vertex, EdgeLabelEnum.GROUPS);
2451 GraphVertex onTitanError(TitanOperationStatus toe) {
2452 throw new StorageException(
2453 DaoStatusConverter.convertTitanStatusToStorageStatus(toe));
2456 public void updateNamesOfCalculatedCapabilitiesRequirements(String componentId){
2457 topologyTemplateOperation
2458 .updateNamesOfCalculatedCapabilitiesRequirements(componentId, getTopologyTemplate(componentId));
2461 public void revertNamesOfCalculatedCapabilitiesRequirements(String componentId) {
2462 topologyTemplateOperation
2463 .revertNamesOfCalculatedCapabilitiesRequirements(componentId, getTopologyTemplate(componentId));
2466 private TopologyTemplate getTopologyTemplate(String componentId) {
2467 return (TopologyTemplate)topologyTemplateOperation
2468 .getToscaElement(componentId, getFilterComponentWithCapProperties())
2470 .on(this::throwStorageException);
2473 private ComponentParametersView getFilterComponentWithCapProperties() {
2474 ComponentParametersView filter = new ComponentParametersView();
2475 filter.setIgnoreCapabiltyProperties(false);
2479 private ToscaElement throwStorageException(StorageOperationStatus status) {
2480 throw new StorageException(status);
2483 public Either<Boolean, StorageOperationStatus> isComponentInUse(String componentId) {
2484 final List<EdgeLabelEnum> forbiddenEdgeLabelEnums = Arrays.asList(EdgeLabelEnum.INSTANCE_OF, EdgeLabelEnum.PROXY_OF, EdgeLabelEnum.ALLOTTED_OF);
2485 Either<GraphVertex, TitanOperationStatus> vertexById = titanDao.getVertexById(componentId);
2486 if (vertexById.isLeft()) {
2487 for (EdgeLabelEnum edgeLabelEnum : forbiddenEdgeLabelEnums) {
2488 Iterator<Edge> edgeItr = vertexById.left().value().getVertex().edges(Direction.IN, edgeLabelEnum.name());
2489 if(edgeItr != null && edgeItr.hasNext()){
2490 return Either.left(true);
2494 return Either.left(false);
2497 public Either<List<Component>, StorageOperationStatus> getComponentListByInvariantUuid
2498 (String componentInvariantUuid, Map<GraphPropertyEnum, Object> additionalPropertiesToMatch) {
2500 Map<GraphPropertyEnum, Object> propertiesToMatch = new EnumMap<>(GraphPropertyEnum.class);
2501 if (MapUtils.isNotEmpty(additionalPropertiesToMatch)) {
2502 propertiesToMatch.putAll(additionalPropertiesToMatch);
2504 propertiesToMatch.put(GraphPropertyEnum.INVARIANT_UUID, componentInvariantUuid);
2506 Either<List<GraphVertex>, TitanOperationStatus> vertexEither = titanDao.getByCriteria(null, propertiesToMatch, JsonParseFlagEnum.ParseMetadata);
2508 if (vertexEither.isRight()) {
2509 log.debug("Couldn't fetch metadata for component with type {} and invariantUUId {}, error: {}", componentInvariantUuid, vertexEither.right().value());
2510 return Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(vertexEither.right().value()));
2512 List<GraphVertex> vertexList = vertexEither.isLeft() ? vertexEither.left().value() : null;
2514 if (vertexList == null || vertexList.isEmpty()) {
2515 log.debug("Component with invariantUUId {} was not found", componentInvariantUuid);
2516 return Either.right(StorageOperationStatus.NOT_FOUND);
2519 ArrayList<Component> components = new ArrayList<>();
2520 for (GraphVertex vertex : vertexList) {
2521 Either<Component, StorageOperationStatus> toscaElementByOperation = getToscaElementByOperation(vertex);
2522 if (toscaElementByOperation.isRight()) {
2523 log.debug("Could not fetch the following Component by Invariant UUID {}", vertex.getUniqueId());
2524 return Either.right(toscaElementByOperation.right().value());
2526 components.add(toscaElementByOperation.left().value());
2529 return Either.left(components);
2532 public Either<List<Component>, StorageOperationStatus> getParentComponents(String componentId) {
2533 List<Component> parentComponents = new ArrayList<>();
2534 final List<EdgeLabelEnum> relationEdgeLabelEnums = Arrays.asList(EdgeLabelEnum.INSTANCE_OF, EdgeLabelEnum.PROXY_OF);
2535 Either<GraphVertex, TitanOperationStatus> vertexById = titanDao.getVertexById(componentId);
2536 if (vertexById.isLeft()) {
2537 for (EdgeLabelEnum edgeLabelEnum : relationEdgeLabelEnums) {
2538 Either<GraphVertex, TitanOperationStatus> parentVertexEither = titanDao.getParentVertex(vertexById.left().value(), edgeLabelEnum, JsonParseFlagEnum.ParseJson);
2539 if(parentVertexEither.isLeft()){
2540 Either<Component, StorageOperationStatus> componentEither = getToscaElement(parentVertexEither.left().value().getUniqueId());
2541 if(componentEither.isLeft()){
2542 parentComponents.add(componentEither.left().value());
2547 return Either.left(parentComponents);
2549 public void updateCapReqOwnerId(String componentId) {
2550 topologyTemplateOperation
2551 .updateCapReqOwnerId(componentId, getTopologyTemplate(componentId));