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.openecomp.sdc.be.dao.jsongraph.GraphVertex;
29 import org.openecomp.sdc.be.dao.jsongraph.TitanDao;
30 import org.openecomp.sdc.be.dao.jsongraph.types.EdgeLabelEnum;
31 import org.openecomp.sdc.be.dao.jsongraph.types.JsonParseFlagEnum;
32 import org.openecomp.sdc.be.dao.jsongraph.types.VertexTypeEnum;
33 import org.openecomp.sdc.be.dao.titan.TitanOperationStatus;
34 import org.openecomp.sdc.be.datatypes.elements.*;
35 import org.openecomp.sdc.be.datatypes.enums.ComponentTypeEnum;
36 import org.openecomp.sdc.be.datatypes.enums.GraphPropertyEnum;
37 import org.openecomp.sdc.be.datatypes.enums.JsonPresentationFields;
38 import org.openecomp.sdc.be.datatypes.enums.OriginTypeEnum;
39 import org.openecomp.sdc.be.datatypes.enums.ResourceTypeEnum;
40 import org.openecomp.sdc.be.model.*;
41 import org.openecomp.sdc.be.model.catalog.CatalogComponent;
42 import org.openecomp.sdc.be.model.jsontitan.datamodel.TopologyTemplate;
43 import org.openecomp.sdc.be.model.jsontitan.datamodel.ToscaElement;
44 import org.openecomp.sdc.be.model.jsontitan.utils.ModelConverter;
45 import org.openecomp.sdc.be.model.operations.api.StorageOperationStatus;
46 import org.openecomp.sdc.be.model.operations.impl.DaoStatusConverter;
47 import org.openecomp.sdc.be.model.operations.impl.UniqueIdBuilder;
48 import org.openecomp.sdc.be.resources.data.ComponentMetadataData;
49 import org.openecomp.sdc.common.jsongraph.util.CommonUtility;
50 import org.openecomp.sdc.common.jsongraph.util.CommonUtility.LogLevelEnum;
51 import org.openecomp.sdc.common.util.ValidationUtils;
52 import org.slf4j.Logger;
53 import org.slf4j.LoggerFactory;
54 import org.springframework.beans.factory.annotation.Autowired;
57 import java.util.Map.Entry;
58 import java.util.function.BiPredicate;
59 import java.util.stream.Collectors;
61 @org.springframework.stereotype.Component("tosca-operation-facade")
62 public class ToscaOperationFacade {
67 private NodeTypeOperation nodeTypeOperation;
69 private TopologyTemplateOperation topologyTemplateOperation;
71 private NodeTemplateOperation nodeTemplateOperation;
73 private GroupsOperation groupsOperation;
75 private TitanDao titanDao;
76 private static Logger log = LoggerFactory.getLogger(ToscaOperationFacade.class.getName());
79 // region - ToscaElement - GetById
80 public static final String PROXY_SUFFIX = "_proxy";
82 public <T extends Component> Either<T, StorageOperationStatus> getToscaElement(String componentId) {
84 return getToscaElement(componentId, JsonParseFlagEnum.ParseAll);
88 public <T extends Component> Either<T, StorageOperationStatus> getToscaFullElement(String componentId) {
89 ComponentParametersView filters = new ComponentParametersView();
90 filters.setIgnoreCapabiltyProperties(false);
91 filters.setIgnoreForwardingPath(false);
92 return getToscaElement(componentId, filters);
95 public <T extends Component> Either<T, StorageOperationStatus> getToscaElement(String componentId, ComponentParametersView filters) {
97 Either<GraphVertex, TitanOperationStatus> getVertexEither = titanDao.getVertexById(componentId, filters.detectParseFlag());
98 if (getVertexEither.isRight()) {
99 log.debug("Couldn't fetch component with and unique id {}, error: {}", componentId, getVertexEither.right().value());
100 return Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(getVertexEither.right().value()));
103 return getToscaElementByOperation(getVertexEither.left().value(), filters);
106 public <T extends Component> Either<T, StorageOperationStatus> getToscaElement(String componentId, JsonParseFlagEnum parseFlag) {
108 Either<GraphVertex, TitanOperationStatus> getVertexEither = titanDao.getVertexById(componentId, parseFlag);
109 if (getVertexEither.isRight()) {
110 log.debug("Couldn't fetch component with and unique id {}, error: {}", componentId, getVertexEither.right().value());
111 return Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(getVertexEither.right().value()));
114 return getToscaElementByOperation(getVertexEither.left().value());
117 public <T extends Component> Either<T, StorageOperationStatus> getToscaElement(GraphVertex componentVertex) {
118 return getToscaElementByOperation(componentVertex);
121 public Either<Boolean, StorageOperationStatus> validateComponentExists(String componentId) {
123 Either<GraphVertex, TitanOperationStatus> getVertexEither = titanDao.getVertexById(componentId, JsonParseFlagEnum.NoParse);
124 if (getVertexEither.isRight()) {
125 TitanOperationStatus status = getVertexEither.right().value();
126 if (status == TitanOperationStatus.NOT_FOUND) {
127 return Either.left(false);
129 log.debug("Couldn't fetch component with and unique id {}, error: {}", componentId, getVertexEither.right().value());
130 return Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(getVertexEither.right().value()));
133 return Either.left(true);
136 public <T extends Component> Either<T, StorageOperationStatus> findLastCertifiedToscaElementByUUID(T component) {
137 Map<GraphPropertyEnum, Object> props = new HashMap<>();
138 props.put(GraphPropertyEnum.UUID, component.getUUID());
139 props.put(GraphPropertyEnum.STATE, LifecycleStateEnum.CERTIFIED.name());
140 props.put(GraphPropertyEnum.IS_HIGHEST_VERSION, true);
142 Either<List<GraphVertex>, TitanOperationStatus> getVertexEither = titanDao.getByCriteria(ModelConverter.getVertexType(component), props);
143 if (getVertexEither.isRight()) {
144 log.debug("Couldn't fetch component with and unique id {}, error: {}", component.getUniqueId(), getVertexEither.right().value());
145 return Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(getVertexEither.right().value()));
148 return getToscaElementByOperation(getVertexEither.left().value().get(0));
152 // region - ToscaElement - GetByOperation
153 private <T extends Component> Either<T, StorageOperationStatus> getToscaElementByOperation(GraphVertex componentV) {
154 return getToscaElementByOperation(componentV, new ComponentParametersView());
157 private <T extends Component> Either<T, StorageOperationStatus> getToscaElementByOperation(GraphVertex componentV, ComponentParametersView filters) {
158 VertexTypeEnum label = componentV.getLabel();
160 ToscaElementOperation toscaOperation = getToscaElementOperation(componentV);
161 Either<ToscaElement, StorageOperationStatus> toscaElement;
162 String componentId = componentV.getUniqueId();
163 if (toscaOperation != null) {
164 log.debug("Need to fetch tosca element for id {}", componentId);
165 toscaElement = toscaOperation.getToscaElement(componentV, filters);
167 log.debug("not supported tosca type {} for id {}", label, componentId);
168 toscaElement = Either.right(StorageOperationStatus.BAD_REQUEST);
170 if (toscaElement.isRight()) {
171 return Either.right(toscaElement.right().value());
173 return Either.left(ModelConverter.convertFromToscaElement(toscaElement.left().value()));
177 private ToscaElementOperation getToscaElementOperation(GraphVertex componentV) {
178 VertexTypeEnum label = componentV.getLabel();
181 return nodeTypeOperation;
182 case TOPOLOGY_TEMPLATE:
183 return topologyTemplateOperation;
194 public <T extends Component> Either<T, StorageOperationStatus> createToscaComponent(T resource) {
195 ToscaElement toscaElement = ModelConverter.convertToToscaElement(resource);
197 ToscaElementOperation toscaElementOperation = getToscaElementOperation(resource);
198 Either<ToscaElement, StorageOperationStatus> createToscaElement = toscaElementOperation.createToscaElement(toscaElement);
199 if (createToscaElement.isLeft()) {
200 log.debug("Component created successfully!!!");
201 T dataModel = ModelConverter.convertFromToscaElement(createToscaElement.left().value());
202 return Either.left(dataModel);
204 return Either.right(createToscaElement.right().value());
207 // region - ToscaElement Delete
210 * @param componentToDelete
213 public StorageOperationStatus markComponentToDelete(Component componentToDelete) {
215 if ((componentToDelete.getIsDeleted() != null) && componentToDelete.getIsDeleted() && !componentToDelete.isHighestVersion()) {
216 // component already marked for delete
217 return StorageOperationStatus.OK;
220 Either<GraphVertex, TitanOperationStatus> getResponse = titanDao.getVertexById(componentToDelete.getUniqueId(), JsonParseFlagEnum.ParseAll);
221 if (getResponse.isRight()) {
222 log.debug("Couldn't fetch component with and unique id {}, error: {}", componentToDelete.getUniqueId(), getResponse.right().value());
223 return DaoStatusConverter.convertTitanStatusToStorageStatus(getResponse.right().value());
226 GraphVertex componentV = getResponse.left().value();
228 // same operation for node type and topology template operations
229 Either<GraphVertex, StorageOperationStatus> result = nodeTypeOperation.markComponentToDelete(componentV);
230 if (result.isRight()) {
231 return result.right().value();
233 return StorageOperationStatus.OK;
242 public <T extends Component> Either<T, StorageOperationStatus> deleteToscaComponent(String componentId) {
244 Either<GraphVertex, TitanOperationStatus> getVertexEither = titanDao.getVertexById(componentId, JsonParseFlagEnum.ParseAll);
245 if (getVertexEither.isRight()) {
246 log.debug("Couldn't fetch component vertex with and unique id {}, error: {}", componentId, getVertexEither.right().value());
247 return Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(getVertexEither.right().value()));
250 Either<ToscaElement, StorageOperationStatus> deleteElement = deleteToscaElement(getVertexEither.left().value());
251 if (deleteElement.isRight()) {
252 log.debug("Failed to delete component with and unique id {}, error: {}", componentId, deleteElement.right().value());
253 return Either.right(deleteElement.right().value());
255 T dataModel = ModelConverter.convertFromToscaElement(deleteElement.left().value());
257 return Either.left(dataModel);
260 private Either<ToscaElement, StorageOperationStatus> deleteToscaElement(GraphVertex componentV) {
261 VertexTypeEnum label = componentV.getLabel();
262 Either<ToscaElement, StorageOperationStatus> toscaElement;
263 Object componentId = componentV.getUniqueId();
266 log.debug("Need to fetch node type for id {}", componentId);
267 toscaElement = nodeTypeOperation.deleteToscaElement(componentV);
269 case TOPOLOGY_TEMPLATE:
270 log.debug("Need to fetch topology template for id {}", componentId);
271 toscaElement = topologyTemplateOperation.deleteToscaElement(componentV);
274 log.debug("not supported tosca type {} for id {}", label, componentId);
275 toscaElement = Either.right(StorageOperationStatus.BAD_REQUEST);
282 private ToscaElementOperation getToscaElementOperation(Component component) {
283 return ModelConverter.isAtomicComponent(component) ? nodeTypeOperation : topologyTemplateOperation;
286 public <T extends Component> Either<T, StorageOperationStatus> getLatestByToscaResourceName(String toscaResourceName) {
287 return getLatestByName(GraphPropertyEnum.TOSCA_RESOURCE_NAME, toscaResourceName);
290 public <T extends Component> Either<T, StorageOperationStatus> getFullLatestComponentByToscaResourceName(String toscaResourceName) {
291 ComponentParametersView fetchAllFilter = new ComponentParametersView();
292 fetchAllFilter.setIgnoreForwardingPath(true);
293 fetchAllFilter.setIgnoreCapabiltyProperties(false);
294 return getLatestByName(GraphPropertyEnum.TOSCA_RESOURCE_NAME, toscaResourceName, JsonParseFlagEnum.ParseAll, fetchAllFilter);
297 public <T extends Component> Either<T, StorageOperationStatus> getLatestByName(String resourceName) {
298 return getLatestByName(GraphPropertyEnum.NAME, resourceName);
302 public Either<Integer, StorageOperationStatus> validateCsarUuidUniqueness(String csarUUID) {
304 Map<GraphPropertyEnum, Object> properties = new HashMap<GraphPropertyEnum, Object>();
305 properties.put(GraphPropertyEnum.CSAR_UUID, csarUUID);
307 Either<List<GraphVertex>, TitanOperationStatus> resources = titanDao.getByCriteria(null, properties, JsonParseFlagEnum.ParseMetadata);
309 if (resources.isRight()) {
310 if (resources.right().value() == TitanOperationStatus.NOT_FOUND) {
311 return Either.left(new Integer(0));
313 log.debug("failed to get resources from graph with property name: {}", csarUUID);
314 return Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(resources.right().value()));
318 List<GraphVertex> resourceList = (resources.isLeft() ? resources.left().value() : null);
320 return Either.left(new Integer(resourceList.size()));
324 public <T extends Component> Either<Set<T>, StorageOperationStatus> getFollowed(String userId, Set<LifecycleStateEnum> lifecycleStates, Set<LifecycleStateEnum> lastStateStates, ComponentTypeEnum componentType) {
325 Either<List<ToscaElement>, StorageOperationStatus> followedResources;
326 if (componentType == ComponentTypeEnum.RESOURCE) {
327 followedResources = nodeTypeOperation.getFollowedComponent(userId, lifecycleStates, lastStateStates, componentType);
329 followedResources = topologyTemplateOperation.getFollowedComponent(userId, lifecycleStates, lastStateStates, componentType);
332 Set<T> components = new HashSet<>();
333 if (followedResources.isRight() && followedResources.right().value() != StorageOperationStatus.NOT_FOUND) {
334 return Either.right(followedResources.right().value());
336 if (followedResources.isLeft()) {
337 List<ToscaElement> toscaElements = followedResources.left().value();
338 toscaElements.forEach(te -> {
339 T component = ModelConverter.convertFromToscaElement(te);
340 components.add(component);
343 return Either.left(components);
346 public Either<Resource, StorageOperationStatus> getLatestCertifiedNodeTypeByToscaResourceName(String toscaResourceName) {
348 return getLatestCertifiedByToscaResourceName(toscaResourceName, VertexTypeEnum.NODE_TYPE, JsonParseFlagEnum.ParseMetadata);
351 public Either<Resource, StorageOperationStatus> getLatestCertifiedByToscaResourceName(String toscaResourceName, VertexTypeEnum vertexType, JsonParseFlagEnum parseFlag) {
353 Either<Resource, StorageOperationStatus> result = null;
354 Map<GraphPropertyEnum, Object> props = new HashMap<GraphPropertyEnum, Object>();
355 props.put(GraphPropertyEnum.TOSCA_RESOURCE_NAME, toscaResourceName);
356 props.put(GraphPropertyEnum.IS_HIGHEST_VERSION, true);
357 props.put(GraphPropertyEnum.STATE, LifecycleStateEnum.CERTIFIED.name());
358 Either<List<GraphVertex>, TitanOperationStatus> getLatestRes = titanDao.getByCriteria(vertexType, props, parseFlag);
360 if (getLatestRes.isRight()) {
361 TitanOperationStatus status = getLatestRes.right().value();
362 CommonUtility.addRecordToLog(log, LogLevelEnum.DEBUG, "Failed to fetch {} with name {}. status={} ", vertexType, toscaResourceName, status);
363 result = Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(status));
365 if (result == null) {
366 List<GraphVertex> resources = getLatestRes.left().value();
367 double version = 0.0;
368 GraphVertex highestResource = null;
369 for (GraphVertex resource : resources) {
370 double resourceVersion = Double.parseDouble((String) resource.getJsonMetadataField(JsonPresentationFields.VERSION));
371 if (resourceVersion > version) {
372 version = resourceVersion;
373 highestResource = resource;
376 result = getToscaFullElement(highestResource.getUniqueId());
381 public Either<Boolean, StorageOperationStatus> validateToscaResourceNameExists(String templateName) {
382 Either<Boolean, StorageOperationStatus> validateUniquenessRes = validateToscaResourceNameUniqueness(templateName);
383 if (validateUniquenessRes.isLeft()) {
384 return Either.left(!validateUniquenessRes.left().value());
386 return validateUniquenessRes;
389 public Either<RequirementCapabilityRelDef, StorageOperationStatus> dissociateResourceInstances(String componentId, RequirementCapabilityRelDef requirementDef) {
390 return nodeTemplateOperation.dissociateResourceInstances(componentId, requirementDef);
393 * Allows to get fulfilled requirement by relation and received predicate
400 public Either<RequirementDataDefinition, StorageOperationStatus> getFulfilledRequirementByRelation(String componentId, String instanceId, RequirementCapabilityRelDef relation, BiPredicate<RelationshipInfo, RequirementDataDefinition> predicate) {
401 return nodeTemplateOperation.getFulfilledRequirementByRelation(componentId, instanceId, relation, predicate);
404 * Allows to get fulfilled capability by relation and received predicate
411 public Either<CapabilityDataDefinition, StorageOperationStatus> getFulfilledCapabilityByRelation(String componentId, String instanceId, RequirementCapabilityRelDef relation, BiPredicate<RelationshipInfo, CapabilityDataDefinition> predicate) {
412 return nodeTemplateOperation.getFulfilledCapabilityByRelation(componentId, instanceId, relation, predicate);
415 public StorageOperationStatus associateResourceInstances(String componentId, List<RequirementCapabilityRelDef> relations) {
416 Either<List<RequirementCapabilityRelDef>, StorageOperationStatus> status = nodeTemplateOperation.associateResourceInstances(componentId, relations);
417 if (status.isRight()) {
418 return status.right().value();
420 return StorageOperationStatus.OK;
423 protected Either<Boolean, StorageOperationStatus> validateToscaResourceNameUniqueness(String name) {
425 Map<GraphPropertyEnum, Object> properties = new HashMap<GraphPropertyEnum, Object>();
426 properties.put(GraphPropertyEnum.TOSCA_RESOURCE_NAME, name);
428 Either<List<GraphVertex>, TitanOperationStatus> resources = titanDao.getByCriteria(null, properties, JsonParseFlagEnum.ParseMetadata);
430 if (resources.isRight() && resources.right().value() != TitanOperationStatus.NOT_FOUND) {
431 log.debug("failed to get resources from graph with property name: {}", name);
432 return Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(resources.right().value()));
434 List<GraphVertex> resourceList = (resources.isLeft() ? resources.left().value() : null);
435 if (resourceList != null && resourceList.size() > 0) {
436 if (log.isDebugEnabled()) {
437 StringBuilder builder = new StringBuilder();
438 for (GraphVertex resourceData : resourceList) {
439 builder.append(resourceData.getUniqueId() + "|");
441 log.debug("resources with property name:{} exists in graph. found {}", name, builder.toString());
443 return Either.left(false);
445 log.debug("resources with property name:{} does not exists in graph", name);
446 return Either.left(true);
451 private List<InputDefinition> getNewInputsByResourceType(Resource component) {
452 return component.getResourceType().equals(ResourceTypeEnum.CVFC) ?
453 component.getInputs() : null;
456 // region - Component Update
459 * @param newComponent
460 * @param oldComponent
463 public Either<Resource, StorageOperationStatus> overrideComponent(Resource newComponent, Resource oldComponent) {
466 // newComponent.setInterfaces(oldComponent.getInterfaces);
467 newComponent.setArtifacts(oldComponent.getArtifacts());
468 newComponent.setDeploymentArtifacts(oldComponent.getDeploymentArtifacts());
469 newComponent.setGroups(oldComponent.getGroups());
470 newComponent.setLastUpdateDate(null);
471 newComponent.setHighestVersion(true);
473 Either<GraphVertex, TitanOperationStatus> componentVEither = titanDao.getVertexById(oldComponent.getUniqueId(), JsonParseFlagEnum.NoParse);
474 if (componentVEither.isRight()) {
475 log.debug("Falied to fetch component {} error {}", oldComponent.getUniqueId(), componentVEither.right().value());
476 return Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(componentVEither.right().value()));
478 GraphVertex componentv = componentVEither.left().value();
479 Either<GraphVertex, TitanOperationStatus> parentVertexEither = titanDao.getParentVertex(componentv, EdgeLabelEnum.VERSION, JsonParseFlagEnum.NoParse);
480 if (parentVertexEither.isRight() && parentVertexEither.right().value() != TitanOperationStatus.NOT_FOUND) {
481 log.debug("Falied to fetch parent version for component {} error {}", oldComponent.getUniqueId(), parentVertexEither.right().value());
482 return Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(parentVertexEither.right().value()));
485 Either<ToscaElement, StorageOperationStatus> deleteToscaComponent = deleteToscaElement(componentv);
486 if (deleteToscaComponent.isRight()) {
487 log.debug("Falied to remove old component {} error {}", oldComponent.getUniqueId(), deleteToscaComponent.right().value());
488 return Either.right(deleteToscaComponent.right().value());
490 Either<Resource, StorageOperationStatus> createToscaComponent = createToscaComponent(newComponent);
491 if (createToscaComponent.isRight()) {
492 log.debug("Falied to create tosca element component {} error {}", newComponent.getUniqueId(), createToscaComponent.right().value());
493 return Either.right(createToscaComponent.right().value());
495 Resource newElement = createToscaComponent.left().value();
496 Either<GraphVertex, TitanOperationStatus> newVersionEither = titanDao.getVertexById(newElement.getUniqueId(), JsonParseFlagEnum.NoParse);
497 if (newVersionEither.isRight()) {
498 log.debug("Falied to fetch new tosca element component {} error {}", newComponent.getUniqueId(), newVersionEither.right().value());
499 return Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(newVersionEither.right().value()));
501 if (parentVertexEither.isLeft()) {
502 GraphVertex previousVersionV = parentVertexEither.left().value();
503 TitanOperationStatus createEdge = titanDao.createEdge(previousVersionV, newVersionEither.left().value(), EdgeLabelEnum.VERSION, null);
504 if (createEdge != TitanOperationStatus.OK) {
505 log.debug("Falied to associate to previous version {} new version {} error {}", previousVersionV.getUniqueId(), newVersionEither.right().value(), createEdge);
506 return Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(createEdge));
509 return Either.left(newElement);
514 * @param componentToUpdate
517 public <T extends Component> Either<T, StorageOperationStatus> updateToscaElement(T componentToUpdate) {
518 return updateToscaElement(componentToUpdate, new ComponentParametersView());
523 * @param componentToUpdate
525 * @param filterResult
528 public <T extends Component> Either<T, StorageOperationStatus> updateToscaElement(T componentToUpdate, ComponentParametersView filterResult) {
529 String componentId = componentToUpdate.getUniqueId();
530 Either<GraphVertex, TitanOperationStatus> getVertexEither = titanDao.getVertexById(componentId, JsonParseFlagEnum.ParseAll);
531 if (getVertexEither.isRight()) {
532 log.debug("Couldn't fetch component with and unique id {}, error: {}", componentId, getVertexEither.right().value());
533 return Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(getVertexEither.right().value()));
535 GraphVertex elementV = getVertexEither.left().value();
536 ToscaElementOperation toscaElementOperation = getToscaElementOperation(elementV);
538 ToscaElement toscaElementToUpdate = ModelConverter.convertToToscaElement(componentToUpdate);
539 Either<ToscaElement, StorageOperationStatus> updateToscaElement = toscaElementOperation.updateToscaElement(toscaElementToUpdate, elementV, filterResult);
540 if (updateToscaElement.isRight()) {
541 log.debug("Failed to update tosca element {} error {}", componentId, updateToscaElement.right().value());
542 return Either.right(updateToscaElement.right().value());
544 return Either.left(ModelConverter.convertFromToscaElement(updateToscaElement.left().value()));
547 private <T extends Component> Either<T, StorageOperationStatus> getLatestByName(GraphPropertyEnum property, String nodeName, JsonParseFlagEnum parseFlag) {
548 return getLatestByName(property, nodeName, parseFlag, new ComponentParametersView());
551 private <T extends Component> Either<T, StorageOperationStatus> getLatestByName(GraphPropertyEnum property, String nodeName, JsonParseFlagEnum parseFlag, ComponentParametersView filter) {
552 Either<T, StorageOperationStatus> result;
554 Map<GraphPropertyEnum, Object> propertiesToMatch = new EnumMap<>(GraphPropertyEnum.class);
555 Map<GraphPropertyEnum, Object> propertiesNotToMatch = new EnumMap<>(GraphPropertyEnum.class);
557 propertiesToMatch.put(property, nodeName);
558 propertiesToMatch.put(GraphPropertyEnum.IS_HIGHEST_VERSION, true);
560 propertiesNotToMatch.put(GraphPropertyEnum.IS_DELETED, true);
562 Either<List<GraphVertex>, TitanOperationStatus> highestResources = titanDao.getByCriteria(null, propertiesToMatch, propertiesNotToMatch, parseFlag);
563 if (highestResources.isRight()) {
564 TitanOperationStatus status = highestResources.right().value();
565 log.debug("failed to find resource with name {}. status={} ", nodeName, status);
566 result = Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(status));
570 List<GraphVertex> resources = highestResources.left().value();
571 double version = 0.0;
572 GraphVertex highestResource = null;
573 for (GraphVertex vertex : resources) {
574 Object versionObj = vertex.getMetadataProperty(GraphPropertyEnum.VERSION);
575 double resourceVersion = Double.valueOf((String) versionObj);
576 if (resourceVersion > version) {
577 version = resourceVersion;
578 highestResource = vertex;
581 return getToscaElementByOperation(highestResource, filter);
585 // region - Component Get By ..
586 private <T extends Component> Either<T, StorageOperationStatus> getLatestByName(GraphPropertyEnum property, String nodeName) {
587 return getLatestByName(property, nodeName, JsonParseFlagEnum.ParseMetadata);
590 public <T extends Component> Either<List<T>, StorageOperationStatus> getBySystemName(ComponentTypeEnum componentType, String systemName) {
592 Either<List<T>, StorageOperationStatus> result = null;
593 Either<T, StorageOperationStatus> getComponentRes;
594 List<T> components = new ArrayList<>();
595 List<GraphVertex> componentVertices;
596 Map<GraphPropertyEnum, Object> propertiesToMatch = new EnumMap<>(GraphPropertyEnum.class);
597 Map<GraphPropertyEnum, Object> propertiesNotToMatch = new EnumMap<>(GraphPropertyEnum.class);
599 propertiesToMatch.put(GraphPropertyEnum.SYSTEM_NAME, systemName);
600 if (componentType != null)
601 propertiesToMatch.put(GraphPropertyEnum.COMPONENT_TYPE, componentType.name());
603 propertiesNotToMatch.put(GraphPropertyEnum.IS_DELETED, true);
605 Either<List<GraphVertex>, TitanOperationStatus> getComponentsRes = titanDao.getByCriteria(null, propertiesToMatch, propertiesNotToMatch, JsonParseFlagEnum.ParseAll);
606 if (getComponentsRes.isRight()) {
607 TitanOperationStatus status = getComponentsRes.right().value();
608 log.debug("Failed to fetch the component with system name {}. Status is {} ", systemName, status);
609 result = Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(status));
611 if (result == null) {
612 componentVertices = getComponentsRes.left().value();
613 for (GraphVertex componentVertex : componentVertices) {
614 getComponentRes = getToscaElementByOperation(componentVertex);
615 if (getComponentRes.isRight()) {
616 log.debug("Failed to get the component {}. Status is {} ", componentVertex.getJsonMetadataField(JsonPresentationFields.NAME), getComponentRes.right().value());
617 result = Either.right(getComponentRes.right().value());
620 T componentBySystemName = getComponentRes.left().value();
621 log.debug("Found component, id: {}", componentBySystemName.getUniqueId());
622 components.add(componentBySystemName);
625 if (result == null) {
626 result = Either.left(components);
631 public <T extends Component> Either<T, StorageOperationStatus> getComponentByNameAndVersion(ComponentTypeEnum componentType, String name, String version) {
632 return getComponentByNameAndVersion(componentType, name, version, JsonParseFlagEnum.ParseAll);
635 public <T extends Component> Either<T, StorageOperationStatus> getComponentByNameAndVersion(ComponentTypeEnum componentType, String name, String version, JsonParseFlagEnum parseFlag) {
636 Either<T, StorageOperationStatus> result;
638 Map<GraphPropertyEnum, Object> hasProperties = new EnumMap<>(GraphPropertyEnum.class);
639 Map<GraphPropertyEnum, Object> hasNotProperties = new EnumMap<>(GraphPropertyEnum.class);
641 hasProperties.put(GraphPropertyEnum.NAME, name);
642 hasProperties.put(GraphPropertyEnum.VERSION, version);
643 hasNotProperties.put(GraphPropertyEnum.IS_DELETED, true);
644 if (componentType != null) {
645 hasProperties.put(GraphPropertyEnum.COMPONENT_TYPE, componentType.name());
647 Either<List<GraphVertex>, TitanOperationStatus> getResourceRes = titanDao.getByCriteria(null, hasProperties, hasNotProperties, parseFlag);
648 if (getResourceRes.isRight()) {
649 TitanOperationStatus status = getResourceRes.right().value();
650 log.debug("failed to find resource with name {}, version {}. Status is {} ", name, version, status);
651 result = Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(status));
654 return getToscaElementByOperation(getResourceRes.left().value().get(0));
656 public Either<List<CatalogComponent>, StorageOperationStatus> getCatalogComponents() {
657 return topologyTemplateOperation.getElementCatalogData();
661 public <T extends Component> Either<List<T>, StorageOperationStatus> getCatalogComponents(ComponentTypeEnum componentType, List<OriginTypeEnum> excludeTypes, boolean isHighestVersions) {
662 List<T> components = new ArrayList<>();
663 Either<List<ToscaElement>, StorageOperationStatus> catalogDataResult;
664 List<ToscaElement> toscaElements = new ArrayList<>();
665 List<ResourceTypeEnum> excludedResourceTypes = Optional.ofNullable(excludeTypes).orElse(Collections.emptyList()).stream().filter(type -> !type.equals(OriginTypeEnum.SERVICE)).map(type -> ResourceTypeEnum.getTypeByName(type.name()))
666 .collect(Collectors.toList());
668 switch (componentType) {
670 catalogDataResult = nodeTypeOperation.getElementCatalogData(ComponentTypeEnum.RESOURCE, excludedResourceTypes, isHighestVersions);
671 if (catalogDataResult.isRight()) {
672 return Either.right(catalogDataResult.right().value());
674 toscaElements = catalogDataResult.left().value();
677 if (excludeTypes != null && excludeTypes.contains(OriginTypeEnum.SERVICE)) {
680 catalogDataResult = topologyTemplateOperation.getElementCatalogData(ComponentTypeEnum.SERVICE, null, isHighestVersions);
681 if (catalogDataResult.isRight()) {
682 return Either.right(catalogDataResult.right().value());
684 toscaElements = catalogDataResult.left().value();
687 log.debug("Not supported component type {}", componentType);
688 return Either.right(StorageOperationStatus.BAD_REQUEST);
690 toscaElements.forEach(te -> {
691 T component = ModelConverter.convertFromToscaElement(te);
692 components.add(component);
694 return Either.left(components);
697 public Either<List<String>, StorageOperationStatus> deleteMarkedElements(ComponentTypeEnum componentType) {
698 Either<List<GraphVertex>, StorageOperationStatus> allComponentsMarkedForDeletion;
699 List<String> deleted = new ArrayList<>();
700 switch (componentType) {
702 allComponentsMarkedForDeletion = nodeTypeOperation.getAllComponentsMarkedForDeletion(componentType);
706 allComponentsMarkedForDeletion = topologyTemplateOperation.getAllComponentsMarkedForDeletion(componentType);
709 log.debug("Not supported component type {}", componentType);
710 return Either.right(StorageOperationStatus.BAD_REQUEST);
712 if (allComponentsMarkedForDeletion.isRight()) {
713 return Either.right(allComponentsMarkedForDeletion.right().value());
715 List<GraphVertex> allMarked = allComponentsMarkedForDeletion.left().value();
717 Either<List<GraphVertex>, TitanOperationStatus> allNotDeletedElements = topologyTemplateOperation.getAllNotDeletedElements();
718 if (allNotDeletedElements.isRight()) {
719 return Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(allNotDeletedElements.right().value()));
721 List<GraphVertex> allNonMarked = allNotDeletedElements.left().value();
722 for (GraphVertex elementV : allMarked) {
723 if (topologyTemplateOperation.isInUse(elementV, allNonMarked) == false) {
724 Either<ToscaElement, StorageOperationStatus> deleteToscaElement = deleteToscaElement(elementV);
725 if (deleteToscaElement.isRight()) {
726 log.debug("Failed to delete marked element {} error {}", elementV.getUniqueId(), deleteToscaElement.right().value());
729 deleted.add(elementV.getUniqueId());
730 log.debug("Marked element {} in use. don't delete it", elementV.getUniqueId());
733 return Either.left(deleted);
736 public Either<List<String>, StorageOperationStatus> getAllComponentsMarkedForDeletion(ComponentTypeEnum componentType) {
737 Either<List<GraphVertex>, StorageOperationStatus> allComponentsMarkedForDeletion;
738 switch (componentType) {
740 allComponentsMarkedForDeletion = nodeTypeOperation.getAllComponentsMarkedForDeletion(componentType);
744 allComponentsMarkedForDeletion = topologyTemplateOperation.getAllComponentsMarkedForDeletion(componentType);
747 log.debug("Not supported component type {}", componentType);
748 return Either.right(StorageOperationStatus.BAD_REQUEST);
750 if (allComponentsMarkedForDeletion.isRight()) {
751 return Either.right(allComponentsMarkedForDeletion.right().value());
753 return Either.left(allComponentsMarkedForDeletion.left().value().stream().map(v -> v.getUniqueId()).collect(Collectors.toList()));
756 public Either<Boolean, StorageOperationStatus> isComponentInUse(String componentId) {
757 Either<Boolean, StorageOperationStatus> result;
758 Either<List<GraphVertex>, TitanOperationStatus> allNotDeletedElements = topologyTemplateOperation.getAllNotDeletedElements();
759 if (allNotDeletedElements.isRight()) {
760 result = Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(allNotDeletedElements.right().value()));
762 result = Either.left(topologyTemplateOperation.isInUse(componentId, allNotDeletedElements.left().value()));
767 // region - Component Update
768 public Either<ImmutablePair<Component, String>, StorageOperationStatus> addComponentInstanceToTopologyTemplate(Component containerComponent, Component origComponent, ComponentInstance componentInstance, boolean allowDeleted, User user) {
770 Either<ImmutablePair<Component, String>, StorageOperationStatus> result = null;
771 Either<ToscaElement, StorageOperationStatus> updateContainerComponentRes = null;
772 if (StringUtils.isEmpty(componentInstance.getIcon())) {
773 componentInstance.setIcon(origComponent.getIcon());
775 String nameToFindForCounter = componentInstance.getOriginType() == OriginTypeEnum.ServiceProxy ? componentInstance.getSourceModelName() + PROXY_SUFFIX : origComponent.getName();
776 String nextComponentInstanceCounter = getNextComponentInstanceCounter(containerComponent, nameToFindForCounter);
777 Either<ImmutablePair<TopologyTemplate, String>, StorageOperationStatus> addResult = nodeTemplateOperation.addComponentInstanceToTopologyTemplate(ModelConverter.convertToToscaElement(containerComponent),
778 ModelConverter.convertToToscaElement(origComponent), nextComponentInstanceCounter, componentInstance, allowDeleted, user);
780 if (addResult.isRight()) {
781 CommonUtility.addRecordToLog(log, LogLevelEnum.DEBUG, "Failed to add the component instance {} to container component {}. ", componentInstance.getName(), containerComponent.getName());
782 result = Either.right(addResult.right().value());
784 if (result == null) {
785 updateContainerComponentRes = topologyTemplateOperation.getToscaElement(containerComponent.getUniqueId());
786 if (updateContainerComponentRes.isRight()) {
787 CommonUtility.addRecordToLog(log, LogLevelEnum.DEBUG, "Failed to fetch updated topology template {} with updated component instance {}. ", containerComponent.getName(), componentInstance.getName());
788 result = Either.right(updateContainerComponentRes.right().value());
791 if (result == null) {
792 Component updatedComponent = ModelConverter.convertFromToscaElement(updateContainerComponentRes.left().value());
793 String createdInstanceId = addResult.left().value().getRight();
794 CommonUtility.addRecordToLog(log, LogLevelEnum.TRACE, "The component instance {} has been added to container component {}. ", createdInstanceId, updatedComponent.getName());
795 result = Either.left(new ImmutablePair<>(updatedComponent, createdInstanceId));
800 public StorageOperationStatus associateComponentInstancesToComponent(Component containerComponent, Map<ComponentInstance, Resource> resourcesInstancesMap, boolean allowDeleted) {
802 StorageOperationStatus result = null;
803 CommonUtility.addRecordToLog(log, LogLevelEnum.DEBUG, "Going to add component instances to component {}", containerComponent.getUniqueId());
805 Either<GraphVertex, TitanOperationStatus> metadataVertex = titanDao.getVertexById(containerComponent.getUniqueId(), JsonParseFlagEnum.ParseAll);
806 if (metadataVertex.isRight()) {
807 TitanOperationStatus status = metadataVertex.right().value();
808 if (status == TitanOperationStatus.NOT_FOUND) {
809 status = TitanOperationStatus.INVALID_ID;
811 result = DaoStatusConverter.convertTitanStatusToStorageStatus(status);
813 if (result == null) {
814 result = nodeTemplateOperation.associateComponentInstancesToComponent(containerComponent, resourcesInstancesMap, metadataVertex.left().value(), allowDeleted);
819 public Either<ImmutablePair<Component, String>, StorageOperationStatus> updateComponentInstanceMetadataOfTopologyTemplate(Component containerComponent, Component origComponent, ComponentInstance componentInstance) {
821 Either<ImmutablePair<Component, String>, StorageOperationStatus> result = null;
823 CommonUtility.addRecordToLog(log, LogLevelEnum.TRACE, "Going to update the metadata of the component instance {} belonging to container component {}. ", componentInstance.getName(), containerComponent.getName());
824 componentInstance.setIcon(origComponent.getIcon());
825 Either<ImmutablePair<TopologyTemplate, String>, StorageOperationStatus> updateResult = nodeTemplateOperation.updateComponentInstanceMetadataOfTopologyTemplate(ModelConverter.convertToToscaElement(containerComponent),
826 ModelConverter.convertToToscaElement(origComponent), componentInstance);
827 if (updateResult.isRight()) {
828 CommonUtility.addRecordToLog(log, LogLevelEnum.DEBUG, "Failed to update the metadata of the component instance {} belonging to container component {}. ", componentInstance.getName(), containerComponent.getName());
829 result = Either.right(updateResult.right().value());
831 if (result == null) {
832 Component updatedComponent = ModelConverter.convertFromToscaElement(updateResult.left().value().getLeft());
833 String createdInstanceId = updateResult.left().value().getRight();
834 CommonUtility.addRecordToLog(log, LogLevelEnum.TRACE, "The metadata of the component instance {} has been updated to container component {}. ", createdInstanceId, updatedComponent.getName());
835 result = Either.left(new ImmutablePair<>(updatedComponent, createdInstanceId));
840 public Either<Component, StorageOperationStatus> updateComponentInstanceMetadataOfTopologyTemplate(Component containerComponent) {
841 return updateComponentInstanceMetadataOfTopologyTemplate(containerComponent, new ComponentParametersView());
844 public Either<Component, StorageOperationStatus> updateComponentInstanceMetadataOfTopologyTemplate(Component containerComponent, ComponentParametersView filter) {
846 Either<Component, StorageOperationStatus> result = null;
848 CommonUtility.addRecordToLog(log, LogLevelEnum.TRACE, "Going to update the metadata belonging to container component {}. ", containerComponent.getName());
850 Either<TopologyTemplate, StorageOperationStatus> updateResult = nodeTemplateOperation.updateComponentInstanceMetadataOfTopologyTemplate(ModelConverter.convertToToscaElement(containerComponent), filter);
851 if (updateResult.isRight()) {
852 CommonUtility.addRecordToLog(log, LogLevelEnum.DEBUG, "Failed to update the metadata belonging to container component {}. ", containerComponent.getName());
853 result = Either.right(updateResult.right().value());
855 if (result == null) {
856 Component updatedComponent = ModelConverter.convertFromToscaElement(updateResult.left().value());
857 CommonUtility.addRecordToLog(log, LogLevelEnum.TRACE, "The metadata has been updated to container component {}. ", updatedComponent.getName());
858 result = Either.left(updatedComponent);
864 public Either<ImmutablePair<Component, String>, StorageOperationStatus> deleteComponentInstanceFromTopologyTemplate(Component containerComponent, String resourceInstanceId) {
866 Either<ImmutablePair<Component, String>, StorageOperationStatus> result = null;
868 CommonUtility.addRecordToLog(log, LogLevelEnum.TRACE, "Going to delete the component instance {} belonging to container component {}. ", resourceInstanceId, containerComponent.getName());
870 Either<ImmutablePair<TopologyTemplate, String>, StorageOperationStatus> updateResult = nodeTemplateOperation.deleteComponentInstanceFromTopologyTemplate(ModelConverter.convertToToscaElement(containerComponent), resourceInstanceId);
871 if (updateResult.isRight()) {
872 CommonUtility.addRecordToLog(log, LogLevelEnum.DEBUG, "Failed to delete the component instance {} belonging to container component {}. ", resourceInstanceId, containerComponent.getName());
873 result = Either.right(updateResult.right().value());
875 if (result == null) {
876 Component updatedComponent = ModelConverter.convertFromToscaElement(updateResult.left().value().getLeft());
877 String deletedInstanceId = updateResult.left().value().getRight();
878 CommonUtility.addRecordToLog(log, LogLevelEnum.TRACE, "The component instance {} has been deleted from container component {}. ", deletedInstanceId, updatedComponent.getName());
879 result = Either.left(new ImmutablePair<>(updatedComponent, deletedInstanceId));
884 private String getNextComponentInstanceCounter(Component containerComponent, String originResourceName) {
886 Integer nextCounter = 0;
888 if (CollectionUtils.isNotEmpty(containerComponent.getComponentInstances())) {
890 String normalizedName = ValidationUtils.normalizeComponentInstanceName(originResourceName);
891 Integer maxCounterFromNames = getMaxCounterFromNames(containerComponent, normalizedName);
892 Integer maxCounterFromIds = getMaxCounterFromIds(containerComponent, normalizedName);
894 if (maxCounterFromNames == null && maxCounterFromIds != null) {
895 nextCounter = maxCounterFromIds + 1;
896 } else if (maxCounterFromIds == null && maxCounterFromNames != null) {
897 nextCounter = maxCounterFromNames + 1;
898 } else if (maxCounterFromIds != null && maxCounterFromNames != null) {
899 nextCounter = maxCounterFromNames > maxCounterFromIds ? maxCounterFromNames + 1 : maxCounterFromIds + 1;
902 return nextCounter.toString();
905 private Integer getMaxCounterFromNames(Component containerComponent, String normalizedName) {
907 Integer maxCounter = 0;
908 List<String> countersStr = containerComponent.getComponentInstances().stream().filter(ci -> ci.getNormalizedName() != null && ci.getNormalizedName().startsWith(normalizedName)).map(ci -> ci.getNormalizedName().split(normalizedName)[1])
909 .collect(Collectors.toList());
911 if (CollectionUtils.isEmpty(countersStr)) {
914 Integer currCounter = null;
915 for (String counter : countersStr) {
916 if (StringUtils.isEmpty(counter)) {
920 currCounter = Integer.parseInt(counter);
921 } catch (Exception e) {
924 maxCounter = maxCounter < currCounter ? currCounter : maxCounter;
926 if (currCounter == null) {
932 private Integer getMaxCounterFromIds(Component containerComponent, String normalizedName) {
934 Integer maxCounter = 0;
935 List<String> countersStr = containerComponent.getComponentInstances().stream().filter(ci -> ci.getUniqueId() != null && ci.getUniqueId().contains(normalizedName)).map(ci -> ci.getUniqueId().split(normalizedName)[1])
936 .collect(Collectors.toList());
938 if (CollectionUtils.isEmpty(countersStr)) {
941 Integer currCounter = null;
942 for (String counter : countersStr) {
943 if (StringUtils.isEmpty(counter)) {
947 currCounter = Integer.parseInt(counter);
948 } catch (Exception e) {
951 maxCounter = maxCounter < currCounter ? currCounter : maxCounter;
953 if (currCounter == null) {
959 public Either<RequirementCapabilityRelDef, StorageOperationStatus> associateResourceInstances(String componentId, RequirementCapabilityRelDef requirementDef) {
960 return nodeTemplateOperation.associateResourceInstances(componentId, requirementDef);
964 public Either<List<InputDefinition>, StorageOperationStatus> createAndAssociateInputs(Map<String, InputDefinition> inputs, String componentId) {
966 Either<GraphVertex, TitanOperationStatus> getVertexEither = titanDao.getVertexById(componentId, JsonParseFlagEnum.NoParse);
967 if (getVertexEither.isRight()) {
968 log.debug("Couldn't fetch component with and unique id {}, error: {}", componentId, getVertexEither.right().value());
969 return Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(getVertexEither.right().value()));
973 GraphVertex vertex = getVertexEither.left().value();
974 Map<String, PropertyDataDefinition> inputsMap = inputs.entrySet().stream().collect(Collectors.toMap(Map.Entry::getKey, e -> new PropertyDataDefinition(e.getValue())));
976 StorageOperationStatus status = topologyTemplateOperation.associateInputsToComponent(vertex, inputsMap, componentId);
978 if (StorageOperationStatus.OK == status) {
979 log.debug("Component created successfully!!!");
980 List<InputDefinition> inputsResList = null;
981 if (inputsMap != null && !inputsMap.isEmpty()) {
982 inputsResList = inputsMap.values().stream().map(i -> new InputDefinition(i)).collect(Collectors.toList());
984 return Either.left(inputsResList);
986 return Either.right(status);
990 public Either<List<InputDefinition>, StorageOperationStatus> addInputsToComponent(Map<String, InputDefinition> inputs, String componentId) {
992 Either<GraphVertex, TitanOperationStatus> getVertexEither = titanDao.getVertexById(componentId, JsonParseFlagEnum.NoParse);
993 if (getVertexEither.isRight()) {
994 log.debug("Couldn't fetch component with and unique id {}, error: {}", componentId, getVertexEither.right().value());
995 return Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(getVertexEither.right().value()));
999 GraphVertex vertex = getVertexEither.left().value();
1000 Map<String, PropertyDataDefinition> inputsMap = inputs.entrySet().stream().collect(Collectors.toMap(Map.Entry::getKey, e -> new PropertyDataDefinition(e.getValue())));
1002 StorageOperationStatus status = topologyTemplateOperation.addToscaDataToToscaElement(vertex, EdgeLabelEnum.INPUTS, VertexTypeEnum.INPUTS, inputsMap, JsonPresentationFields.NAME);
1004 if (StorageOperationStatus.OK == status) {
1005 log.debug("Component created successfully!!!");
1006 List<InputDefinition> inputsResList = null;
1007 if (inputsMap != null && !inputsMap.isEmpty()) {
1008 inputsResList = inputsMap.values().stream().map(i -> new InputDefinition(i)).collect(Collectors.toList());
1010 return Either.left(inputsResList);
1012 return Either.right(status);
1016 public Either<List<InputDefinition>, StorageOperationStatus> updateInputsToComponent(List<InputDefinition> inputs, String componentId) {
1018 Either<GraphVertex, TitanOperationStatus> getVertexEither = titanDao.getVertexById(componentId, JsonParseFlagEnum.NoParse);
1019 if (getVertexEither.isRight()) {
1020 log.debug("Couldn't fetch component with and unique id {}, error: {}", componentId, getVertexEither.right().value());
1021 return Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(getVertexEither.right().value()));
1025 GraphVertex vertex = getVertexEither.left().value();
1026 List<PropertyDataDefinition> inputsAsDataDef = inputs.stream().map(PropertyDataDefinition::new).collect(Collectors.toList());
1028 StorageOperationStatus status = topologyTemplateOperation.updateToscaDataOfToscaElement(vertex, EdgeLabelEnum.INPUTS, VertexTypeEnum.INPUTS, inputsAsDataDef, JsonPresentationFields.NAME);
1030 if (StorageOperationStatus.OK == status) {
1031 log.debug("Component created successfully!!!");
1032 List<InputDefinition> inputsResList = null;
1033 if (inputsAsDataDef != null && !inputsAsDataDef.isEmpty()) {
1034 inputsResList = inputsAsDataDef.stream().map(InputDefinition::new).collect(Collectors.toList());
1036 return Either.left(inputsResList);
1038 return Either.right(status);
1042 // region - ComponentInstance
1043 public Either<Map<String, List<ComponentInstanceProperty>>, StorageOperationStatus> associateComponentInstancePropertiesToComponent(Map<String, List<ComponentInstanceProperty>> instProperties, String componentId) {
1045 Either<GraphVertex, TitanOperationStatus> getVertexEither = titanDao.getVertexById(componentId, JsonParseFlagEnum.NoParse);
1046 if (getVertexEither.isRight()) {
1047 log.debug("Couldn't fetch component with and unique id {}, error: {}", componentId, getVertexEither.right().value());
1048 return Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(getVertexEither.right().value()));
1052 GraphVertex vertex = getVertexEither.left().value();
1053 Map<String, MapPropertiesDataDefinition> instPropsMap = new HashMap<>();
1054 if (instProperties != null) {
1056 MapPropertiesDataDefinition propertiesMap;
1057 for (Entry<String, List<ComponentInstanceProperty>> entry : instProperties.entrySet()) {
1058 propertiesMap = new MapPropertiesDataDefinition();
1060 propertiesMap.setMapToscaDataDefinition(entry.getValue().stream().map(e -> new PropertyDataDefinition(e)).collect(Collectors.toMap(e -> e.getName(), e -> e)));
1062 instPropsMap.put(entry.getKey(), propertiesMap);
1066 StorageOperationStatus status = topologyTemplateOperation.associateInstPropertiesToComponent(vertex, instPropsMap);
1068 if (StorageOperationStatus.OK == status) {
1069 log.debug("Component created successfully!!!");
1070 return Either.left(instProperties);
1072 return Either.right(status);
1077 * saves the instInputs as the updated instance inputs of the component container in DB
1079 * @param componentId
1082 public Either<Map<String, List<ComponentInstanceInput>>, StorageOperationStatus> updateComponentInstanceInputsToComponent(Map<String, List<ComponentInstanceInput>> instInputs, String componentId) {
1083 if (instInputs == null || instInputs.isEmpty()) {
1084 return Either.left(instInputs);
1086 StorageOperationStatus status;
1087 for ( Entry<String, List<ComponentInstanceInput>> inputsPerIntance : instInputs.entrySet() ) {
1088 List<ComponentInstanceInput> toscaDataListPerInst = inputsPerIntance.getValue();
1089 List<String> pathKeysPerInst = new ArrayList<>();
1090 pathKeysPerInst.add(inputsPerIntance.getKey());
1091 status = topologyTemplateOperation.updateToscaDataDeepElementsOfToscaElement(componentId, EdgeLabelEnum.INST_INPUTS, VertexTypeEnum.INST_INPUTS, toscaDataListPerInst, pathKeysPerInst, JsonPresentationFields.NAME);
1092 if ( status != StorageOperationStatus.OK) {
1093 log.debug("Failed to update component instance inputs for instance {} in component {} edge type {} error {}", inputsPerIntance.getKey(), componentId, EdgeLabelEnum.INST_INPUTS, status);
1094 return Either.right(status);
1098 return Either.left(instInputs);
1102 * saves the instProps as the updated instance properties of the component container in DB
1104 * @param componentId
1107 public Either<Map<String, List<ComponentInstanceProperty>>, StorageOperationStatus> updateComponentInstancePropsToComponent(Map<String, List<ComponentInstanceProperty>> instProps, String componentId) {
1108 if (instProps == null || instProps.isEmpty()) {
1109 return Either.left(instProps);
1111 StorageOperationStatus status;
1112 for ( Entry<String, List<ComponentInstanceProperty>> propsPerIntance : instProps.entrySet() ) {
1113 List<ComponentInstanceProperty> toscaDataListPerInst = propsPerIntance.getValue();
1114 List<String> pathKeysPerInst = new ArrayList<>();
1115 pathKeysPerInst.add(propsPerIntance.getKey());
1116 status = topologyTemplateOperation.updateToscaDataDeepElementsOfToscaElement(componentId, EdgeLabelEnum.INST_PROPERTIES, VertexTypeEnum.INST_PROPERTIES, toscaDataListPerInst, pathKeysPerInst, JsonPresentationFields.NAME);
1117 if ( status != StorageOperationStatus.OK) {
1118 log.debug("Failed to update component instance inputs for instance {} in component {} edge type {} error {}", propsPerIntance.getKey(), componentId, EdgeLabelEnum.INST_PROPERTIES, status);
1119 return Either.right(status);
1123 return Either.left(instProps);
1126 public Either<Map<String, List<ComponentInstanceInput>>, StorageOperationStatus> associateComponentInstanceInputsToComponent(Map<String, List<ComponentInstanceInput>> instInputs, String componentId) {
1128 Either<GraphVertex, TitanOperationStatus> getVertexEither = titanDao.getVertexById(componentId, JsonParseFlagEnum.NoParse);
1129 if (getVertexEither.isRight()) {
1130 log.debug("Couldn't fetch component with and unique id {}, error: {}", componentId, getVertexEither.right().value());
1131 return Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(getVertexEither.right().value()));
1134 GraphVertex vertex = getVertexEither.left().value();
1135 Map<String, MapPropertiesDataDefinition> instPropsMap = new HashMap<>();
1136 if (instInputs != null) {
1138 MapPropertiesDataDefinition propertiesMap;
1139 for (Entry<String, List<ComponentInstanceInput>> entry : instInputs.entrySet()) {
1140 propertiesMap = new MapPropertiesDataDefinition();
1142 propertiesMap.setMapToscaDataDefinition(entry.getValue().stream().map(e -> new PropertyDataDefinition(e)).collect(Collectors.toMap(e -> e.getName(), e -> e)));
1144 instPropsMap.put(entry.getKey(), propertiesMap);
1148 StorageOperationStatus status = topologyTemplateOperation.associateInstInputsToComponent(vertex, instPropsMap);
1150 if (StorageOperationStatus.OK == status) {
1151 log.debug("Component created successfully!!!");
1152 return Either.left(instInputs);
1154 return Either.right(status);
1158 public Either<Map<String, List<ComponentInstanceInput>>, StorageOperationStatus> addComponentInstanceInputsToComponent(Component containerComponent, Map<String, List<ComponentInstanceInput>> instProperties) {
1160 StorageOperationStatus status = StorageOperationStatus.OK;
1161 if (instProperties != null) {
1163 for (Entry<String, List<ComponentInstanceInput>> entry : instProperties.entrySet()) {
1164 List<ComponentInstanceInput> props = entry.getValue();
1165 String componentInstanseId = entry.getKey();
1166 if (props != null && !props.isEmpty()) {
1167 for (ComponentInstanceInput property : props) {
1168 List<ComponentInstanceInput> componentInstancesInputs = containerComponent.getComponentInstancesInputs().get(componentInstanseId);
1169 Optional<ComponentInstanceInput> instanceProperty = componentInstancesInputs.stream().filter(p -> p.getName().equals(property.getName())).findAny();
1170 if (instanceProperty.isPresent()) {
1171 status = updateComponentInstanceInput(containerComponent, componentInstanseId, property);
1173 status = addComponentInstanceInput(containerComponent, componentInstanseId, property);
1175 if (status != StorageOperationStatus.OK) {
1176 log.debug("Failed to update instance input {} for instance {} error {} ", property, componentInstanseId, status);
1177 return Either.right(status);
1179 log.trace("instance input {} for instance {} updated", property, componentInstanseId);
1185 return Either.left(instProperties);
1188 public StorageOperationStatus deleteComponentInstanceInputsToComponent(Map<String, List<ComponentInstanceInput>> instProperties, String componentId) {
1190 Either<GraphVertex, TitanOperationStatus> getVertexEither = titanDao.getVertexById(componentId, JsonParseFlagEnum.NoParse);
1191 if (getVertexEither.isRight()) {
1192 log.debug("Couldn't fetch component with and unique id {}, error: {}", componentId, getVertexEither.right().value());
1193 return DaoStatusConverter.convertTitanStatusToStorageStatus(getVertexEither.right().value());
1197 GraphVertex vertex = getVertexEither.left().value();
1198 Map<String, MapPropertiesDataDefinition> instPropsMap = new HashMap<>();
1199 if (instProperties != null) {
1201 MapPropertiesDataDefinition propertiesMap;
1202 for (Entry<String, List<ComponentInstanceInput>> entry : instProperties.entrySet()) {
1203 propertiesMap = new MapPropertiesDataDefinition();
1205 propertiesMap.setMapToscaDataDefinition(entry.getValue().stream().map(e -> new PropertyDataDefinition(e)).collect(Collectors.toMap(e -> e.getName(), e -> e)));
1207 instPropsMap.put(entry.getKey(), propertiesMap);
1211 return topologyTemplateOperation.deleteInstInputsToComponent(vertex, instPropsMap);
1215 public Either<Map<String, List<ComponentInstanceProperty>>, StorageOperationStatus> addComponentInstancePropertiesToComponent(Component containerComponent, Map<String, List<ComponentInstanceProperty>> instProperties, String componentId) {
1217 if (instProperties != null) {
1219 for (Entry<String, List<ComponentInstanceProperty>> entry : instProperties.entrySet()) {
1220 List<ComponentInstanceProperty> props = entry.getValue();
1221 String componentInstanseId = entry.getKey();
1222 List<ComponentInstanceProperty> instanceProperties = containerComponent.getComponentInstancesProperties().get(componentInstanseId);
1223 if (props != null && !props.isEmpty()) {
1224 for (ComponentInstanceProperty property : props) {
1225 Optional<ComponentInstanceProperty> instanceProperty = instanceProperties.stream().filter(p -> p.getUniqueId().equals(property.getUniqueId())).findAny();
1226 if (instanceProperty.isPresent()) {
1227 updateComponentInstanceProperty(containerComponent, componentInstanseId, property);
1229 addComponentInstanceProperty(containerComponent, componentInstanseId, property);
1237 return Either.left(instProperties);
1241 public StorageOperationStatus associateDeploymentArtifactsToInstances(Map<String, Map<String, ArtifactDefinition>> instDeploymentArtifacts, String componentId, User user) {
1243 Either<GraphVertex, TitanOperationStatus> getVertexEither = titanDao.getVertexById(componentId, JsonParseFlagEnum.NoParse);
1244 if (getVertexEither.isRight()) {
1245 log.debug("Couldn't fetch component with and unique id {}, error: {}", componentId, getVertexEither.right().value());
1246 return DaoStatusConverter.convertTitanStatusToStorageStatus(getVertexEither.right().value());
1250 GraphVertex vertex = getVertexEither.left().value();
1251 Map<String, MapArtifactDataDefinition> instArtMap = new HashMap<>();
1252 if (instDeploymentArtifacts != null) {
1254 MapArtifactDataDefinition artifactsMap;
1255 for (Entry<String, Map<String, ArtifactDefinition>> entry : instDeploymentArtifacts.entrySet()) {
1256 Map<String, ArtifactDefinition> artList = entry.getValue();
1257 Map<String, ArtifactDataDefinition> artifacts = artList.entrySet().stream().collect(Collectors.toMap(Map.Entry::getKey, e -> new ArtifactDataDefinition(e.getValue())));
1258 artifactsMap = nodeTemplateOperation.prepareInstDeploymentArtifactPerInstance(artifacts, entry.getKey(), user, NodeTemplateOperation.HEAT_VF_ENV_NAME);
1260 instArtMap.put(entry.getKey(), artifactsMap);
1264 return topologyTemplateOperation.associateInstDeploymentArtifactsToComponent(vertex, instArtMap);
1268 public StorageOperationStatus associateArtifactsToInstances(Map<String, Map<String, ArtifactDefinition>> instArtifacts, String componentId, User user) {
1270 Either<GraphVertex, TitanOperationStatus> getVertexEither = titanDao.getVertexById(componentId, JsonParseFlagEnum.NoParse);
1271 if (getVertexEither.isRight()) {
1272 log.debug("Couldn't fetch component with and unique id {}, error: {}", componentId, getVertexEither.right().value());
1273 return DaoStatusConverter.convertTitanStatusToStorageStatus(getVertexEither.right().value());
1277 GraphVertex vertex = getVertexEither.left().value();
1278 Map<String, MapArtifactDataDefinition> instArtMap = new HashMap<>();
1279 if (instArtifacts != null) {
1281 MapArtifactDataDefinition artifactsMap;
1282 for (Entry<String, Map<String, ArtifactDefinition>> entry : instArtifacts.entrySet()) {
1283 Map<String, ArtifactDefinition> artList = entry.getValue();
1284 Map<String, ArtifactDataDefinition> artifacts = artList.entrySet().stream().collect(Collectors.toMap(Map.Entry::getKey, e -> new ArtifactDataDefinition(e.getValue())));
1285 artifactsMap = new MapArtifactDataDefinition(artifacts);
1287 instArtMap.put(entry.getKey(), artifactsMap);
1291 return topologyTemplateOperation.associateInstArtifactsToComponent(vertex, instArtMap);
1295 public StorageOperationStatus associateInstAttributeToComponentToInstances(Map<String, List<PropertyDefinition>> instArttributes, String componentId) {
1297 Either<GraphVertex, TitanOperationStatus> getVertexEither = titanDao.getVertexById(componentId, JsonParseFlagEnum.NoParse);
1298 if (getVertexEither.isRight()) {
1299 log.debug("Couldn't fetch component with and unique id {}, error: {}", componentId, getVertexEither.right().value());
1300 return DaoStatusConverter.convertTitanStatusToStorageStatus(getVertexEither.right().value());
1304 GraphVertex vertex = getVertexEither.left().value();
1305 Map<String, MapPropertiesDataDefinition> instAttr = new HashMap<>();
1306 if (instArttributes != null) {
1308 MapPropertiesDataDefinition attributesMap;
1309 for (Entry<String, List<PropertyDefinition>> entry : instArttributes.entrySet()) {
1310 attributesMap = new MapPropertiesDataDefinition();
1311 attributesMap.setMapToscaDataDefinition(entry.getValue().stream().map(e -> new PropertyDataDefinition(e)).collect(Collectors.toMap(e -> e.getName(), e -> e)));
1312 instAttr.put(entry.getKey(), attributesMap);
1316 return topologyTemplateOperation.associateInstAttributeToComponent(vertex, instAttr);
1321 public StorageOperationStatus associateCalculatedCapReq(Map<ComponentInstance, Map<String, List<CapabilityDefinition>>> instCapabilties, Map<ComponentInstance, Map<String, List<RequirementDefinition>>> instReg, String componentId) {
1322 Either<GraphVertex, TitanOperationStatus> getVertexEither = titanDao.getVertexById(componentId, JsonParseFlagEnum.NoParse);
1323 if (getVertexEither.isRight()) {
1324 log.debug("Couldn't fetch component with and unique id {}, error: {}", componentId, getVertexEither.right().value());
1325 return DaoStatusConverter.convertTitanStatusToStorageStatus(getVertexEither.right().value());
1329 GraphVertex vertex = getVertexEither.left().value();
1331 Map<String, MapListRequirementDataDefinition> calcRequirements = new HashMap<>();
1333 Map<String, MapListCapabiltyDataDefinition> calcCapabilty = new HashMap<>();
1334 Map<String, MapCapabiltyProperty> calculatedCapabilitiesProperties = new HashMap<>();
1336 if (instCapabilties != null) {
1337 for (Entry<ComponentInstance, Map<String, List<CapabilityDefinition>>> entry : instCapabilties.entrySet()) {
1339 Map<String, List<CapabilityDefinition>> caps = entry.getValue();
1340 Map<String, ListCapabilityDataDefinition> mapToscaDataDefinition = new HashMap<>();
1341 for (Entry<String, List<CapabilityDefinition>> instCapability : caps.entrySet()) {
1342 mapToscaDataDefinition.put(instCapability.getKey(), new ListCapabilityDataDefinition(instCapability.getValue().stream().map(iCap -> new CapabilityDataDefinition(iCap)).collect(Collectors.toList())));
1345 ComponentInstanceDataDefinition componentInstance = new ComponentInstanceDataDefinition(entry.getKey());
1346 MapListCapabiltyDataDefinition capMap = nodeTemplateOperation.prepareCalculatedCapabiltyForNodeType(mapToscaDataDefinition, componentInstance);
1348 MapCapabiltyProperty mapCapabiltyProperty = ModelConverter.convertToMapOfMapCapabiltyProperties(caps, componentInstance.getUniqueId(), true);
1350 calcCapabilty.put(entry.getKey().getUniqueId(), capMap);
1351 calculatedCapabilitiesProperties.put(entry.getKey().getUniqueId(), mapCapabiltyProperty);
1355 if (instReg != null) {
1356 for (Entry<ComponentInstance, Map<String, List<RequirementDefinition>>> entry : instReg.entrySet()) {
1358 Map<String, List<RequirementDefinition>> req = entry.getValue();
1359 Map<String, ListRequirementDataDefinition> mapToscaDataDefinition = new HashMap<>();
1360 for (Entry<String, List<RequirementDefinition>> instReq : req.entrySet()) {
1361 mapToscaDataDefinition.put(instReq.getKey(), new ListRequirementDataDefinition(instReq.getValue().stream().map(iCap -> new RequirementDataDefinition(iCap)).collect(Collectors.toList())));
1364 MapListRequirementDataDefinition capMap = nodeTemplateOperation.prepareCalculatedRequirementForNodeType(mapToscaDataDefinition, new ComponentInstanceDataDefinition(entry.getKey()));
1366 calcRequirements.put(entry.getKey().getUniqueId(), capMap);
1370 StorageOperationStatus status = topologyTemplateOperation.associateCalcCapReqToComponent(vertex, calcRequirements, calcCapabilty, calculatedCapabilitiesProperties);
1375 private Either<List<Service>, StorageOperationStatus> getLatestVersionNonCheckoutServicesMetadataOnly(Map<GraphPropertyEnum, Object> hasProps, Map<GraphPropertyEnum, Object> hasNotProps) {
1376 List<Service> services = new ArrayList<>();
1377 List<LifecycleStateEnum> states = new ArrayList<>();
1379 hasProps.put(GraphPropertyEnum.COMPONENT_TYPE, ComponentTypeEnum.SERVICE.name());
1380 hasProps.put(GraphPropertyEnum.IS_HIGHEST_VERSION, true);
1383 states.add(LifecycleStateEnum.NOT_CERTIFIED_CHECKOUT);
1384 hasNotProps.put(GraphPropertyEnum.STATE, states);
1385 hasNotProps.put(GraphPropertyEnum.IS_DELETED, true);
1386 return fetchServicesByCriteria(services, hasProps, hasNotProps);
1389 private Either<List<Component>, StorageOperationStatus> getLatestVersionNotAbstractToscaElementsMetadataOnly(boolean isAbstract, Boolean isHighest, ComponentTypeEnum componentTypeEnum, String internalComponentType, VertexTypeEnum vertexType) {
1390 List<Service> services = null;
1391 Map<GraphPropertyEnum, Object> hasProps = new EnumMap<>(GraphPropertyEnum.class);
1392 Map<GraphPropertyEnum, Object> hasNotProps = new EnumMap<>(GraphPropertyEnum.class);
1393 fillPropsMap(hasProps, hasNotProps, internalComponentType, componentTypeEnum, isAbstract, vertexType);
1394 Either<List<GraphVertex>, TitanOperationStatus> getRes = titanDao.getByCriteria(vertexType, hasProps, hasNotProps, JsonParseFlagEnum.ParseMetadata);
1395 if (getRes.isRight()) {
1396 if (getRes.right().value().equals(TitanOperationStatus.NOT_FOUND)) {
1397 return Either.left(new ArrayList<>());
1399 return Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(getRes.right().value()));
1402 // region -> Fetch non checked-out services
1403 if (internalComponentType != null && internalComponentType.toLowerCase().trim().equals("service") && VertexTypeEnum.NODE_TYPE == vertexType) { // and NODE_TYPE==vertextype
1404 Either<List<Service>, StorageOperationStatus> result = getLatestVersionNonCheckoutServicesMetadataOnly(new EnumMap<>(GraphPropertyEnum.class), new EnumMap<>(GraphPropertyEnum.class));
1405 if (result.isRight()) {
1406 log.debug("Failed to fetch services for");
1407 return Either.right(result.right().value());
1409 services = result.left().value();
1410 if (CollectionUtils.isEmpty(services) && log.isTraceEnabled())
1411 log.trace("No relevant services available");
1414 List<Component> nonAbstractLatestComponents = new ArrayList<>();
1415 ComponentParametersView params = new ComponentParametersView(true);
1416 params.setIgnoreAllVersions(false);
1417 for (GraphVertex vertexComponent : getRes.left().value()) {
1418 Either<ToscaElement, StorageOperationStatus> componentRes = topologyTemplateOperation.getLightComponent(vertexComponent, componentTypeEnum, params);
1419 if (componentRes.isRight()) {
1420 log.debug("Failed to fetch ligth element for {} error {}", vertexComponent.getUniqueId(), componentRes.right().value());
1421 return Either.right(componentRes.right().value());
1423 Component component = ModelConverter.convertFromToscaElement(componentRes.left().value());
1424 nonAbstractLatestComponents.add(component);
1427 if (CollectionUtils.isNotEmpty(services))
1428 nonAbstractLatestComponents.addAll(services);
1429 return Either.left(nonAbstractLatestComponents);
1433 public Either<ComponentMetadataData, StorageOperationStatus> getLatestComponentMetadataByUuid(String componentUuid, JsonParseFlagEnum parseFlag, Boolean isHighest) {
1435 Either<ComponentMetadataData, StorageOperationStatus> result;
1437 Map<GraphPropertyEnum, Object> hasProperties = new EnumMap<>(GraphPropertyEnum.class);
1439 hasProperties.put(GraphPropertyEnum.UUID, componentUuid);
1440 if (isHighest != null) {
1441 hasProperties.put(GraphPropertyEnum.IS_HIGHEST_VERSION, isHighest.booleanValue());
1444 Map<GraphPropertyEnum, Object> propertiesNotToMatch = new EnumMap<>(GraphPropertyEnum.class);
1445 propertiesNotToMatch.put(GraphPropertyEnum.IS_DELETED, true);
1447 Either<List<GraphVertex>, TitanOperationStatus> getRes = titanDao.getByCriteria(null, hasProperties, propertiesNotToMatch, parseFlag);
1448 if (getRes.isRight()) {
1449 result = Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(getRes.right().value()));
1451 List<ComponentMetadataData> latestVersionList = getRes.left().value().stream().map(ModelConverter::convertToComponentMetadata).collect(Collectors.toList());
1452 ComponentMetadataData latestVersion = latestVersionList.size() == 1 ? latestVersionList.get(0)
1453 : latestVersionList.stream().max((c1, c2) -> Double.compare(Double.parseDouble(c1.getMetadataDataDefinition().getVersion()), Double.parseDouble(c2.getMetadataDataDefinition().getVersion()))).get();
1454 result = Either.left(latestVersion);
1459 public Either<ComponentMetadataData, StorageOperationStatus> getComponentMetadata(String componentId) {
1461 Either<ComponentMetadataData, StorageOperationStatus> result;
1462 Either<GraphVertex, TitanOperationStatus> getRes = titanDao.getVertexById(componentId, JsonParseFlagEnum.ParseMetadata);
1463 if (getRes.isRight()) {
1464 result = Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(getRes.right().value()));
1466 ComponentMetadataData componentMetadata = ModelConverter.convertToComponentMetadata(getRes.left().value());
1467 result = Either.left(componentMetadata);
1472 public Either<List<Component>, StorageOperationStatus> getLatestVersionNotAbstractComponents(boolean isAbstract, Boolean isHighest, ComponentTypeEnum componentTypeEnum, String internalComponentType, List<String> componentUids) {
1474 Either<List<Component>, StorageOperationStatus> result = null;
1475 List<Component> components = new ArrayList<>();
1476 if (componentUids == null) {
1477 Either<List<String>, StorageOperationStatus> componentUidsRes = getComponentUids(isAbstract, isHighest, componentTypeEnum, internalComponentType, componentUids);
1478 if (componentUidsRes.isRight()) {
1479 result = Either.right(componentUidsRes.right().value());
1481 componentUids = componentUidsRes.left().value();
1484 if (!componentUids.isEmpty()) {
1485 for (String componentUid : componentUids) {
1486 ComponentParametersView componentParametersView = buildComponentViewForNotAbstract();
1487 if (internalComponentType != null && "vl".equalsIgnoreCase(internalComponentType)) {
1488 componentParametersView.setIgnoreCapabilities(false);
1489 componentParametersView.setIgnoreRequirements(false);
1491 Either<ToscaElement, StorageOperationStatus> getToscaElementRes = nodeTemplateOperation.getToscaElementOperation(componentTypeEnum).getLightComponent(componentUid, componentTypeEnum, componentParametersView);
1492 if (getToscaElementRes.isRight()) {
1493 if (log.isDebugEnabled())
1494 log.debug("Failed to fetch resource for error is {}", getToscaElementRes.right().value());
1495 result = Either.right(getToscaElementRes.right().value());
1498 Component component = ModelConverter.convertFromToscaElement(getToscaElementRes.left().value());
1499 component.setContactId(null);
1500 component.setCreationDate(null);
1501 component.setCreatorUserId(null);
1502 component.setCreatorFullName(null);
1503 component.setLastUpdateDate(null);
1504 component.setLastUpdaterUserId(null);
1505 component.setLastUpdaterFullName(null);
1506 component.setNormalizedName(null);
1507 components.add(component);
1510 if (result == null) {
1511 result = Either.left(components);
1516 private Either<List<String>, StorageOperationStatus> getComponentUids(boolean isAbstract, Boolean isHighest, ComponentTypeEnum componentTypeEnum, String internalComponentType, List<String> componentUids) {
1518 Either<List<String>, StorageOperationStatus> result = null;
1519 Either<List<Component>, StorageOperationStatus> getToscaElementsRes = getLatestVersionNotAbstractMetadataOnly(isAbstract, isHighest, componentTypeEnum, internalComponentType);
1520 if (getToscaElementsRes.isRight()) {
1521 result = Either.right(getToscaElementsRes.right().value());
1523 List<Component> collection = getToscaElementsRes.left().value();
1524 if (collection == null) {
1525 componentUids = new ArrayList<>();
1527 componentUids = collection.stream().map(p -> p.getUniqueId()).collect(Collectors.toList());
1530 if (result == null) {
1531 result = Either.left(componentUids);
1536 private ComponentParametersView buildComponentViewForNotAbstract() {
1537 ComponentParametersView componentParametersView = new ComponentParametersView();
1538 componentParametersView.disableAll();
1539 componentParametersView.setIgnoreCategories(false);
1540 componentParametersView.setIgnoreAllVersions(false);
1541 return componentParametersView;
1544 public Either<Boolean, StorageOperationStatus> validateComponentNameExists(String name, ResourceTypeEnum resourceType, ComponentTypeEnum componentType) {
1545 Either<Boolean, StorageOperationStatus> result = validateComponentNameUniqueness(name, resourceType, componentType);
1546 if (result.isLeft()) {
1547 result = Either.left(!result.left().value());
1552 public Either<Boolean, StorageOperationStatus> validateComponentNameUniqueness(String name, ResourceTypeEnum resourceType, ComponentTypeEnum componentType) {
1553 VertexTypeEnum vertexType = ModelConverter.isAtomicComponent(resourceType) ? VertexTypeEnum.NODE_TYPE : VertexTypeEnum.TOPOLOGY_TEMPLATE;
1554 String normalizedName = ValidationUtils.normaliseComponentName(name);
1555 Map<GraphPropertyEnum, Object> properties = new EnumMap<>(GraphPropertyEnum.class);
1556 properties.put(GraphPropertyEnum.NORMALIZED_NAME, normalizedName);
1557 properties.put(GraphPropertyEnum.COMPONENT_TYPE, componentType.name());
1559 Either<List<GraphVertex>, TitanOperationStatus> vertexEither = titanDao.getByCriteria(vertexType, properties, JsonParseFlagEnum.NoParse);
1560 if (vertexEither.isRight() && vertexEither.right().value() != TitanOperationStatus.NOT_FOUND) {
1561 log.debug("failed to get vertex from graph with property normalizedName: {}", normalizedName);
1562 return Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(vertexEither.right().value()));
1564 List<GraphVertex> vertexList = vertexEither.isLeft() ? vertexEither.left().value() : null;
1565 if (vertexList != null && !vertexList.isEmpty()) {
1566 return Either.left(false);
1568 return Either.left(true);
1572 private void fillNodeTypePropsMap(Map<GraphPropertyEnum, Object> hasProps, Map<GraphPropertyEnum, Object> hasNotProps, String internalComponentType) {
1573 switch (internalComponentType.toLowerCase()) {
1576 hasNotProps.put(GraphPropertyEnum.RESOURCE_TYPE, Arrays.asList(ResourceTypeEnum.VFCMT.name(), ResourceTypeEnum.Configuration.name()));
1581 hasNotProps.put(GraphPropertyEnum.RESOURCE_TYPE, Arrays.asList(ResourceTypeEnum.VFC.name(), ResourceTypeEnum.VFCMT.name()));
1584 hasProps.put(GraphPropertyEnum.RESOURCE_TYPE, ResourceTypeEnum.VL.name());
1591 private void fillTopologyTemplatePropsMap(Map<GraphPropertyEnum, Object> hasProps, Map<GraphPropertyEnum, Object> hasNotProps, ComponentTypeEnum componentTypeEnum, String internalComponentType) {
1592 switch (componentTypeEnum) {
1594 hasProps.put(GraphPropertyEnum.COMPONENT_TYPE, ComponentTypeEnum.RESOURCE.name());
1597 hasProps.put(GraphPropertyEnum.COMPONENT_TYPE, ComponentTypeEnum.SERVICE.name());
1602 switch (internalComponentType.toLowerCase()) {
1605 hasProps.put(GraphPropertyEnum.RESOURCE_TYPE, ResourceTypeEnum.CVFC.name());
1608 hasNotProps.put(GraphPropertyEnum.RESOURCE_TYPE, ResourceTypeEnum.CVFC.name());
1615 private void fillPropsMap(Map<GraphPropertyEnum, Object> hasProps, Map<GraphPropertyEnum, Object> hasNotProps, String internalComponentType, ComponentTypeEnum componentTypeEnum, boolean isAbstract, VertexTypeEnum internalVertexType) {
1616 hasNotProps.put(GraphPropertyEnum.STATE, LifecycleStateEnum.NOT_CERTIFIED_CHECKOUT.name());
1618 hasNotProps.put(GraphPropertyEnum.IS_DELETED, true);
1619 hasProps.put(GraphPropertyEnum.IS_HIGHEST_VERSION, true);
1620 if (VertexTypeEnum.NODE_TYPE == internalVertexType) {
1621 hasProps.put(GraphPropertyEnum.IS_ABSTRACT, isAbstract);
1622 if (internalComponentType != null) {
1623 fillNodeTypePropsMap(hasProps, hasNotProps, internalComponentType);
1626 fillTopologyTemplatePropsMap(hasProps, hasNotProps, componentTypeEnum, internalComponentType);
1630 private List<VertexTypeEnum> getInternalVertexTypes(ComponentTypeEnum componentTypeEnum, String internalComponentType) {
1631 List<VertexTypeEnum> internalVertexTypes = new ArrayList<>();
1632 if (ComponentTypeEnum.RESOURCE == componentTypeEnum) {
1633 internalVertexTypes.add(VertexTypeEnum.NODE_TYPE);
1635 if (ComponentTypeEnum.SERVICE == componentTypeEnum || "service".equalsIgnoreCase(internalComponentType) || "vf".equalsIgnoreCase(internalComponentType)) {
1636 internalVertexTypes.add(VertexTypeEnum.TOPOLOGY_TEMPLATE);
1638 return internalVertexTypes;
1641 public Either<List<Component>, StorageOperationStatus> getLatestVersionNotAbstractMetadataOnly(boolean isAbstract, Boolean isHighest, ComponentTypeEnum componentTypeEnum, String internalComponentType) {
1642 List<VertexTypeEnum> internalVertexTypes = getInternalVertexTypes(componentTypeEnum, internalComponentType);
1643 List<Component> result = new ArrayList<>();
1644 for (VertexTypeEnum vertexType : internalVertexTypes) {
1645 Either<List<Component>, StorageOperationStatus> listByVertexType = getLatestVersionNotAbstractToscaElementsMetadataOnly(isAbstract, isHighest, componentTypeEnum, internalComponentType, vertexType);
1646 if (listByVertexType.isRight()) {
1647 return listByVertexType;
1649 result.addAll(listByVertexType.left().value());
1651 return Either.left(result);
1655 private Either<List<Component>, StorageOperationStatus> getLatestComponentListByUuid(String componentUuid, Map<GraphPropertyEnum, Object> additionalPropertiesToMatch) {
1656 Map<GraphPropertyEnum, Object> propertiesToMatch = new EnumMap<>(GraphPropertyEnum.class);
1657 if (additionalPropertiesToMatch != null) {
1658 propertiesToMatch.putAll(additionalPropertiesToMatch);
1660 propertiesToMatch.put(GraphPropertyEnum.IS_HIGHEST_VERSION, true);
1661 Either<List<Component>, StorageOperationStatus> componentListByUuid = getComponentListByUuid(componentUuid, propertiesToMatch);
1662 return componentListByUuid;
1665 public Either<Component, StorageOperationStatus> getComponentByUuidAndVersion(String componentUuid, String version) {
1666 Map<GraphPropertyEnum, Object> propertiesToMatch = new EnumMap<>(GraphPropertyEnum.class);
1668 propertiesToMatch.put(GraphPropertyEnum.UUID, componentUuid);
1669 propertiesToMatch.put(GraphPropertyEnum.VERSION, version);
1671 Map<GraphPropertyEnum, Object> propertiesNotToMatch = new EnumMap<>(GraphPropertyEnum.class);
1672 propertiesNotToMatch.put(GraphPropertyEnum.IS_DELETED, true);
1673 Either<List<GraphVertex>, TitanOperationStatus> vertexEither = titanDao.getByCriteria(null, propertiesToMatch, propertiesNotToMatch, JsonParseFlagEnum.ParseAll);
1674 if (vertexEither.isRight()) {
1675 return Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(vertexEither.right().value()));
1678 List<GraphVertex> vertexList = vertexEither.isLeft() ? vertexEither.left().value() : null;
1679 if (vertexList == null || vertexList.isEmpty() || vertexList.size() > 1) {
1680 return Either.right(StorageOperationStatus.NOT_FOUND);
1683 return getToscaElementByOperation(vertexList.get(0));
1686 public Either<List<Component>, StorageOperationStatus> getComponentListByUuid(String componentUuid, Map<GraphPropertyEnum, Object> additionalPropertiesToMatch) {
1688 Map<GraphPropertyEnum, Object> propertiesToMatch = new EnumMap<>(GraphPropertyEnum.class);
1690 if (additionalPropertiesToMatch != null) {
1691 propertiesToMatch.putAll(additionalPropertiesToMatch);
1694 propertiesToMatch.put(GraphPropertyEnum.UUID, componentUuid);
1696 Map<GraphPropertyEnum, Object> propertiesNotToMatch = new EnumMap<>(GraphPropertyEnum.class);
1697 propertiesNotToMatch.put(GraphPropertyEnum.IS_DELETED, true);
1699 Either<List<GraphVertex>, TitanOperationStatus> vertexEither = titanDao.getByCriteria(null, propertiesToMatch, propertiesNotToMatch, JsonParseFlagEnum.ParseAll);
1701 if (vertexEither.isRight()) {
1702 log.debug("Couldn't fetch metadata for component with type {} and uuid {}, error: {}", componentUuid, vertexEither.right().value());
1703 return Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(vertexEither.right().value()));
1705 List<GraphVertex> vertexList = vertexEither.isLeft() ? vertexEither.left().value() : null;
1707 if (vertexList == null || vertexList.isEmpty()) {
1708 log.debug("Component with uuid {} was not found", componentUuid);
1709 return Either.right(StorageOperationStatus.NOT_FOUND);
1712 ArrayList<Component> latestComponents = new ArrayList<>();
1713 for (GraphVertex vertex : vertexList) {
1714 Either<Component, StorageOperationStatus> toscaElementByOperation = getToscaElementByOperation(vertex);
1716 if (toscaElementByOperation.isRight()) {
1717 log.debug("Could not fetch the following Component by UUID {}", vertex.getUniqueId());
1718 return Either.right(toscaElementByOperation.right().value());
1721 latestComponents.add(toscaElementByOperation.left().value());
1724 if (latestComponents.size() > 1) {
1725 for (Component component : latestComponents) {
1726 if (component.isHighestVersion()) {
1727 LinkedList<Component> highestComponent = new LinkedList<>();
1728 highestComponent.add(component);
1729 return Either.left(highestComponent);
1734 return Either.left(latestComponents);
1737 public Either<Component, StorageOperationStatus> getLatestServiceByUuid(String serviceUuid) {
1738 Map<GraphPropertyEnum, Object> propertiesToMatch = new HashMap<>();
1739 propertiesToMatch.put(GraphPropertyEnum.COMPONENT_TYPE, ComponentTypeEnum.SERVICE.name());
1740 return getLatestComponentByUuid(serviceUuid, propertiesToMatch);
1743 public Either<Component, StorageOperationStatus> getLatestComponentByUuid(String componentUuid) {
1744 return getLatestComponentByUuid(componentUuid, null);
1747 public Either<Component, StorageOperationStatus> getLatestComponentByUuid(String componentUuid, Map<GraphPropertyEnum, Object> propertiesToMatch) {
1749 Either<List<Component>, StorageOperationStatus> latestVersionListEither = getLatestComponentListByUuid(componentUuid, propertiesToMatch);
1751 if (latestVersionListEither.isRight()) {
1752 return Either.right(latestVersionListEither.right().value());
1755 List<Component> latestVersionList = latestVersionListEither.left().value();
1757 if (latestVersionList.isEmpty()) {
1758 return Either.right(StorageOperationStatus.NOT_FOUND);
1760 Component component = latestVersionList.size() == 1 ? latestVersionList.get(0) : latestVersionList.stream().max((c1, c2) -> Double.compare(Double.parseDouble(c1.getVersion()), Double.parseDouble(c2.getVersion()))).get();
1762 return Either.left(component);
1765 public Either<List<Resource>, StorageOperationStatus> getAllCertifiedResources(boolean isAbstract, Boolean isHighest) {
1767 List<Resource> resources = new ArrayList<>();
1768 Map<GraphPropertyEnum, Object> propertiesToMatch = new EnumMap<>(GraphPropertyEnum.class);
1769 Map<GraphPropertyEnum, Object> propertiesNotToMatch = new EnumMap<>(GraphPropertyEnum.class);
1771 propertiesToMatch.put(GraphPropertyEnum.IS_ABSTRACT, isAbstract);
1772 if (isHighest != null) {
1773 propertiesToMatch.put(GraphPropertyEnum.IS_HIGHEST_VERSION, isHighest.booleanValue());
1775 propertiesToMatch.put(GraphPropertyEnum.STATE, LifecycleStateEnum.CERTIFIED.name());
1776 propertiesToMatch.put(GraphPropertyEnum.COMPONENT_TYPE, ComponentTypeEnum.RESOURCE.name());
1777 propertiesNotToMatch.put(GraphPropertyEnum.IS_DELETED, true);
1779 Either<List<GraphVertex>, TitanOperationStatus> getResourcesRes = titanDao.getByCriteria(null, propertiesToMatch, propertiesNotToMatch, JsonParseFlagEnum.ParseAll);
1781 if (getResourcesRes.isRight()) {
1782 log.debug("Failed to fetch all certified resources. Status is {}", getResourcesRes.right().value());
1783 return Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(getResourcesRes.right().value()));
1785 List<GraphVertex> resourceVerticies = getResourcesRes.left().value();
1786 for (GraphVertex resourceV : resourceVerticies) {
1787 Either<Resource, StorageOperationStatus> getResourceRes = getToscaElement(resourceV);
1788 if (getResourceRes.isRight()) {
1789 return Either.right(getResourceRes.right().value());
1791 resources.add(getResourceRes.left().value());
1793 return Either.left(resources);
1796 public <T extends Component> Either<T, StorageOperationStatus> getLatestByNameAndVersion(String name, String version, JsonParseFlagEnum parseFlag) {
1797 Either<T, StorageOperationStatus> result;
1799 Map<GraphPropertyEnum, Object> hasProperties = new EnumMap<>(GraphPropertyEnum.class);
1800 Map<GraphPropertyEnum, Object> hasNotProperties = new EnumMap<>(GraphPropertyEnum.class);
1802 hasProperties.put(GraphPropertyEnum.NAME, name);
1803 hasProperties.put(GraphPropertyEnum.VERSION, version);
1804 hasProperties.put(GraphPropertyEnum.IS_HIGHEST_VERSION, true);
1806 hasNotProperties.put(GraphPropertyEnum.IS_DELETED, true);
1808 Either<List<GraphVertex>, TitanOperationStatus> getResourceRes = titanDao.getByCriteria(null, hasProperties, hasNotProperties, parseFlag);
1809 if (getResourceRes.isRight()) {
1810 TitanOperationStatus status = getResourceRes.right().value();
1811 log.debug("failed to find resource with name {}, version {}. Status is {} ", name, version, status);
1812 result = Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(status));
1815 return getToscaElementByOperation(getResourceRes.left().value().get(0));
1818 public Either<Resource, StorageOperationStatus> getLatestComponentByCsarOrName(ComponentTypeEnum componentType, String csarUUID, String systemName) {
1819 return getLatestComponentByCsarOrName(componentType, csarUUID, systemName, false, JsonParseFlagEnum.ParseAll);
1822 public Either<Resource, StorageOperationStatus> getLatestComponentByCsarOrName(ComponentTypeEnum componentType, String csarUUID, String systemName, boolean allowDeleted, JsonParseFlagEnum parseFlag) {
1823 Map<GraphPropertyEnum, Object> props = new EnumMap<>(GraphPropertyEnum.class);
1824 props.put(GraphPropertyEnum.CSAR_UUID, csarUUID);
1825 props.put(GraphPropertyEnum.IS_HIGHEST_VERSION, true);
1826 if (componentType != null) {
1827 props.put(GraphPropertyEnum.COMPONENT_TYPE, componentType.name());
1829 Map<GraphPropertyEnum, Object> propsHasNot = new EnumMap<>(GraphPropertyEnum.class);
1830 propsHasNot.put(GraphPropertyEnum.IS_DELETED, true);
1832 GraphVertex resourceMetadataData = null;
1833 List<GraphVertex> resourceMetadataDataList = null;
1834 Either<List<GraphVertex>, TitanOperationStatus> byCsar = titanDao.getByCriteria(null, props, propsHasNot, JsonParseFlagEnum.ParseMetadata);
1835 if (byCsar.isRight()) {
1836 if (TitanOperationStatus.NOT_FOUND == byCsar.right().value()) {
1837 // Fix Defect DE256036
1838 if (StringUtils.isEmpty(systemName)) {
1839 return Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(TitanOperationStatus.NOT_FOUND));
1843 props.put(GraphPropertyEnum.IS_HIGHEST_VERSION, true);
1844 props.put(GraphPropertyEnum.SYSTEM_NAME, systemName);
1845 Either<List<GraphVertex>, TitanOperationStatus> bySystemname = titanDao.getByCriteria(null, props, JsonParseFlagEnum.ParseMetadata);
1846 if (bySystemname.isRight()) {
1847 log.debug("getLatestResourceByCsarOrName - Failed to find by system name {} error {} ", systemName, bySystemname.right().value());
1848 return Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(bySystemname.right().value()));
1850 if (bySystemname.left().value().size() > 2) {
1851 log.debug("getLatestResourceByCsarOrName - getByCriteria(by system name) must return only 2 latest version, but was returned - {}", bySystemname.left().value().size());
1852 return Either.right(StorageOperationStatus.GENERAL_ERROR);
1854 resourceMetadataDataList = bySystemname.left().value();
1855 if (resourceMetadataDataList.size() == 1) {
1856 resourceMetadataData = resourceMetadataDataList.get(0);
1858 for (GraphVertex curResource : resourceMetadataDataList) {
1859 if (!((String) curResource.getJsonMetadataField(JsonPresentationFields.LIFECYCLE_STATE)).equals("CERTIFIED")) {
1860 resourceMetadataData = curResource;
1865 if (resourceMetadataData == null) {
1866 log.debug("getLatestResourceByCsarOrName - getByCriteria(by system name) returned 2 latest CERTIFIED versions");
1867 return Either.right(StorageOperationStatus.GENERAL_ERROR);
1869 if (resourceMetadataData.getJsonMetadataField(JsonPresentationFields.CSAR_UUID) != null && !((String) resourceMetadataData.getJsonMetadataField(JsonPresentationFields.CSAR_UUID)).equals(csarUUID)) {
1870 log.debug("getLatestResourceByCsarOrName - same system name {} but different csarUUID. exist {} and new {} ", systemName, resourceMetadataData.getJsonMetadataField(JsonPresentationFields.CSAR_UUID), csarUUID);
1871 // correct error will be returned from create flow. with all
1872 // correct audit records!!!!!
1873 return Either.right(StorageOperationStatus.NOT_FOUND);
1875 Either<Resource, StorageOperationStatus> resource = getToscaElement((String) resourceMetadataData.getUniqueId());
1879 resourceMetadataDataList = byCsar.left().value();
1880 if (resourceMetadataDataList.size() > 2) {
1881 log.debug("getLatestResourceByCsarOrName - getByCriteria(by csar) must return only 2 latest version, but was returned - {}", byCsar.left().value().size());
1882 return Either.right(StorageOperationStatus.GENERAL_ERROR);
1884 if (resourceMetadataDataList.size() == 1) {
1885 resourceMetadataData = resourceMetadataDataList.get(0);
1887 for (GraphVertex curResource : resourceMetadataDataList) {
1888 if (!((String) curResource.getJsonMetadataField(JsonPresentationFields.LIFECYCLE_STATE)).equals("CERTIFIED")) {
1889 resourceMetadataData = curResource;
1894 if (resourceMetadataData == null) {
1895 log.debug("getLatestResourceByCsarOrName - getByCriteria(by csar) returned 2 latest CERTIFIED versions");
1896 return Either.right(StorageOperationStatus.GENERAL_ERROR);
1898 Either<Resource, StorageOperationStatus> resource = getToscaElement((String) resourceMetadataData.getJsonMetadataField(JsonPresentationFields.UNIQUE_ID), parseFlag);
1904 public Either<Boolean, StorageOperationStatus> validateToscaResourceNameExtends(String templateNameCurrent, String templateNameExtends) {
1906 String currentTemplateNameChecked = templateNameExtends;
1908 while (currentTemplateNameChecked != null && !currentTemplateNameChecked.equalsIgnoreCase(templateNameCurrent)) {
1909 Either<Resource, StorageOperationStatus> latestByToscaResourceName = getLatestByToscaResourceName(currentTemplateNameChecked);
1911 if (latestByToscaResourceName.isRight()) {
1912 return latestByToscaResourceName.right().value() == StorageOperationStatus.NOT_FOUND ? Either.left(false) : Either.right(latestByToscaResourceName.right().value());
1915 Resource value = latestByToscaResourceName.left().value();
1917 if (value.getDerivedFrom() != null) {
1918 currentTemplateNameChecked = value.getDerivedFrom().get(0);
1920 currentTemplateNameChecked = null;
1924 return (currentTemplateNameChecked != null && currentTemplateNameChecked.equalsIgnoreCase(templateNameCurrent)) ? Either.left(true) : Either.left(false);
1927 public Either<List<Component>, StorageOperationStatus> fetchMetaDataByResourceType(String resourceType, ComponentParametersView filterBy) {
1928 Map<GraphPropertyEnum, Object> props = new EnumMap<>(GraphPropertyEnum.class);
1929 props.put(GraphPropertyEnum.RESOURCE_TYPE, resourceType);
1930 props.put(GraphPropertyEnum.IS_HIGHEST_VERSION, true);
1931 Map<GraphPropertyEnum, Object> propsHasNotToMatch = new HashMap<>();
1932 propsHasNotToMatch.put(GraphPropertyEnum.IS_DELETED, true);
1933 Either<List<GraphVertex>, TitanOperationStatus> resourcesByTypeEither = titanDao.getByCriteria(null, props, propsHasNotToMatch, JsonParseFlagEnum.ParseMetadata);
1935 if (resourcesByTypeEither.isRight()) {
1936 return Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(resourcesByTypeEither.right().value()));
1939 List<GraphVertex> vertexList = resourcesByTypeEither.left().value();
1940 List<Component> components = new ArrayList<>();
1942 for (GraphVertex vertex : vertexList) {
1943 components.add(getToscaElementByOperation(vertex, filterBy).left().value());
1946 return Either.left(components);
1949 public void commit() {
1953 public Either<Service, StorageOperationStatus> updateDistributionStatus(Service service, User user, DistributionStatusEnum distributionStatus) {
1954 Either<GraphVertex, StorageOperationStatus> updateDistributionStatus = topologyTemplateOperation.updateDistributionStatus(service.getUniqueId(), user, distributionStatus);
1955 if (updateDistributionStatus.isRight()) {
1956 return Either.right(updateDistributionStatus.right().value());
1958 GraphVertex serviceV = updateDistributionStatus.left().value();
1959 service.setDistributionStatus(distributionStatus);
1960 service.setLastUpdateDate((Long) serviceV.getJsonMetadataField(JsonPresentationFields.LAST_UPDATE_DATE));
1961 return Either.left(service);
1964 public Either<ComponentMetadataData, StorageOperationStatus> updateComponentLastUpdateDateOnGraph(Component component, Long modificationTime) {
1966 Either<ComponentMetadataData, StorageOperationStatus> result = null;
1967 GraphVertex serviceVertex;
1968 Either<GraphVertex, TitanOperationStatus> updateRes = null;
1969 Either<GraphVertex, TitanOperationStatus> getRes = titanDao.getVertexById(component.getUniqueId(), JsonParseFlagEnum.ParseMetadata);
1970 if (getRes.isRight()) {
1971 TitanOperationStatus status = getRes.right().value();
1972 log.error("Failed to fetch component {}. status is {}", component.getUniqueId(), status);
1973 result = Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(status));
1975 if (result == null) {
1976 serviceVertex = getRes.left().value();
1977 long lastUpdateDate = System.currentTimeMillis();
1978 serviceVertex.setJsonMetadataField(JsonPresentationFields.LAST_UPDATE_DATE, lastUpdateDate);
1979 component.setLastUpdateDate(lastUpdateDate);
1980 updateRes = titanDao.updateVertex(serviceVertex);
1981 if (updateRes.isRight()) {
1982 result = Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(updateRes.right().value()));
1985 if (result == null) {
1986 result = Either.left(ModelConverter.convertToComponentMetadata(updateRes.left().value()));
1991 public TitanDao getTitanDao() {
1995 public Either<List<Service>, StorageOperationStatus> getCertifiedServicesWithDistStatus(Set<DistributionStatusEnum> distStatus) {
1996 Map<GraphPropertyEnum, Object> propertiesToMatch = new EnumMap<>(GraphPropertyEnum.class);
1997 propertiesToMatch.put(GraphPropertyEnum.STATE, LifecycleStateEnum.CERTIFIED.name());
1999 return getServicesWithDistStatus(distStatus, propertiesToMatch);
2002 public Either<List<Service>, StorageOperationStatus> getServicesWithDistStatus(Set<DistributionStatusEnum> distStatus, Map<GraphPropertyEnum, Object> additionalPropertiesToMatch) {
2004 List<Service> servicesAll = new ArrayList<>();
2006 Map<GraphPropertyEnum, Object> propertiesToMatch = new EnumMap<>(GraphPropertyEnum.class);
2007 Map<GraphPropertyEnum, Object> propertiesNotToMatch = new EnumMap<>(GraphPropertyEnum.class);
2009 if (additionalPropertiesToMatch != null && !additionalPropertiesToMatch.isEmpty()) {
2010 propertiesToMatch.putAll(additionalPropertiesToMatch);
2013 propertiesToMatch.put(GraphPropertyEnum.COMPONENT_TYPE, ComponentTypeEnum.SERVICE.name());
2015 propertiesNotToMatch.put(GraphPropertyEnum.IS_DELETED, true);
2017 if (distStatus != null && !distStatus.isEmpty()) {
2018 for (DistributionStatusEnum state : distStatus) {
2019 propertiesToMatch.put(GraphPropertyEnum.DISTRIBUTION_STATUS, state.name());
2020 Either<List<Service>, StorageOperationStatus> fetchServicesByCriteria = fetchServicesByCriteria(servicesAll, propertiesToMatch, propertiesNotToMatch);
2021 if (fetchServicesByCriteria.isRight()) {
2022 return fetchServicesByCriteria;
2024 servicesAll = fetchServicesByCriteria.left().value();
2027 return Either.left(servicesAll);
2029 return fetchServicesByCriteria(servicesAll, propertiesToMatch, propertiesNotToMatch);
2033 // private Either<List<Service>, StorageOperationStatus> fetchServicesByCriteria(List<Service> servicesAll, Map<GraphPropertyEnum, Object> propertiesToMatch, Map<GraphPropertyEnum, Object> propertiesNotToMatch) {
2034 // Either<List<GraphVertex>, TitanOperationStatus> getRes = titanDao.getByCriteria(VertexTypeEnum.TOPOLOGY_TEMPLATE, propertiesToMatch, propertiesNotToMatch, JsonParseFlagEnum.ParseAll);
2035 // if (getRes.isRight()) {
2036 // if (getRes.right().value() != TitanOperationStatus.NOT_FOUND) {
2037 // CommonUtility.addRecordToLog(log, LogLevelEnum.DEBUG, "Failed to fetch certified services by match properties {} not match properties {} . Status is {}. ", propertiesToMatch, propertiesNotToMatch, getRes.right().value());
2038 // return Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(getRes.right().value()));
2041 // for (GraphVertex vertex : getRes.left().value()) {
2042 // Either<Component, StorageOperationStatus> getServiceRes = getToscaElementByOperation(vertex);
2043 // if (getServiceRes.isRight()) {
2044 // CommonUtility.addRecordToLog(log, LogLevelEnum.DEBUG, "Failed to fetch certified service {}. Status is {}. ", vertex.getJsonMetadataField(JsonPresentationFields.NAME), getServiceRes.right().value());
2045 // return Either.right(getServiceRes.right().value());
2047 // servicesAll.add((Service) getToscaElementByOperation(vertex).left().value());
2051 // return Either.left(servicesAll);
2054 private Either<List<Service>, StorageOperationStatus> fetchServicesByCriteria(List<Service> servicesAll, Map<GraphPropertyEnum, Object> propertiesToMatch, Map<GraphPropertyEnum, Object> propertiesNotToMatch) {
2055 Either<List<GraphVertex>, TitanOperationStatus> getRes = titanDao.getByCriteria(VertexTypeEnum.TOPOLOGY_TEMPLATE, propertiesToMatch, propertiesNotToMatch, JsonParseFlagEnum.ParseAll);
2056 if (getRes.isRight()) {
2057 if (getRes.right().value() != TitanOperationStatus.NOT_FOUND) {
2058 CommonUtility.addRecordToLog(log, LogLevelEnum.DEBUG, "Failed to fetch certified services by match properties {} not match properties {} . Status is {}. ", propertiesToMatch, propertiesNotToMatch, getRes.right().value());
2059 return Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(getRes.right().value()));
2062 for (GraphVertex vertex : getRes.left().value()) {
2063 // Either<Component, StorageOperationStatus> getServiceRes = getToscaElementByOperation(vertex);
2064 Either<ToscaElement, StorageOperationStatus> getServiceRes = topologyTemplateOperation.getLightComponent(vertex, ComponentTypeEnum.SERVICE, new ComponentParametersView(true));
2066 if (getServiceRes.isRight()) {
2067 CommonUtility.addRecordToLog(log, LogLevelEnum.DEBUG, "Failed to fetch certified service {}. Status is {}. ", vertex.getJsonMetadataField(JsonPresentationFields.NAME), getServiceRes.right().value());
2068 return Either.right(getServiceRes.right().value());
2070 servicesAll.add(ModelConverter.convertFromToscaElement(getServiceRes.left().value()));
2074 return Either.left(servicesAll);
2077 public void rollback() {
2078 titanDao.rollback();
2081 public StorageOperationStatus addDeploymentArtifactsToInstance(String componentId, ComponentInstance componentInstance, Map<String, ArtifactDefinition> finalDeploymentArtifacts) {
2082 Map<String, ArtifactDataDefinition> instDeplArtifacts = finalDeploymentArtifacts.entrySet().stream().collect(Collectors.toMap(Map.Entry::getKey, e -> new ArtifactDataDefinition(e.getValue())));
2084 return nodeTemplateOperation.addDeploymentArtifactsToInstance(componentId, componentInstance.getUniqueId(), instDeplArtifacts);
2087 public StorageOperationStatus addInformationalArtifactsToInstance(String componentId, ComponentInstance componentInstance, Map<String, ArtifactDefinition> artifacts) {
2088 StorageOperationStatus status = StorageOperationStatus.OK;
2089 if (MapUtils.isNotEmpty(artifacts)) {
2090 Map<String, ArtifactDataDefinition> instDeplArtifacts = artifacts.entrySet().stream().collect(Collectors.toMap(Map.Entry::getKey, e -> new ArtifactDataDefinition(e.getValue())));
2091 status = nodeTemplateOperation.addInformationalArtifactsToInstance(componentId, componentInstance.getUniqueId(), instDeplArtifacts);
2096 public StorageOperationStatus generateCustomizationUUIDOnInstance(String componentId, String instanceId) {
2097 return nodeTemplateOperation.generateCustomizationUUIDOnInstance(componentId, instanceId);
2100 public StorageOperationStatus generateCustomizationUUIDOnInstanceGroup(String componentId, String instanceId, List<String> groupInstances) {
2101 return nodeTemplateOperation.generateCustomizationUUIDOnInstanceGroup(componentId, instanceId, groupInstances);
2105 * adds property to a resource
2106 * @warn this method has SIDE EFFECT on ownerId ,use it with caution
2108 public Either<PropertyDefinition, StorageOperationStatus> addPropertyToResource(String propertyName, PropertyDefinition newPropertyDefinition, Resource resource) {
2110 Either<PropertyDefinition, StorageOperationStatus> result = null;
2111 Either<Component, StorageOperationStatus> getUpdatedComponentRes = null;
2112 newPropertyDefinition.setName(propertyName);
2113 // newPropertyDefinition.setParentUniqueId(resource.getUniqueId()); //todo- DELETE me after 10.18, ownerId==null => current resource is the owner. ownerId should be null since coming for the servlet => changing self resource property, assigning a null value actually means that the property has no assigned owner ,therfor current resource is the owner
2114 StorageOperationStatus status = getToscaElementOperation(resource).addToscaDataToToscaElement(resource.getUniqueId(), EdgeLabelEnum.PROPERTIES, VertexTypeEnum.PROPERTIES, newPropertyDefinition, JsonPresentationFields.NAME);
2115 if (status != StorageOperationStatus.OK) {
2116 CommonUtility.addRecordToLog(log, LogLevelEnum.DEBUG, "Failed to add the property {} to the resource {}. Status is {}. ", propertyName, resource.getName(), status);
2117 result = Either.right(status);
2119 if (result == null) {
2120 ComponentParametersView filter = new ComponentParametersView(true);
2121 filter.setIgnoreProperties(false);
2122 getUpdatedComponentRes = getToscaElement(resource.getUniqueId(), filter);
2123 if (getUpdatedComponentRes.isRight()) {
2124 CommonUtility.addRecordToLog(log, LogLevelEnum.DEBUG, "Failed to get updated resource {}. Status is {}. ", resource.getUniqueId(), getUpdatedComponentRes.right().value());
2125 result = Either.right(status);
2128 if (result == null) {
2129 PropertyDefinition newProperty = null;
2130 List<PropertyDefinition> properties = ((Resource) getUpdatedComponentRes.left().value()).getProperties();
2131 if (CollectionUtils.isNotEmpty(properties)) {
2132 Optional<PropertyDefinition> newPropertyOptional = properties.stream().filter(p -> p.getName().equals(propertyName)).findAny();
2133 if (newPropertyOptional.isPresent()) {
2134 newProperty = newPropertyOptional.get();
2137 if (newProperty == null) {
2138 CommonUtility.addRecordToLog(log, LogLevelEnum.DEBUG, "Failed to find recently added property {} on the resource {}. Status is {}. ", propertyName, resource.getUniqueId(), StorageOperationStatus.NOT_FOUND);
2139 result = Either.right(StorageOperationStatus.NOT_FOUND);
2141 result = Either.left(newProperty);
2147 public StorageOperationStatus deletePropertyOfResource(Resource resource, String propertyName) {
2148 return getToscaElementOperation(resource).deleteToscaDataElement(resource.getUniqueId(), EdgeLabelEnum.PROPERTIES, VertexTypeEnum.PROPERTIES, propertyName, JsonPresentationFields.NAME);
2151 public StorageOperationStatus deleteAttributeOfResource(Component component, String attributeName) {
2152 return getToscaElementOperation(component).deleteToscaDataElement(component.getUniqueId(), EdgeLabelEnum.ATTRIBUTES, VertexTypeEnum.ATTRIBUTES, attributeName, JsonPresentationFields.NAME);
2155 public StorageOperationStatus deleteInputOfResource(Component resource, String inputName) {
2156 return getToscaElementOperation(resource).deleteToscaDataElement(resource.getUniqueId(), EdgeLabelEnum.INPUTS, VertexTypeEnum.INPUTS, inputName, JsonPresentationFields.NAME);
2159 public Either<PropertyDefinition, StorageOperationStatus> updatePropertyOfResource(Resource resource, PropertyDefinition newPropertyDefinition) {
2161 Either<Component, StorageOperationStatus> getUpdatedComponentRes = null;
2162 Either<PropertyDefinition, StorageOperationStatus> result = null;
2163 StorageOperationStatus status = getToscaElementOperation(resource).updateToscaDataOfToscaElement(resource.getUniqueId(), EdgeLabelEnum.PROPERTIES, VertexTypeEnum.PROPERTIES, newPropertyDefinition, JsonPresentationFields.NAME);
2164 if (status != StorageOperationStatus.OK) {
2165 CommonUtility.addRecordToLog(log, LogLevelEnum.DEBUG, "Failed to add the property {} to the resource {}. Status is {}. ", newPropertyDefinition.getName(), resource.getName(), status);
2166 result = Either.right(status);
2168 if (result == null) {
2169 ComponentParametersView filter = new ComponentParametersView(true);
2170 filter.setIgnoreProperties(false);
2171 getUpdatedComponentRes = getToscaElement(resource.getUniqueId(), filter);
2172 if (getUpdatedComponentRes.isRight()) {
2173 CommonUtility.addRecordToLog(log, LogLevelEnum.DEBUG, "Failed to get updated resource {}. Status is {}. ", resource.getUniqueId(), getUpdatedComponentRes.right().value());
2174 result = Either.right(status);
2177 if (result == null) {
2178 Optional<PropertyDefinition> newProperty = ((Resource) getUpdatedComponentRes.left().value()).getProperties().stream().filter(p -> p.getName().equals(newPropertyDefinition.getName())).findAny();
2179 if (newProperty.isPresent()) {
2180 result = Either.left(newProperty.get());
2182 CommonUtility.addRecordToLog(log, LogLevelEnum.DEBUG, "Failed to find recently added property {} on the resource {}. Status is {}. ", newPropertyDefinition.getName(), resource.getUniqueId(), StorageOperationStatus.NOT_FOUND);
2183 result = Either.right(StorageOperationStatus.NOT_FOUND);
2189 public Either<PropertyDefinition, StorageOperationStatus> addAttributeOfResource(Component component, PropertyDefinition newAttributeDef) {
2191 Either<Component, StorageOperationStatus> getUpdatedComponentRes = null;
2192 Either<PropertyDefinition, StorageOperationStatus> result = null;
2193 if (newAttributeDef.getUniqueId() == null || newAttributeDef.getUniqueId().isEmpty()) {
2194 String attUniqueId = UniqueIdBuilder.buildAttributeUid(component.getUniqueId(), newAttributeDef.getName());
2195 newAttributeDef.setUniqueId(attUniqueId);
2198 StorageOperationStatus status = getToscaElementOperation(component).addToscaDataToToscaElement(component.getUniqueId(), EdgeLabelEnum.ATTRIBUTES, VertexTypeEnum.ATTRIBUTES, newAttributeDef, JsonPresentationFields.NAME);
2199 if (status != StorageOperationStatus.OK) {
2200 CommonUtility.addRecordToLog(log, LogLevelEnum.DEBUG, "Failed to add the property {} to the resource {}. Status is {}. ", newAttributeDef.getName(), component.getName(), status);
2201 result = Either.right(status);
2203 if (result == null) {
2204 ComponentParametersView filter = new ComponentParametersView(true);
2205 filter.setIgnoreAttributesFrom(false);
2206 getUpdatedComponentRes = getToscaElement(component.getUniqueId(), filter);
2207 if (getUpdatedComponentRes.isRight()) {
2208 CommonUtility.addRecordToLog(log, LogLevelEnum.DEBUG, "Failed to get updated resource {}. Status is {}. ", component.getUniqueId(), getUpdatedComponentRes.right().value());
2209 result = Either.right(status);
2212 if (result == null) {
2213 Optional<PropertyDefinition> newAttribute = ((Resource) getUpdatedComponentRes.left().value()).getAttributes().stream().filter(p -> p.getName().equals(newAttributeDef.getName())).findAny();
2214 if (newAttribute.isPresent()) {
2215 result = Either.left(newAttribute.get());
2217 CommonUtility.addRecordToLog(log, LogLevelEnum.DEBUG, "Failed to find recently added property {} on the resource {}. Status is {}. ", newAttributeDef.getName(), component.getUniqueId(), StorageOperationStatus.NOT_FOUND);
2218 result = Either.right(StorageOperationStatus.NOT_FOUND);
2224 public Either<PropertyDefinition, StorageOperationStatus> updateAttributeOfResource(Component component, PropertyDefinition newAttributeDef) {
2226 Either<Component, StorageOperationStatus> getUpdatedComponentRes = null;
2227 Either<PropertyDefinition, StorageOperationStatus> result = null;
2228 StorageOperationStatus status = getToscaElementOperation(component).updateToscaDataOfToscaElement(component.getUniqueId(), EdgeLabelEnum.ATTRIBUTES, VertexTypeEnum.ATTRIBUTES, newAttributeDef, JsonPresentationFields.NAME);
2229 if (status != StorageOperationStatus.OK) {
2230 CommonUtility.addRecordToLog(log, LogLevelEnum.DEBUG, "Failed to add the property {} to the resource {}. Status is {}. ", newAttributeDef.getName(), component.getName(), status);
2231 result = Either.right(status);
2233 if (result == null) {
2234 ComponentParametersView filter = new ComponentParametersView(true);
2235 filter.setIgnoreAttributesFrom(false);
2236 getUpdatedComponentRes = getToscaElement(component.getUniqueId(), filter);
2237 if (getUpdatedComponentRes.isRight()) {
2238 CommonUtility.addRecordToLog(log, LogLevelEnum.DEBUG, "Failed to get updated resource {}. Status is {}. ", component.getUniqueId(), getUpdatedComponentRes.right().value());
2239 result = Either.right(status);
2242 if (result == null) {
2243 Optional<PropertyDefinition> newProperty = ((Resource) getUpdatedComponentRes.left().value()).getAttributes().stream().filter(p -> p.getName().equals(newAttributeDef.getName())).findAny();
2244 if (newProperty.isPresent()) {
2245 result = Either.left(newProperty.get());
2247 CommonUtility.addRecordToLog(log, LogLevelEnum.DEBUG, "Failed to find recently added property {} on the resource {}. Status is {}. ", newAttributeDef.getName(), component.getUniqueId(), StorageOperationStatus.NOT_FOUND);
2248 result = Either.right(StorageOperationStatus.NOT_FOUND);
2254 public Either<InputDefinition, StorageOperationStatus> updateInputOfComponent(Component component, InputDefinition newInputDefinition) {
2256 Either<Component, StorageOperationStatus> getUpdatedComponentRes = null;
2257 Either<InputDefinition, StorageOperationStatus> result = null;
2258 StorageOperationStatus status = getToscaElementOperation(component).updateToscaDataOfToscaElement(component.getUniqueId(), EdgeLabelEnum.INPUTS, VertexTypeEnum.INPUTS, newInputDefinition, JsonPresentationFields.NAME);
2259 if (status != StorageOperationStatus.OK) {
2260 CommonUtility.addRecordToLog(log, LogLevelEnum.DEBUG, "Failed to update the input {} to the component {}. Status is {}. ", newInputDefinition.getName(), component.getName(), status);
2261 result = Either.right(status);
2263 if (result == null) {
2264 ComponentParametersView filter = new ComponentParametersView(true);
2265 filter.setIgnoreInputs(false);
2266 getUpdatedComponentRes = getToscaElement(component.getUniqueId(), filter);
2267 if (getUpdatedComponentRes.isRight()) {
2268 CommonUtility.addRecordToLog(log, LogLevelEnum.DEBUG, "Failed to get updated resource {}. Status is {}. ", component.getUniqueId(), getUpdatedComponentRes.right().value());
2269 result = Either.right(status);
2272 if (result == null) {
2273 Optional<InputDefinition> updatedInput = getUpdatedComponentRes.left().value().getInputs().stream().filter(p -> p.getName().equals(newInputDefinition.getName())).findAny();
2274 if (updatedInput.isPresent()) {
2275 result = Either.left(updatedInput.get());
2277 CommonUtility.addRecordToLog(log, LogLevelEnum.DEBUG, "Failed to find recently updated inputs {} on the resource {}. Status is {}. ", newInputDefinition.getName(), component.getUniqueId(), StorageOperationStatus.NOT_FOUND);
2278 result = Either.right(StorageOperationStatus.NOT_FOUND);
2285 * method - ename the group instances after referenced container name renamed flow - VF rename -(triggers)-> Group rename
2287 * @param containerComponent
2288 * - container such as service
2289 * @param componentInstance
2290 * - context component
2291 * @param componentInstanceId
2294 * @return - successfull/failed status
2296 public Either<StorageOperationStatus, StorageOperationStatus> cleanAndAddGroupInstancesToComponentInstance(Component containerComponent, ComponentInstance componentInstance, String componentInstanceId) {
2297 String uniqueId = componentInstance.getUniqueId();
2298 StorageOperationStatus status = nodeTemplateOperation.deleteToscaDataDeepElementsBlockToToscaElement(containerComponent.getUniqueId(), EdgeLabelEnum.INST_GROUPS, VertexTypeEnum.INST_GROUPS, uniqueId);
2299 if (status != StorageOperationStatus.OK && status != StorageOperationStatus.NOT_FOUND) {
2300 CommonUtility.addRecordToLog(log, LogLevelEnum.DEBUG, "Failed to delete group instances for container {}. error {] ", componentInstanceId, status);
2301 return Either.right(status);
2303 if (componentInstance.getGroupInstances() != null) {
2304 status = addGroupInstancesToComponentInstance(containerComponent, componentInstance, componentInstance.getGroupInstances());
2305 if (status != StorageOperationStatus.OK && status != StorageOperationStatus.NOT_FOUND) {
2306 CommonUtility.addRecordToLog(log, LogLevelEnum.DEBUG, "Failed to add group instances for container {}. error {] ", componentInstanceId, status);
2307 return Either.right(status);
2310 return Either.left(status);
2313 public StorageOperationStatus addGroupInstancesToComponentInstance(Component containerComponent, ComponentInstance componentInstance, List<GroupDefinition> groups, Map<String, List<ArtifactDefinition>> groupInstancesArtifacts) {
2314 return nodeTemplateOperation.addGroupInstancesToComponentInstance(containerComponent, componentInstance, groups, groupInstancesArtifacts);
2317 public Either<List<GroupDefinition>, StorageOperationStatus> updateGroupsOnComponent(Component component, List<GroupDataDefinition> updatedGroups) {
2318 return groupsOperation.updateGroups(component, updatedGroups);
2321 public Either<List<GroupInstance>, StorageOperationStatus> updateGroupInstancesOnComponent(Component component, ComponentTypeEnum componentType, String instanceId, List<GroupInstance> updatedGroupInstances) {
2322 return groupsOperation.updateGroupInstances(component, instanceId, updatedGroupInstances);
2325 public StorageOperationStatus addGroupInstancesToComponentInstance(Component containerComponent, ComponentInstance componentInstance, List<GroupInstance> groupInstances) {
2326 return nodeTemplateOperation.addGroupInstancesToComponentInstance(containerComponent, componentInstance, groupInstances);
2329 public StorageOperationStatus addDeploymentArtifactsToComponentInstance(Component containerComponent, ComponentInstance componentInstance, Map<String, ArtifactDefinition> deploymentArtifacts) {
2330 return nodeTemplateOperation.addDeploymentArtifactsToComponentInstance(containerComponent, componentInstance, deploymentArtifacts);
2333 public StorageOperationStatus updateComponentInstanceProperty(Component containerComponent, String componentInstanceId, ComponentInstanceProperty property) {
2334 return nodeTemplateOperation.updateComponentInstanceProperty(containerComponent, componentInstanceId, property);
2337 public StorageOperationStatus updateComponentInstanceProperties(Component containerComponent, String componentInstanceId, List<ComponentInstanceProperty> properties) {
2338 return nodeTemplateOperation.updateComponentInstanceProperties(containerComponent, componentInstanceId, properties);
2342 public StorageOperationStatus addComponentInstanceProperty(Component containerComponent, String componentInstanceId, ComponentInstanceProperty property) {
2343 return nodeTemplateOperation.addComponentInstanceProperty(containerComponent, componentInstanceId, property);
2346 public StorageOperationStatus updateComponentInstanceInput(Component containerComponent, String componentInstanceId, ComponentInstanceInput property) {
2347 return nodeTemplateOperation.updateComponentInstanceInput(containerComponent, componentInstanceId, property);
2350 public StorageOperationStatus updateComponentInstanceInputs(Component containerComponent, String componentInstanceId, List<ComponentInstanceInput> instanceInputs) {
2351 return nodeTemplateOperation.updateComponentInstanceInputs(containerComponent, componentInstanceId, instanceInputs);
2354 public StorageOperationStatus addComponentInstanceInput(Component containerComponent, String componentInstanceId, ComponentInstanceInput property) {
2355 return nodeTemplateOperation.addComponentInstanceInput(containerComponent, componentInstanceId, property);
2358 public void setNodeTypeOperation(NodeTypeOperation nodeTypeOperation) {
2359 this.nodeTypeOperation = nodeTypeOperation;
2362 public void setTopologyTemplateOperation(TopologyTemplateOperation topologyTemplateOperation) {
2363 this.topologyTemplateOperation = topologyTemplateOperation;
2366 public StorageOperationStatus deleteComponentInstanceInputsFromTopologyTemplate(Component containerComponent, ComponentTypeEnum componentType, List<InputDefinition> inputsToDelete) {
2367 return topologyTemplateOperation.deleteToscaDataElements(containerComponent.getUniqueId(), EdgeLabelEnum.INPUTS, inputsToDelete.stream().map(i -> i.getName()).collect(Collectors.toList()));
2370 public StorageOperationStatus updateComponentInstanceCapabiltyProperty(Component containerComponent, String componentInstanceUniqueId, String capabilityUniqueId, ComponentInstanceProperty property) {
2371 return nodeTemplateOperation.updateComponentInstanceCapabilityProperty(containerComponent, componentInstanceUniqueId, capabilityUniqueId, property);
2374 public StorageOperationStatus updateComponentInstanceCapabilityProperties(Component containerComponent, String componentInstanceUniqueId) {
2375 return convertComponentInstanceProperties(containerComponent, componentInstanceUniqueId)
2376 .map(instanceCapProps -> topologyTemplateOperation.updateComponentInstanceCapabilityProperties(containerComponent, componentInstanceUniqueId, instanceCapProps))
2377 .orElse(StorageOperationStatus.NOT_FOUND);
2380 public StorageOperationStatus updateComponentCalculatedCapabilitiesProperties(Component containerComponent) {
2381 Map<String, MapCapabiltyProperty> mapCapabiltyPropertyMap = convertComponentCapabilitiesProperties(containerComponent);
2382 return nodeTemplateOperation.overrideComponentCapabilitiesProperties(containerComponent, mapCapabiltyPropertyMap);
2385 public StorageOperationStatus deleteAllCalculatedCapabilitiesRequirements(String topologyTemplateId) {
2386 StorageOperationStatus status = topologyTemplateOperation.removeToscaData(topologyTemplateId, EdgeLabelEnum.CALCULATED_CAPABILITIES, VertexTypeEnum.CALCULATED_CAPABILITIES);
2387 if (status == StorageOperationStatus.OK) {
2388 status = topologyTemplateOperation.removeToscaData(topologyTemplateId, EdgeLabelEnum.CALCULATED_REQUIREMENTS, VertexTypeEnum.CALCULATED_REQUIREMENTS);
2390 if(status == StorageOperationStatus.OK){
2391 status = topologyTemplateOperation.removeToscaData(topologyTemplateId, EdgeLabelEnum.CALCULATED_CAP_PROPERTIES, VertexTypeEnum.CALCULATED_CAP_PROPERTIES);
2396 public Either<Component, StorageOperationStatus> shouldUpgradeToLatestDerived(Resource clonedResource) {
2397 String componentId = clonedResource.getUniqueId();
2398 Either<GraphVertex, TitanOperationStatus> getVertexEither = titanDao.getVertexById(componentId, JsonParseFlagEnum.NoParse);
2399 if (getVertexEither.isRight()) {
2400 log.debug("Couldn't fetch component with and unique id {}, error: {}", componentId, getVertexEither.right().value());
2401 return Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(getVertexEither.right().value()));
2404 GraphVertex nodeTypeV = getVertexEither.left().value();
2406 ToscaElement toscaElementToUpdate = ModelConverter.convertToToscaElement(clonedResource);
2408 Either<ToscaElement, StorageOperationStatus> shouldUpdateDerivedVersion = nodeTypeOperation.shouldUpdateDerivedVersion(toscaElementToUpdate, nodeTypeV);
2409 if ( shouldUpdateDerivedVersion.isRight() && StorageOperationStatus.OK != shouldUpdateDerivedVersion.right().value() ){
2410 log.debug("Failed to update derived version for node type {} derived {}, error: {}", componentId, clonedResource.getDerivedFrom().get(0), shouldUpdateDerivedVersion.right().value());
2411 return Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(getVertexEither.right().value()));
2413 if ( shouldUpdateDerivedVersion.isLeft() ){
2414 return Either.left(ModelConverter.convertFromToscaElement(shouldUpdateDerivedVersion.left().value()));
2416 return Either.left(clonedResource);
2419 * Returns list of ComponentInstanceProperty belonging to component instance capability specified by name, type and ownerId
2420 * @param componentId
2422 * @param capabilityName
2423 * @param capabilityType
2427 public Either<List<ComponentInstanceProperty>, StorageOperationStatus> getComponentInstanceCapabilityProperties(String componentId, String instanceId, String capabilityName, String capabilityType, String ownerId) {
2428 return topologyTemplateOperation.getComponentInstanceCapabilityProperties(componentId, instanceId, capabilityName, capabilityType, ownerId);
2431 private Map<String, MapCapabiltyProperty> convertComponentCapabilitiesProperties(Component currComponent) {
2432 return currComponent.getComponentInstances()
2434 .collect(Collectors.toMap(ComponentInstanceDataDefinition::getUniqueId,
2435 ci -> ModelConverter.convertToMapOfMapCapabiltyProperties(ci.getCapabilities(), ci.getUniqueId(), true)));
2438 private Optional<MapCapabiltyProperty> convertComponentInstanceProperties(Component component, String instanceId) {
2439 return component.fetchInstanceById(instanceId)
2440 .map(ci -> ModelConverter.convertToMapOfMapCapabiltyProperties(ci.getCapabilities(),instanceId));
2443 public Either<PolicyDefinition, StorageOperationStatus> associatePolicyToComponent(String componentId, PolicyDefinition policyDefinition, int counter) {
2444 Either<PolicyDefinition, StorageOperationStatus> result = null;
2445 Either<GraphVertex, TitanOperationStatus> getVertexEither;
2446 getVertexEither = titanDao.getVertexById(componentId, JsonParseFlagEnum.ParseMetadata);
2447 if (getVertexEither.isRight()) {
2448 log.error("Couldn't fetch a component with and UniqueId {}, error: {}", componentId, getVertexEither.right().value());
2449 result = Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(getVertexEither.right().value()));
2451 if(getVertexEither.left().value().getLabel() != VertexTypeEnum.TOPOLOGY_TEMPLATE){
2452 log.error("Policy association to component of Tosca type {} is not allowed. ", getVertexEither.left().value().getLabel());
2453 result = Either.right(StorageOperationStatus.BAD_REQUEST);
2457 StorageOperationStatus status = topologyTemplateOperation.addPolicyToToscaElement(getVertexEither.left().value(), policyDefinition, counter);
2458 if(status != StorageOperationStatus.OK){
2459 return Either.right(status);
2463 result = Either.left(policyDefinition);
2468 public Either<PolicyDefinition, StorageOperationStatus> updatePolicyOfComponent(String componentId, PolicyDefinition policyDefinition) {
2469 Either<PolicyDefinition, StorageOperationStatus> result = null;
2470 Either<GraphVertex, TitanOperationStatus> getVertexEither;
2471 getVertexEither = titanDao.getVertexById(componentId, JsonParseFlagEnum.NoParse);
2472 if (getVertexEither.isRight()) {
2473 log.error("Couldn't fetch a component with and UniqueId {}, error: {}", componentId, getVertexEither.right().value());
2474 result = Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(getVertexEither.right().value()));
2477 StorageOperationStatus status = topologyTemplateOperation.updatePolicyOfToscaElement(getVertexEither.left().value(), policyDefinition);
2478 if(status != StorageOperationStatus.OK){
2479 return Either.right(status);
2483 result = Either.left(policyDefinition);
2488 public StorageOperationStatus updatePoliciesOfComponent(String componentId, List<PolicyDefinition> policyDefinition) {
2489 log.debug("#updatePoliciesOfComponent - updating policies for component {}", componentId);
2490 return titanDao.getVertexById(componentId, JsonParseFlagEnum.NoParse)
2492 .map(DaoStatusConverter::convertTitanStatusToStorageStatus)
2493 .either(containerVertex -> topologyTemplateOperation.updatePoliciesOfToscaElement(containerVertex, policyDefinition),
2497 public StorageOperationStatus removePolicyFromComponent(String componentId, String policyId) {
2498 StorageOperationStatus status = null;
2499 Either<GraphVertex, TitanOperationStatus> getVertexEither = titanDao.getVertexById(componentId, JsonParseFlagEnum.NoParse);
2500 if (getVertexEither.isRight()) {
2501 log.error("Couldn't fetch a component with and UniqueId {}, error: {}", componentId, getVertexEither.right().value());
2502 status = DaoStatusConverter.convertTitanStatusToStorageStatus(getVertexEither.right().value());
2505 status = topologyTemplateOperation.removePolicyFromToscaElement(getVertexEither.left().value(), policyId);