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 // region - Component Update
454 * @param newComponent
455 * @param oldComponent
458 public Either<Resource, StorageOperationStatus> overrideComponent(Resource newComponent, Resource oldComponent) {
461 // newComponent.setInterfaces(oldComponent.getInterfaces);
462 newComponent.setArtifacts(oldComponent.getArtifacts());
463 newComponent.setDeploymentArtifacts(oldComponent.getDeploymentArtifacts());
464 newComponent.setGroups(oldComponent.getGroups());
465 newComponent.setLastUpdateDate(null);
466 newComponent.setHighestVersion(true);
468 Either<GraphVertex, TitanOperationStatus> componentVEither = titanDao.getVertexById(oldComponent.getUniqueId(), JsonParseFlagEnum.NoParse);
469 if (componentVEither.isRight()) {
470 log.debug("Falied to fetch component {} error {}", oldComponent.getUniqueId(), componentVEither.right().value());
471 return Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(componentVEither.right().value()));
473 GraphVertex componentv = componentVEither.left().value();
474 Either<GraphVertex, TitanOperationStatus> parentVertexEither = titanDao.getParentVertex(componentv, EdgeLabelEnum.VERSION, JsonParseFlagEnum.NoParse);
475 if (parentVertexEither.isRight() && parentVertexEither.right().value() != TitanOperationStatus.NOT_FOUND) {
476 log.debug("Falied to fetch parent version for component {} error {}", oldComponent.getUniqueId(), parentVertexEither.right().value());
477 return Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(parentVertexEither.right().value()));
480 Either<ToscaElement, StorageOperationStatus> deleteToscaComponent = deleteToscaElement(componentv);
481 if (deleteToscaComponent.isRight()) {
482 log.debug("Falied to remove old component {} error {}", oldComponent.getUniqueId(), deleteToscaComponent.right().value());
483 return Either.right(deleteToscaComponent.right().value());
485 Either<Resource, StorageOperationStatus> createToscaComponent = createToscaComponent(newComponent);
486 if (createToscaComponent.isRight()) {
487 log.debug("Falied to create tosca element component {} error {}", newComponent.getUniqueId(), createToscaComponent.right().value());
488 return Either.right(createToscaComponent.right().value());
490 Resource newElement = createToscaComponent.left().value();
491 Either<GraphVertex, TitanOperationStatus> newVersionEither = titanDao.getVertexById(newElement.getUniqueId(), JsonParseFlagEnum.NoParse);
492 if (newVersionEither.isRight()) {
493 log.debug("Falied to fetch new tosca element component {} error {}", newComponent.getUniqueId(), newVersionEither.right().value());
494 return Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(newVersionEither.right().value()));
496 if (parentVertexEither.isLeft()) {
497 GraphVertex previousVersionV = parentVertexEither.left().value();
498 TitanOperationStatus createEdge = titanDao.createEdge(previousVersionV, newVersionEither.left().value(), EdgeLabelEnum.VERSION, null);
499 if (createEdge != TitanOperationStatus.OK) {
500 log.debug("Falied to associate to previous version {} new version {} error {}", previousVersionV.getUniqueId(), newVersionEither.right().value(), createEdge);
501 return Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(createEdge));
504 return Either.left(newElement);
509 * @param componentToUpdate
512 public <T extends Component> Either<T, StorageOperationStatus> updateToscaElement(T componentToUpdate) {
513 return updateToscaElement(componentToUpdate, new ComponentParametersView());
518 * @param componentToUpdate
520 * @param filterResult
523 public <T extends Component> Either<T, StorageOperationStatus> updateToscaElement(T componentToUpdate, ComponentParametersView filterResult) {
524 String componentId = componentToUpdate.getUniqueId();
525 Either<GraphVertex, TitanOperationStatus> getVertexEither = titanDao.getVertexById(componentId, JsonParseFlagEnum.ParseAll);
526 if (getVertexEither.isRight()) {
527 log.debug("Couldn't fetch component with and unique id {}, error: {}", componentId, getVertexEither.right().value());
528 return Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(getVertexEither.right().value()));
530 GraphVertex elementV = getVertexEither.left().value();
531 ToscaElementOperation toscaElementOperation = getToscaElementOperation(elementV);
533 ToscaElement toscaElementToUpdate = ModelConverter.convertToToscaElement(componentToUpdate);
534 Either<ToscaElement, StorageOperationStatus> updateToscaElement = toscaElementOperation.updateToscaElement(toscaElementToUpdate, elementV, filterResult);
535 if (updateToscaElement.isRight()) {
536 log.debug("Failed to update tosca element {} error {}", componentId, updateToscaElement.right().value());
537 return Either.right(updateToscaElement.right().value());
539 return Either.left(ModelConverter.convertFromToscaElement(updateToscaElement.left().value()));
542 private <T extends Component> Either<T, StorageOperationStatus> getLatestByName(GraphPropertyEnum property, String nodeName, JsonParseFlagEnum parseFlag) {
543 return getLatestByName(property, nodeName, parseFlag, new ComponentParametersView());
546 private <T extends Component> Either<T, StorageOperationStatus> getLatestByName(GraphPropertyEnum property, String nodeName, JsonParseFlagEnum parseFlag, ComponentParametersView filter) {
547 Either<T, StorageOperationStatus> result;
549 Map<GraphPropertyEnum, Object> propertiesToMatch = new EnumMap<>(GraphPropertyEnum.class);
550 Map<GraphPropertyEnum, Object> propertiesNotToMatch = new EnumMap<>(GraphPropertyEnum.class);
552 propertiesToMatch.put(property, nodeName);
553 propertiesToMatch.put(GraphPropertyEnum.IS_HIGHEST_VERSION, true);
555 propertiesNotToMatch.put(GraphPropertyEnum.IS_DELETED, true);
557 Either<List<GraphVertex>, TitanOperationStatus> highestResources = titanDao.getByCriteria(null, propertiesToMatch, propertiesNotToMatch, parseFlag);
558 if (highestResources.isRight()) {
559 TitanOperationStatus status = highestResources.right().value();
560 log.debug("failed to find resource with name {}. status={} ", nodeName, status);
561 result = Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(status));
565 List<GraphVertex> resources = highestResources.left().value();
566 double version = 0.0;
567 GraphVertex highestResource = null;
568 for (GraphVertex vertex : resources) {
569 Object versionObj = vertex.getMetadataProperty(GraphPropertyEnum.VERSION);
570 double resourceVersion = Double.valueOf((String) versionObj);
571 if (resourceVersion > version) {
572 version = resourceVersion;
573 highestResource = vertex;
576 return getToscaElementByOperation(highestResource, filter);
580 // region - Component Get By ..
581 private <T extends Component> Either<T, StorageOperationStatus> getLatestByName(GraphPropertyEnum property, String nodeName) {
582 return getLatestByName(property, nodeName, JsonParseFlagEnum.ParseMetadata);
585 public <T extends Component> Either<List<T>, StorageOperationStatus> getBySystemName(ComponentTypeEnum componentType, String systemName) {
587 Either<List<T>, StorageOperationStatus> result = null;
588 Either<T, StorageOperationStatus> getComponentRes;
589 List<T> components = new ArrayList<>();
590 List<GraphVertex> componentVertices;
591 Map<GraphPropertyEnum, Object> propertiesToMatch = new EnumMap<>(GraphPropertyEnum.class);
592 Map<GraphPropertyEnum, Object> propertiesNotToMatch = new EnumMap<>(GraphPropertyEnum.class);
594 propertiesToMatch.put(GraphPropertyEnum.SYSTEM_NAME, systemName);
595 if (componentType != null)
596 propertiesToMatch.put(GraphPropertyEnum.COMPONENT_TYPE, componentType.name());
598 propertiesNotToMatch.put(GraphPropertyEnum.IS_DELETED, true);
600 Either<List<GraphVertex>, TitanOperationStatus> getComponentsRes = titanDao.getByCriteria(null, propertiesToMatch, propertiesNotToMatch, JsonParseFlagEnum.ParseAll);
601 if (getComponentsRes.isRight()) {
602 TitanOperationStatus status = getComponentsRes.right().value();
603 log.debug("Failed to fetch the component with system name {}. Status is {} ", systemName, status);
604 result = Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(status));
606 if (result == null) {
607 componentVertices = getComponentsRes.left().value();
608 for (GraphVertex componentVertex : componentVertices) {
609 getComponentRes = getToscaElementByOperation(componentVertex);
610 if (getComponentRes.isRight()) {
611 log.debug("Failed to get the component {}. Status is {} ", componentVertex.getJsonMetadataField(JsonPresentationFields.NAME), getComponentRes.right().value());
612 result = Either.right(getComponentRes.right().value());
615 T componentBySystemName = getComponentRes.left().value();
616 log.debug("Found component, id: {}", componentBySystemName.getUniqueId());
617 components.add(componentBySystemName);
620 if (result == null) {
621 result = Either.left(components);
626 public <T extends Component> Either<T, StorageOperationStatus> getComponentByNameAndVersion(ComponentTypeEnum componentType, String name, String version) {
627 return getComponentByNameAndVersion(componentType, name, version, JsonParseFlagEnum.ParseAll);
630 public <T extends Component> Either<T, StorageOperationStatus> getComponentByNameAndVersion(ComponentTypeEnum componentType, String name, String version, JsonParseFlagEnum parseFlag) {
631 Either<T, StorageOperationStatus> result;
633 Map<GraphPropertyEnum, Object> hasProperties = new EnumMap<>(GraphPropertyEnum.class);
634 Map<GraphPropertyEnum, Object> hasNotProperties = new EnumMap<>(GraphPropertyEnum.class);
636 hasProperties.put(GraphPropertyEnum.NAME, name);
637 hasProperties.put(GraphPropertyEnum.VERSION, version);
638 hasNotProperties.put(GraphPropertyEnum.IS_DELETED, true);
639 if (componentType != null) {
640 hasProperties.put(GraphPropertyEnum.COMPONENT_TYPE, componentType.name());
642 Either<List<GraphVertex>, TitanOperationStatus> getResourceRes = titanDao.getByCriteria(null, hasProperties, hasNotProperties, parseFlag);
643 if (getResourceRes.isRight()) {
644 TitanOperationStatus status = getResourceRes.right().value();
645 log.debug("failed to find resource with name {}, version {}. Status is {} ", name, version, status);
646 result = Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(status));
649 return getToscaElementByOperation(getResourceRes.left().value().get(0));
651 public Either<List<CatalogComponent>, StorageOperationStatus> getCatalogComponents() {
652 return topologyTemplateOperation.getElementCatalogData();
656 public <T extends Component> Either<List<T>, StorageOperationStatus> getCatalogComponents(ComponentTypeEnum componentType, List<OriginTypeEnum> excludeTypes, boolean isHighestVersions) {
657 List<T> components = new ArrayList<>();
658 Either<List<ToscaElement>, StorageOperationStatus> catalogDataResult;
659 List<ToscaElement> toscaElements = new ArrayList<>();
660 List<ResourceTypeEnum> excludedResourceTypes = Optional.ofNullable(excludeTypes).orElse(Collections.emptyList()).stream().filter(type -> !type.equals(OriginTypeEnum.SERVICE)).map(type -> ResourceTypeEnum.getTypeByName(type.name()))
661 .collect(Collectors.toList());
663 switch (componentType) {
665 catalogDataResult = nodeTypeOperation.getElementCatalogData(ComponentTypeEnum.RESOURCE, excludedResourceTypes, isHighestVersions);
666 if (catalogDataResult.isRight()) {
667 return Either.right(catalogDataResult.right().value());
669 toscaElements = catalogDataResult.left().value();
672 if (excludeTypes != null && excludeTypes.contains(OriginTypeEnum.SERVICE)) {
675 catalogDataResult = topologyTemplateOperation.getElementCatalogData(ComponentTypeEnum.SERVICE, null, isHighestVersions);
676 if (catalogDataResult.isRight()) {
677 return Either.right(catalogDataResult.right().value());
679 toscaElements = catalogDataResult.left().value();
682 log.debug("Not supported component type {}", componentType);
683 return Either.right(StorageOperationStatus.BAD_REQUEST);
685 toscaElements.forEach(te -> {
686 T component = ModelConverter.convertFromToscaElement(te);
687 components.add(component);
689 return Either.left(components);
692 public Either<List<String>, StorageOperationStatus> deleteMarkedElements(ComponentTypeEnum componentType) {
693 Either<List<GraphVertex>, StorageOperationStatus> allComponentsMarkedForDeletion;
694 List<String> deleted = new ArrayList<>();
695 switch (componentType) {
697 allComponentsMarkedForDeletion = nodeTypeOperation.getAllComponentsMarkedForDeletion(componentType);
701 allComponentsMarkedForDeletion = topologyTemplateOperation.getAllComponentsMarkedForDeletion(componentType);
704 log.debug("Not supported component type {}", componentType);
705 return Either.right(StorageOperationStatus.BAD_REQUEST);
707 if (allComponentsMarkedForDeletion.isRight()) {
708 return Either.right(allComponentsMarkedForDeletion.right().value());
710 List<GraphVertex> allMarked = allComponentsMarkedForDeletion.left().value();
712 Either<List<GraphVertex>, TitanOperationStatus> allNotDeletedElements = topologyTemplateOperation.getAllNotDeletedElements();
713 if (allNotDeletedElements.isRight()) {
714 return Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(allNotDeletedElements.right().value()));
716 List<GraphVertex> allNonMarked = allNotDeletedElements.left().value();
717 for (GraphVertex elementV : allMarked) {
718 if (topologyTemplateOperation.isInUse(elementV, allNonMarked) == false) {
719 Either<ToscaElement, StorageOperationStatus> deleteToscaElement = deleteToscaElement(elementV);
720 if (deleteToscaElement.isRight()) {
721 log.debug("Failed to delete marked element {} error {}", elementV.getUniqueId(), deleteToscaElement.right().value());
724 deleted.add(elementV.getUniqueId());
725 log.debug("Marked element {} in use. don't delete it", elementV.getUniqueId());
728 return Either.left(deleted);
731 public Either<List<String>, StorageOperationStatus> getAllComponentsMarkedForDeletion(ComponentTypeEnum componentType) {
732 Either<List<GraphVertex>, StorageOperationStatus> allComponentsMarkedForDeletion;
733 switch (componentType) {
735 allComponentsMarkedForDeletion = nodeTypeOperation.getAllComponentsMarkedForDeletion(componentType);
739 allComponentsMarkedForDeletion = topologyTemplateOperation.getAllComponentsMarkedForDeletion(componentType);
742 log.debug("Not supported component type {}", componentType);
743 return Either.right(StorageOperationStatus.BAD_REQUEST);
745 if (allComponentsMarkedForDeletion.isRight()) {
746 return Either.right(allComponentsMarkedForDeletion.right().value());
748 return Either.left(allComponentsMarkedForDeletion.left().value().stream().map(v -> v.getUniqueId()).collect(Collectors.toList()));
751 public Either<Boolean, StorageOperationStatus> isComponentInUse(String componentId) {
752 Either<Boolean, StorageOperationStatus> result;
753 Either<List<GraphVertex>, TitanOperationStatus> allNotDeletedElements = topologyTemplateOperation.getAllNotDeletedElements();
754 if (allNotDeletedElements.isRight()) {
755 result = Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(allNotDeletedElements.right().value()));
757 result = Either.left(topologyTemplateOperation.isInUse(componentId, allNotDeletedElements.left().value()));
762 // region - Component Update
763 public Either<ImmutablePair<Component, String>, StorageOperationStatus> addComponentInstanceToTopologyTemplate(Component containerComponent, Component origComponent, ComponentInstance componentInstance, boolean allowDeleted, User user) {
765 Either<ImmutablePair<Component, String>, StorageOperationStatus> result = null;
766 Either<ToscaElement, StorageOperationStatus> updateContainerComponentRes = null;
767 if (StringUtils.isEmpty(componentInstance.getIcon())) {
768 componentInstance.setIcon(origComponent.getIcon());
770 String nameToFindForCounter = componentInstance.getOriginType() == OriginTypeEnum.ServiceProxy ? componentInstance.getSourceModelName() + PROXY_SUFFIX : origComponent.getName();
771 String nextComponentInstanceCounter = getNextComponentInstanceCounter(containerComponent, nameToFindForCounter);
772 Either<ImmutablePair<TopologyTemplate, String>, StorageOperationStatus> addResult = nodeTemplateOperation.addComponentInstanceToTopologyTemplate(ModelConverter.convertToToscaElement(containerComponent),
773 ModelConverter.convertToToscaElement(origComponent), nextComponentInstanceCounter, componentInstance, allowDeleted, user);
775 if (addResult.isRight()) {
776 CommonUtility.addRecordToLog(log, LogLevelEnum.DEBUG, "Failed to add the component instance {} to container component {}. ", componentInstance.getName(), containerComponent.getName());
777 result = Either.right(addResult.right().value());
779 if (result == null) {
780 updateContainerComponentRes = topologyTemplateOperation.getToscaElement(containerComponent.getUniqueId());
781 if (updateContainerComponentRes.isRight()) {
782 CommonUtility.addRecordToLog(log, LogLevelEnum.DEBUG, "Failed to fetch updated topology template {} with updated component instance {}. ", containerComponent.getName(), componentInstance.getName());
783 result = Either.right(updateContainerComponentRes.right().value());
786 if (result == null) {
787 Component updatedComponent = ModelConverter.convertFromToscaElement(updateContainerComponentRes.left().value());
788 String createdInstanceId = addResult.left().value().getRight();
789 CommonUtility.addRecordToLog(log, LogLevelEnum.TRACE, "The component instance {} has been added to container component {}. ", createdInstanceId, updatedComponent.getName());
790 result = Either.left(new ImmutablePair<>(updatedComponent, createdInstanceId));
795 public StorageOperationStatus associateComponentInstancesToComponent(Component containerComponent, Map<ComponentInstance, Resource> resourcesInstancesMap, boolean allowDeleted) {
797 StorageOperationStatus result = null;
798 CommonUtility.addRecordToLog(log, LogLevelEnum.DEBUG, "Going to add component instances to component {}", containerComponent.getUniqueId());
800 Either<GraphVertex, TitanOperationStatus> metadataVertex = titanDao.getVertexById(containerComponent.getUniqueId(), JsonParseFlagEnum.ParseAll);
801 if (metadataVertex.isRight()) {
802 TitanOperationStatus status = metadataVertex.right().value();
803 if (status == TitanOperationStatus.NOT_FOUND) {
804 status = TitanOperationStatus.INVALID_ID;
806 result = DaoStatusConverter.convertTitanStatusToStorageStatus(status);
808 if (result == null) {
809 result = nodeTemplateOperation.associateComponentInstancesToComponent(containerComponent, resourcesInstancesMap, metadataVertex.left().value(), allowDeleted);
814 public Either<ImmutablePair<Component, String>, StorageOperationStatus> updateComponentInstanceMetadataOfTopologyTemplate(Component containerComponent, Component origComponent, ComponentInstance componentInstance) {
816 Either<ImmutablePair<Component, String>, StorageOperationStatus> result = null;
818 CommonUtility.addRecordToLog(log, LogLevelEnum.TRACE, "Going to update the metadata of the component instance {} belonging to container component {}. ", componentInstance.getName(), containerComponent.getName());
819 componentInstance.setIcon(origComponent.getIcon());
820 Either<ImmutablePair<TopologyTemplate, String>, StorageOperationStatus> updateResult = nodeTemplateOperation.updateComponentInstanceMetadataOfTopologyTemplate(ModelConverter.convertToToscaElement(containerComponent),
821 ModelConverter.convertToToscaElement(origComponent), componentInstance);
822 if (updateResult.isRight()) {
823 CommonUtility.addRecordToLog(log, LogLevelEnum.DEBUG, "Failed to update the metadata of the component instance {} belonging to container component {}. ", componentInstance.getName(), containerComponent.getName());
824 result = Either.right(updateResult.right().value());
826 if (result == null) {
827 Component updatedComponent = ModelConverter.convertFromToscaElement(updateResult.left().value().getLeft());
828 String createdInstanceId = updateResult.left().value().getRight();
829 CommonUtility.addRecordToLog(log, LogLevelEnum.TRACE, "The metadata of the component instance {} has been updated to container component {}. ", createdInstanceId, updatedComponent.getName());
830 result = Either.left(new ImmutablePair<>(updatedComponent, createdInstanceId));
835 public Either<Component, StorageOperationStatus> updateComponentInstanceMetadataOfTopologyTemplate(Component containerComponent) {
836 return updateComponentInstanceMetadataOfTopologyTemplate(containerComponent, new ComponentParametersView());
839 public Either<Component, StorageOperationStatus> updateComponentInstanceMetadataOfTopologyTemplate(Component containerComponent, ComponentParametersView filter) {
841 Either<Component, StorageOperationStatus> result = null;
843 CommonUtility.addRecordToLog(log, LogLevelEnum.TRACE, "Going to update the metadata belonging to container component {}. ", containerComponent.getName());
845 Either<TopologyTemplate, StorageOperationStatus> updateResult = nodeTemplateOperation.updateComponentInstanceMetadataOfTopologyTemplate(ModelConverter.convertToToscaElement(containerComponent), filter);
846 if (updateResult.isRight()) {
847 CommonUtility.addRecordToLog(log, LogLevelEnum.DEBUG, "Failed to update the metadata belonging to container component {}. ", containerComponent.getName());
848 result = Either.right(updateResult.right().value());
850 if (result == null) {
851 Component updatedComponent = ModelConverter.convertFromToscaElement(updateResult.left().value());
852 CommonUtility.addRecordToLog(log, LogLevelEnum.TRACE, "The metadata has been updated to container component {}. ", updatedComponent.getName());
853 result = Either.left(updatedComponent);
859 public Either<ImmutablePair<Component, String>, StorageOperationStatus> deleteComponentInstanceFromTopologyTemplate(Component containerComponent, String resourceInstanceId) {
861 Either<ImmutablePair<Component, String>, StorageOperationStatus> result = null;
863 CommonUtility.addRecordToLog(log, LogLevelEnum.TRACE, "Going to delete the component instance {} belonging to container component {}. ", resourceInstanceId, containerComponent.getName());
865 Either<ImmutablePair<TopologyTemplate, String>, StorageOperationStatus> updateResult = nodeTemplateOperation.deleteComponentInstanceFromTopologyTemplate(ModelConverter.convertToToscaElement(containerComponent), resourceInstanceId);
866 if (updateResult.isRight()) {
867 CommonUtility.addRecordToLog(log, LogLevelEnum.DEBUG, "Failed to delete the component instance {} belonging to container component {}. ", resourceInstanceId, containerComponent.getName());
868 result = Either.right(updateResult.right().value());
870 if (result == null) {
871 Component updatedComponent = ModelConverter.convertFromToscaElement(updateResult.left().value().getLeft());
872 String deletedInstanceId = updateResult.left().value().getRight();
873 CommonUtility.addRecordToLog(log, LogLevelEnum.TRACE, "The component instance {} has been deleted from container component {}. ", deletedInstanceId, updatedComponent.getName());
874 result = Either.left(new ImmutablePair<>(updatedComponent, deletedInstanceId));
879 private String getNextComponentInstanceCounter(Component containerComponent, String originResourceName) {
881 Integer nextCounter = 0;
883 if (CollectionUtils.isNotEmpty(containerComponent.getComponentInstances())) {
885 String normalizedName = ValidationUtils.normalizeComponentInstanceName(originResourceName);
886 Integer maxCounterFromNames = getMaxCounterFromNames(containerComponent, normalizedName);
887 Integer maxCounterFromIds = getMaxCounterFromIds(containerComponent, normalizedName);
889 if (maxCounterFromNames == null && maxCounterFromIds != null) {
890 nextCounter = maxCounterFromIds + 1;
891 } else if (maxCounterFromIds == null && maxCounterFromNames != null) {
892 nextCounter = maxCounterFromNames + 1;
893 } else if (maxCounterFromIds != null && maxCounterFromNames != null) {
894 nextCounter = maxCounterFromNames > maxCounterFromIds ? maxCounterFromNames + 1 : maxCounterFromIds + 1;
897 return nextCounter.toString();
900 private Integer getMaxCounterFromNames(Component containerComponent, String normalizedName) {
902 Integer maxCounter = 0;
903 List<String> countersStr = containerComponent.getComponentInstances().stream().filter(ci -> ci.getNormalizedName() != null && ci.getNormalizedName().startsWith(normalizedName)).map(ci -> ci.getNormalizedName().split(normalizedName)[1])
904 .collect(Collectors.toList());
906 if (CollectionUtils.isEmpty(countersStr)) {
909 Integer currCounter = null;
910 for (String counter : countersStr) {
911 if (StringUtils.isEmpty(counter)) {
915 currCounter = Integer.parseInt(counter);
916 } catch (Exception e) {
919 maxCounter = maxCounter < currCounter ? currCounter : maxCounter;
921 if (currCounter == null) {
927 private Integer getMaxCounterFromIds(Component containerComponent, String normalizedName) {
929 Integer maxCounter = 0;
930 List<String> countersStr = containerComponent.getComponentInstances().stream().filter(ci -> ci.getUniqueId() != null && ci.getUniqueId().contains(normalizedName)).map(ci -> ci.getUniqueId().split(normalizedName)[1])
931 .collect(Collectors.toList());
933 if (CollectionUtils.isEmpty(countersStr)) {
936 Integer currCounter = null;
937 for (String counter : countersStr) {
938 if (StringUtils.isEmpty(counter)) {
942 currCounter = Integer.parseInt(counter);
943 } catch (Exception e) {
946 maxCounter = maxCounter < currCounter ? currCounter : maxCounter;
948 if (currCounter == null) {
954 public Either<RequirementCapabilityRelDef, StorageOperationStatus> associateResourceInstances(String componentId, RequirementCapabilityRelDef requirementDef) {
955 return nodeTemplateOperation.associateResourceInstances(componentId, requirementDef);
959 public Either<List<InputDefinition>, StorageOperationStatus> createAndAssociateInputs(Map<String, InputDefinition> inputs, String componentId) {
961 Either<GraphVertex, TitanOperationStatus> getVertexEither = titanDao.getVertexById(componentId, JsonParseFlagEnum.NoParse);
962 if (getVertexEither.isRight()) {
963 log.debug("Couldn't fetch component with and unique id {}, error: {}", componentId, getVertexEither.right().value());
964 return Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(getVertexEither.right().value()));
968 GraphVertex vertex = getVertexEither.left().value();
969 Map<String, PropertyDataDefinition> inputsMap = inputs.entrySet().stream().collect(Collectors.toMap(Map.Entry::getKey, e -> new PropertyDataDefinition(e.getValue())));
971 StorageOperationStatus status = topologyTemplateOperation.associateInputsToComponent(vertex, inputsMap, componentId);
973 if (StorageOperationStatus.OK == status) {
974 log.debug("Component created successfully!!!");
975 List<InputDefinition> inputsResList = null;
976 if (inputsMap != null && !inputsMap.isEmpty()) {
977 inputsResList = inputsMap.values().stream().map(i -> new InputDefinition(i)).collect(Collectors.toList());
979 return Either.left(inputsResList);
981 return Either.right(status);
985 public Either<List<InputDefinition>, StorageOperationStatus> addInputsToComponent(Map<String, InputDefinition> inputs, String componentId) {
987 Either<GraphVertex, TitanOperationStatus> getVertexEither = titanDao.getVertexById(componentId, JsonParseFlagEnum.NoParse);
988 if (getVertexEither.isRight()) {
989 log.debug("Couldn't fetch component with and unique id {}, error: {}", componentId, getVertexEither.right().value());
990 return Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(getVertexEither.right().value()));
994 GraphVertex vertex = getVertexEither.left().value();
995 Map<String, PropertyDataDefinition> inputsMap = inputs.entrySet().stream().collect(Collectors.toMap(Map.Entry::getKey, e -> new PropertyDataDefinition(e.getValue())));
997 StorageOperationStatus status = topologyTemplateOperation.addToscaDataToToscaElement(vertex, EdgeLabelEnum.INPUTS, VertexTypeEnum.INPUTS, inputsMap, JsonPresentationFields.NAME);
999 if (StorageOperationStatus.OK == status) {
1000 log.debug("Component created successfully!!!");
1001 List<InputDefinition> inputsResList = null;
1002 if (inputsMap != null && !inputsMap.isEmpty()) {
1003 inputsResList = inputsMap.values().stream().map(i -> new InputDefinition(i)).collect(Collectors.toList());
1005 return Either.left(inputsResList);
1007 return Either.right(status);
1011 public Either<List<InputDefinition>, StorageOperationStatus> updateInputsToComponent(List<InputDefinition> inputs, String componentId) {
1013 Either<GraphVertex, TitanOperationStatus> getVertexEither = titanDao.getVertexById(componentId, JsonParseFlagEnum.NoParse);
1014 if (getVertexEither.isRight()) {
1015 log.debug("Couldn't fetch component with and unique id {}, error: {}", componentId, getVertexEither.right().value());
1016 return Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(getVertexEither.right().value()));
1020 GraphVertex vertex = getVertexEither.left().value();
1021 List<PropertyDataDefinition> inputsAsDataDef = inputs.stream().map(PropertyDataDefinition::new).collect(Collectors.toList());
1023 StorageOperationStatus status = topologyTemplateOperation.updateToscaDataOfToscaElement(vertex, EdgeLabelEnum.INPUTS, VertexTypeEnum.INPUTS, inputsAsDataDef, JsonPresentationFields.NAME);
1025 if (StorageOperationStatus.OK == status) {
1026 log.debug("Component created successfully!!!");
1027 List<InputDefinition> inputsResList = null;
1028 if (inputsAsDataDef != null && !inputsAsDataDef.isEmpty()) {
1029 inputsResList = inputsAsDataDef.stream().map(InputDefinition::new).collect(Collectors.toList());
1031 return Either.left(inputsResList);
1033 return Either.right(status);
1037 // region - ComponentInstance
1038 public Either<Map<String, List<ComponentInstanceProperty>>, StorageOperationStatus> associateComponentInstancePropertiesToComponent(Map<String, List<ComponentInstanceProperty>> instProperties, String componentId) {
1040 Either<GraphVertex, TitanOperationStatus> getVertexEither = titanDao.getVertexById(componentId, JsonParseFlagEnum.NoParse);
1041 if (getVertexEither.isRight()) {
1042 log.debug("Couldn't fetch component with and unique id {}, error: {}", componentId, getVertexEither.right().value());
1043 return Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(getVertexEither.right().value()));
1047 GraphVertex vertex = getVertexEither.left().value();
1048 Map<String, MapPropertiesDataDefinition> instPropsMap = new HashMap<>();
1049 if (instProperties != null) {
1051 MapPropertiesDataDefinition propertiesMap;
1052 for (Entry<String, List<ComponentInstanceProperty>> entry : instProperties.entrySet()) {
1053 propertiesMap = new MapPropertiesDataDefinition();
1055 propertiesMap.setMapToscaDataDefinition(entry.getValue().stream().map(e -> new PropertyDataDefinition(e)).collect(Collectors.toMap(e -> e.getName(), e -> e)));
1057 instPropsMap.put(entry.getKey(), propertiesMap);
1061 StorageOperationStatus status = topologyTemplateOperation.associateInstPropertiesToComponent(vertex, instPropsMap);
1063 if (StorageOperationStatus.OK == status) {
1064 log.debug("Component created successfully!!!");
1065 return Either.left(instProperties);
1067 return Either.right(status);
1072 * saves the instInputs as the updated instance inputs of the component container in DB
1074 * @param componentId
1077 public Either<Map<String, List<ComponentInstanceInput>>, StorageOperationStatus> updateComponentInstanceInputsToComponent(Map<String, List<ComponentInstanceInput>> instInputs, String componentId) {
1078 if (instInputs == null || instInputs.isEmpty()) {
1079 return Either.left(instInputs);
1081 StorageOperationStatus status;
1082 for ( Entry<String, List<ComponentInstanceInput>> inputsPerIntance : instInputs.entrySet() ) {
1083 List<ComponentInstanceInput> toscaDataListPerInst = inputsPerIntance.getValue();
1084 List<String> pathKeysPerInst = new ArrayList<>();
1085 pathKeysPerInst.add(inputsPerIntance.getKey());
1086 status = topologyTemplateOperation.updateToscaDataDeepElementsOfToscaElement(componentId, EdgeLabelEnum.INST_INPUTS, VertexTypeEnum.INST_INPUTS, toscaDataListPerInst, pathKeysPerInst, JsonPresentationFields.NAME);
1087 if ( status != StorageOperationStatus.OK) {
1088 log.debug("Failed to update component instance inputs for instance {} in component {} edge type {} error {}", inputsPerIntance.getKey(), componentId, EdgeLabelEnum.INST_INPUTS, status);
1089 return Either.right(status);
1093 return Either.left(instInputs);
1097 * saves the instProps as the updated instance properties of the component container in DB
1099 * @param componentId
1102 public Either<Map<String, List<ComponentInstanceProperty>>, StorageOperationStatus> updateComponentInstancePropsToComponent(Map<String, List<ComponentInstanceProperty>> instProps, String componentId) {
1103 if (instProps == null || instProps.isEmpty()) {
1104 return Either.left(instProps);
1106 StorageOperationStatus status;
1107 for ( Entry<String, List<ComponentInstanceProperty>> propsPerIntance : instProps.entrySet() ) {
1108 List<ComponentInstanceProperty> toscaDataListPerInst = propsPerIntance.getValue();
1109 List<String> pathKeysPerInst = new ArrayList<>();
1110 pathKeysPerInst.add(propsPerIntance.getKey());
1111 status = topologyTemplateOperation.updateToscaDataDeepElementsOfToscaElement(componentId, EdgeLabelEnum.INST_PROPERTIES, VertexTypeEnum.INST_PROPERTIES, toscaDataListPerInst, pathKeysPerInst, JsonPresentationFields.NAME);
1112 if ( status != StorageOperationStatus.OK) {
1113 log.debug("Failed to update component instance inputs for instance {} in component {} edge type {} error {}", propsPerIntance.getKey(), componentId, EdgeLabelEnum.INST_PROPERTIES, status);
1114 return Either.right(status);
1118 return Either.left(instProps);
1121 public Either<Map<String, List<ComponentInstanceInput>>, StorageOperationStatus> associateComponentInstanceInputsToComponent(Map<String, List<ComponentInstanceInput>> instInputs, String componentId) {
1123 Either<GraphVertex, TitanOperationStatus> getVertexEither = titanDao.getVertexById(componentId, JsonParseFlagEnum.NoParse);
1124 if (getVertexEither.isRight()) {
1125 log.debug("Couldn't fetch component with and unique id {}, error: {}", componentId, getVertexEither.right().value());
1126 return Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(getVertexEither.right().value()));
1129 GraphVertex vertex = getVertexEither.left().value();
1130 Map<String, MapPropertiesDataDefinition> instPropsMap = new HashMap<>();
1131 if (instInputs != null) {
1133 MapPropertiesDataDefinition propertiesMap;
1134 for (Entry<String, List<ComponentInstanceInput>> entry : instInputs.entrySet()) {
1135 propertiesMap = new MapPropertiesDataDefinition();
1137 propertiesMap.setMapToscaDataDefinition(entry.getValue().stream().map(e -> new PropertyDataDefinition(e)).collect(Collectors.toMap(e -> e.getName(), e -> e)));
1139 instPropsMap.put(entry.getKey(), propertiesMap);
1143 StorageOperationStatus status = topologyTemplateOperation.associateInstInputsToComponent(vertex, instPropsMap);
1145 if (StorageOperationStatus.OK == status) {
1146 log.debug("Component created successfully!!!");
1147 return Either.left(instInputs);
1149 return Either.right(status);
1153 public Either<Map<String, List<ComponentInstanceInput>>, StorageOperationStatus> addComponentInstanceInputsToComponent(Component containerComponent, Map<String, List<ComponentInstanceInput>> instProperties) {
1155 StorageOperationStatus status = StorageOperationStatus.OK;
1156 if (instProperties != null) {
1158 for (Entry<String, List<ComponentInstanceInput>> entry : instProperties.entrySet()) {
1159 List<ComponentInstanceInput> props = entry.getValue();
1160 String componentInstanseId = entry.getKey();
1161 if (props != null && !props.isEmpty()) {
1162 for (ComponentInstanceInput property : props) {
1163 List<ComponentInstanceInput> componentInstancesInputs = containerComponent.getComponentInstancesInputs().get(componentInstanseId);
1164 Optional<ComponentInstanceInput> instanceProperty = componentInstancesInputs.stream().filter(p -> p.getName().equals(property.getName())).findAny();
1165 if (instanceProperty.isPresent()) {
1166 status = updateComponentInstanceInput(containerComponent, componentInstanseId, property);
1168 status = addComponentInstanceInput(containerComponent, componentInstanseId, property);
1170 if (status != StorageOperationStatus.OK) {
1171 log.debug("Failed to update instance input {} for instance {} error {} ", property, componentInstanseId, status);
1172 return Either.right(status);
1174 log.trace("instance input {} for instance {} updated", property, componentInstanseId);
1180 return Either.left(instProperties);
1183 public Either<Map<String, List<ComponentInstanceProperty>>, StorageOperationStatus> addComponentInstancePropertiesToComponent(Component containerComponent, Map<String, List<ComponentInstanceProperty>> instProperties, String componentId) {
1185 if (instProperties != null) {
1187 for (Entry<String, List<ComponentInstanceProperty>> entry : instProperties.entrySet()) {
1188 List<ComponentInstanceProperty> props = entry.getValue();
1189 String componentInstanseId = entry.getKey();
1190 List<ComponentInstanceProperty> instanceProperties = containerComponent.getComponentInstancesProperties().get(componentInstanseId);
1191 if (props != null && !props.isEmpty()) {
1192 for (ComponentInstanceProperty property : props) {
1193 Optional<ComponentInstanceProperty> instanceProperty = instanceProperties.stream().filter(p -> p.getUniqueId().equals(property.getUniqueId())).findAny();
1194 if (instanceProperty.isPresent()) {
1195 updateComponentInstanceProperty(containerComponent, componentInstanseId, property);
1197 addComponentInstanceProperty(containerComponent, componentInstanseId, property);
1205 return Either.left(instProperties);
1209 public StorageOperationStatus associateDeploymentArtifactsToInstances(Map<String, Map<String, ArtifactDefinition>> instDeploymentArtifacts, String componentId, User user) {
1211 Either<GraphVertex, TitanOperationStatus> getVertexEither = titanDao.getVertexById(componentId, JsonParseFlagEnum.NoParse);
1212 if (getVertexEither.isRight()) {
1213 log.debug("Couldn't fetch component with and unique id {}, error: {}", componentId, getVertexEither.right().value());
1214 return DaoStatusConverter.convertTitanStatusToStorageStatus(getVertexEither.right().value());
1218 GraphVertex vertex = getVertexEither.left().value();
1219 Map<String, MapArtifactDataDefinition> instArtMap = new HashMap<>();
1220 if (instDeploymentArtifacts != null) {
1222 MapArtifactDataDefinition artifactsMap;
1223 for (Entry<String, Map<String, ArtifactDefinition>> entry : instDeploymentArtifacts.entrySet()) {
1224 Map<String, ArtifactDefinition> artList = entry.getValue();
1225 Map<String, ArtifactDataDefinition> artifacts = artList.entrySet().stream().collect(Collectors.toMap(Map.Entry::getKey, e -> new ArtifactDataDefinition(e.getValue())));
1226 artifactsMap = nodeTemplateOperation.prepareInstDeploymentArtifactPerInstance(artifacts, entry.getKey(), user, NodeTemplateOperation.HEAT_VF_ENV_NAME);
1228 instArtMap.put(entry.getKey(), artifactsMap);
1232 return topologyTemplateOperation.associateInstDeploymentArtifactsToComponent(vertex, instArtMap);
1236 public StorageOperationStatus associateArtifactsToInstances(Map<String, Map<String, ArtifactDefinition>> instArtifacts, String componentId, User user) {
1238 Either<GraphVertex, TitanOperationStatus> getVertexEither = titanDao.getVertexById(componentId, JsonParseFlagEnum.NoParse);
1239 if (getVertexEither.isRight()) {
1240 log.debug("Couldn't fetch component with and unique id {}, error: {}", componentId, getVertexEither.right().value());
1241 return DaoStatusConverter.convertTitanStatusToStorageStatus(getVertexEither.right().value());
1245 GraphVertex vertex = getVertexEither.left().value();
1246 Map<String, MapArtifactDataDefinition> instArtMap = new HashMap<>();
1247 if (instArtifacts != null) {
1249 MapArtifactDataDefinition artifactsMap;
1250 for (Entry<String, Map<String, ArtifactDefinition>> entry : instArtifacts.entrySet()) {
1251 Map<String, ArtifactDefinition> artList = entry.getValue();
1252 Map<String, ArtifactDataDefinition> artifacts = artList.entrySet().stream().collect(Collectors.toMap(Map.Entry::getKey, e -> new ArtifactDataDefinition(e.getValue())));
1253 artifactsMap = new MapArtifactDataDefinition(artifacts);
1255 instArtMap.put(entry.getKey(), artifactsMap);
1259 return topologyTemplateOperation.associateInstArtifactsToComponent(vertex, instArtMap);
1263 public StorageOperationStatus associateInstAttributeToComponentToInstances(Map<String, List<PropertyDefinition>> instArttributes, String componentId) {
1265 Either<GraphVertex, TitanOperationStatus> getVertexEither = titanDao.getVertexById(componentId, JsonParseFlagEnum.NoParse);
1266 if (getVertexEither.isRight()) {
1267 log.debug("Couldn't fetch component with and unique id {}, error: {}", componentId, getVertexEither.right().value());
1268 return DaoStatusConverter.convertTitanStatusToStorageStatus(getVertexEither.right().value());
1272 GraphVertex vertex = getVertexEither.left().value();
1273 Map<String, MapPropertiesDataDefinition> instAttr = new HashMap<>();
1274 if (instArttributes != null) {
1276 MapPropertiesDataDefinition attributesMap;
1277 for (Entry<String, List<PropertyDefinition>> entry : instArttributes.entrySet()) {
1278 attributesMap = new MapPropertiesDataDefinition();
1279 attributesMap.setMapToscaDataDefinition(entry.getValue().stream().map(e -> new PropertyDataDefinition(e)).collect(Collectors.toMap(e -> e.getName(), e -> e)));
1280 instAttr.put(entry.getKey(), attributesMap);
1284 return topologyTemplateOperation.associateInstAttributeToComponent(vertex, instAttr);
1289 public StorageOperationStatus associateCalculatedCapReq(Map<ComponentInstance, Map<String, List<CapabilityDefinition>>> instCapabilties, Map<ComponentInstance, Map<String, List<RequirementDefinition>>> instReg, String componentId) {
1290 Either<GraphVertex, TitanOperationStatus> getVertexEither = titanDao.getVertexById(componentId, JsonParseFlagEnum.NoParse);
1291 if (getVertexEither.isRight()) {
1292 log.debug("Couldn't fetch component with and unique id {}, error: {}", componentId, getVertexEither.right().value());
1293 return DaoStatusConverter.convertTitanStatusToStorageStatus(getVertexEither.right().value());
1297 GraphVertex vertex = getVertexEither.left().value();
1299 Map<String, MapListRequirementDataDefinition> calcRequirements = new HashMap<>();
1301 Map<String, MapListCapabiltyDataDefinition> calcCapabilty = new HashMap<>();
1302 Map<String, MapCapabiltyProperty> calculatedCapabilitiesProperties = new HashMap<>();
1304 if (instCapabilties != null) {
1305 for (Entry<ComponentInstance, Map<String, List<CapabilityDefinition>>> entry : instCapabilties.entrySet()) {
1307 Map<String, List<CapabilityDefinition>> caps = entry.getValue();
1308 Map<String, ListCapabilityDataDefinition> mapToscaDataDefinition = new HashMap<>();
1309 for (Entry<String, List<CapabilityDefinition>> instCapability : caps.entrySet()) {
1310 mapToscaDataDefinition.put(instCapability.getKey(), new ListCapabilityDataDefinition(instCapability.getValue().stream().map(iCap -> new CapabilityDataDefinition(iCap)).collect(Collectors.toList())));
1313 ComponentInstanceDataDefinition componentInstance = new ComponentInstanceDataDefinition(entry.getKey());
1314 MapListCapabiltyDataDefinition capMap = nodeTemplateOperation.prepareCalculatedCapabiltyForNodeType(mapToscaDataDefinition, componentInstance);
1316 MapCapabiltyProperty mapCapabiltyProperty = ModelConverter.convertToMapOfMapCapabiltyProperties(caps, componentInstance.getUniqueId(), true);
1318 calcCapabilty.put(entry.getKey().getUniqueId(), capMap);
1319 calculatedCapabilitiesProperties.put(entry.getKey().getUniqueId(), mapCapabiltyProperty);
1323 if (instReg != null) {
1324 for (Entry<ComponentInstance, Map<String, List<RequirementDefinition>>> entry : instReg.entrySet()) {
1326 Map<String, List<RequirementDefinition>> req = entry.getValue();
1327 Map<String, ListRequirementDataDefinition> mapToscaDataDefinition = new HashMap<>();
1328 for (Entry<String, List<RequirementDefinition>> instReq : req.entrySet()) {
1329 mapToscaDataDefinition.put(instReq.getKey(), new ListRequirementDataDefinition(instReq.getValue().stream().map(iCap -> new RequirementDataDefinition(iCap)).collect(Collectors.toList())));
1332 MapListRequirementDataDefinition capMap = nodeTemplateOperation.prepareCalculatedRequirementForNodeType(mapToscaDataDefinition, new ComponentInstanceDataDefinition(entry.getKey()));
1334 calcRequirements.put(entry.getKey().getUniqueId(), capMap);
1338 StorageOperationStatus status = topologyTemplateOperation.associateCalcCapReqToComponent(vertex, calcRequirements, calcCapabilty, calculatedCapabilitiesProperties);
1343 private Either<List<Service>, StorageOperationStatus> getLatestVersionNonCheckoutServicesMetadataOnly(Map<GraphPropertyEnum, Object> hasProps, Map<GraphPropertyEnum, Object> hasNotProps) {
1344 List<Service> services = new ArrayList<>();
1345 List<LifecycleStateEnum> states = new ArrayList<>();
1347 hasProps.put(GraphPropertyEnum.COMPONENT_TYPE, ComponentTypeEnum.SERVICE.name());
1348 hasProps.put(GraphPropertyEnum.IS_HIGHEST_VERSION, true);
1351 states.add(LifecycleStateEnum.NOT_CERTIFIED_CHECKOUT);
1352 hasNotProps.put(GraphPropertyEnum.STATE, states);
1353 hasNotProps.put(GraphPropertyEnum.IS_DELETED, true);
1354 return fetchServicesByCriteria(services, hasProps, hasNotProps);
1357 private Either<List<Component>, StorageOperationStatus> getLatestVersionNotAbstractToscaElementsMetadataOnly(boolean isAbstract, Boolean isHighest, ComponentTypeEnum componentTypeEnum, String internalComponentType, VertexTypeEnum vertexType) {
1358 List<Service> services = null;
1359 Map<GraphPropertyEnum, Object> hasProps = new EnumMap<>(GraphPropertyEnum.class);
1360 Map<GraphPropertyEnum, Object> hasNotProps = new EnumMap<>(GraphPropertyEnum.class);
1361 fillPropsMap(hasProps, hasNotProps, internalComponentType, componentTypeEnum, isAbstract, vertexType);
1362 Either<List<GraphVertex>, TitanOperationStatus> getRes = titanDao.getByCriteria(vertexType, hasProps, hasNotProps, JsonParseFlagEnum.ParseMetadata);
1363 if (getRes.isRight()) {
1364 if (getRes.right().value().equals(TitanOperationStatus.NOT_FOUND)) {
1365 return Either.left(new ArrayList<>());
1367 return Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(getRes.right().value()));
1370 // region -> Fetch non checked-out services
1371 if (internalComponentType != null && internalComponentType.toLowerCase().trim().equals("service") && VertexTypeEnum.NODE_TYPE == vertexType) { // and NODE_TYPE==vertextype
1372 Either<List<Service>, StorageOperationStatus> result = getLatestVersionNonCheckoutServicesMetadataOnly(new EnumMap<>(GraphPropertyEnum.class), new EnumMap<>(GraphPropertyEnum.class));
1373 if (result.isRight()) {
1374 log.debug("Failed to fetch services for");
1375 return Either.right(result.right().value());
1377 services = result.left().value();
1378 if (CollectionUtils.isEmpty(services) && log.isTraceEnabled())
1379 log.trace("No relevant services available");
1382 List<Component> nonAbstractLatestComponents = new ArrayList<>();
1383 ComponentParametersView params = new ComponentParametersView(true);
1384 params.setIgnoreAllVersions(false);
1385 for (GraphVertex vertexComponent : getRes.left().value()) {
1386 Either<ToscaElement, StorageOperationStatus> componentRes = topologyTemplateOperation.getLightComponent(vertexComponent, componentTypeEnum, params);
1387 if (componentRes.isRight()) {
1388 log.debug("Failed to fetch ligth element for {} error {}", vertexComponent.getUniqueId(), componentRes.right().value());
1389 return Either.right(componentRes.right().value());
1391 Component component = ModelConverter.convertFromToscaElement(componentRes.left().value());
1392 nonAbstractLatestComponents.add(component);
1395 if (CollectionUtils.isNotEmpty(services))
1396 nonAbstractLatestComponents.addAll(services);
1397 return Either.left(nonAbstractLatestComponents);
1401 public Either<ComponentMetadataData, StorageOperationStatus> getLatestComponentMetadataByUuid(String componentUuid, JsonParseFlagEnum parseFlag, Boolean isHighest) {
1403 Either<ComponentMetadataData, StorageOperationStatus> result;
1405 Map<GraphPropertyEnum, Object> hasProperties = new EnumMap<>(GraphPropertyEnum.class);
1407 hasProperties.put(GraphPropertyEnum.UUID, componentUuid);
1408 if (isHighest != null) {
1409 hasProperties.put(GraphPropertyEnum.IS_HIGHEST_VERSION, isHighest.booleanValue());
1412 Map<GraphPropertyEnum, Object> propertiesNotToMatch = new EnumMap<>(GraphPropertyEnum.class);
1413 propertiesNotToMatch.put(GraphPropertyEnum.IS_DELETED, true);
1415 Either<List<GraphVertex>, TitanOperationStatus> getRes = titanDao.getByCriteria(null, hasProperties, propertiesNotToMatch, parseFlag);
1416 if (getRes.isRight()) {
1417 result = Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(getRes.right().value()));
1419 List<ComponentMetadataData> latestVersionList = getRes.left().value().stream().map(ModelConverter::convertToComponentMetadata).collect(Collectors.toList());
1420 ComponentMetadataData latestVersion = latestVersionList.size() == 1 ? latestVersionList.get(0)
1421 : latestVersionList.stream().max((c1, c2) -> Double.compare(Double.parseDouble(c1.getMetadataDataDefinition().getVersion()), Double.parseDouble(c2.getMetadataDataDefinition().getVersion()))).get();
1422 result = Either.left(latestVersion);
1427 public Either<ComponentMetadataData, StorageOperationStatus> getComponentMetadata(String componentId) {
1429 Either<ComponentMetadataData, StorageOperationStatus> result;
1430 Either<GraphVertex, TitanOperationStatus> getRes = titanDao.getVertexById(componentId, JsonParseFlagEnum.ParseMetadata);
1431 if (getRes.isRight()) {
1432 result = Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(getRes.right().value()));
1434 ComponentMetadataData componentMetadata = ModelConverter.convertToComponentMetadata(getRes.left().value());
1435 result = Either.left(componentMetadata);
1440 public Either<List<Component>, StorageOperationStatus> getLatestVersionNotAbstractComponents(boolean isAbstract, Boolean isHighest, ComponentTypeEnum componentTypeEnum, String internalComponentType, List<String> componentUids) {
1442 Either<List<Component>, StorageOperationStatus> result = null;
1443 List<Component> components = new ArrayList<>();
1444 if (componentUids == null) {
1445 Either<List<String>, StorageOperationStatus> componentUidsRes = getComponentUids(isAbstract, isHighest, componentTypeEnum, internalComponentType, componentUids);
1446 if (componentUidsRes.isRight()) {
1447 result = Either.right(componentUidsRes.right().value());
1449 componentUids = componentUidsRes.left().value();
1452 if (!componentUids.isEmpty()) {
1453 for (String componentUid : componentUids) {
1454 ComponentParametersView componentParametersView = buildComponentViewForNotAbstract();
1455 if (internalComponentType != null && "vl".equalsIgnoreCase(internalComponentType)) {
1456 componentParametersView.setIgnoreCapabilities(false);
1457 componentParametersView.setIgnoreRequirements(false);
1459 Either<ToscaElement, StorageOperationStatus> getToscaElementRes = nodeTemplateOperation.getToscaElementOperation(componentTypeEnum).getLightComponent(componentUid, componentTypeEnum, componentParametersView);
1460 if (getToscaElementRes.isRight()) {
1461 if (log.isDebugEnabled())
1462 log.debug("Failed to fetch resource for error is {}", getToscaElementRes.right().value());
1463 result = Either.right(getToscaElementRes.right().value());
1466 Component component = ModelConverter.convertFromToscaElement(getToscaElementRes.left().value());
1467 component.setContactId(null);
1468 component.setCreationDate(null);
1469 component.setCreatorUserId(null);
1470 component.setCreatorFullName(null);
1471 component.setLastUpdateDate(null);
1472 component.setLastUpdaterUserId(null);
1473 component.setLastUpdaterFullName(null);
1474 component.setNormalizedName(null);
1475 components.add(component);
1478 if (result == null) {
1479 result = Either.left(components);
1484 private Either<List<String>, StorageOperationStatus> getComponentUids(boolean isAbstract, Boolean isHighest, ComponentTypeEnum componentTypeEnum, String internalComponentType, List<String> componentUids) {
1486 Either<List<String>, StorageOperationStatus> result = null;
1487 Either<List<Component>, StorageOperationStatus> getToscaElementsRes = getLatestVersionNotAbstractMetadataOnly(isAbstract, isHighest, componentTypeEnum, internalComponentType);
1488 if (getToscaElementsRes.isRight()) {
1489 result = Either.right(getToscaElementsRes.right().value());
1491 List<Component> collection = getToscaElementsRes.left().value();
1492 if (collection == null) {
1493 componentUids = new ArrayList<>();
1495 componentUids = collection.stream().map(p -> p.getUniqueId()).collect(Collectors.toList());
1498 if (result == null) {
1499 result = Either.left(componentUids);
1504 private ComponentParametersView buildComponentViewForNotAbstract() {
1505 ComponentParametersView componentParametersView = new ComponentParametersView();
1506 componentParametersView.disableAll();
1507 componentParametersView.setIgnoreCategories(false);
1508 componentParametersView.setIgnoreAllVersions(false);
1509 return componentParametersView;
1512 public Either<Boolean, StorageOperationStatus> validateComponentNameExists(String name, ResourceTypeEnum resourceType, ComponentTypeEnum componentType) {
1513 Either<Boolean, StorageOperationStatus> result = validateComponentNameUniqueness(name, resourceType, componentType);
1514 if (result.isLeft()) {
1515 result = Either.left(!result.left().value());
1520 public Either<Boolean, StorageOperationStatus> validateComponentNameUniqueness(String name, ResourceTypeEnum resourceType, ComponentTypeEnum componentType) {
1521 VertexTypeEnum vertexType = ModelConverter.isAtomicComponent(resourceType) ? VertexTypeEnum.NODE_TYPE : VertexTypeEnum.TOPOLOGY_TEMPLATE;
1522 String normalizedName = ValidationUtils.normaliseComponentName(name);
1523 Map<GraphPropertyEnum, Object> properties = new EnumMap<>(GraphPropertyEnum.class);
1524 properties.put(GraphPropertyEnum.NORMALIZED_NAME, normalizedName);
1525 properties.put(GraphPropertyEnum.COMPONENT_TYPE, componentType.name());
1527 Either<List<GraphVertex>, TitanOperationStatus> vertexEither = titanDao.getByCriteria(vertexType, properties, JsonParseFlagEnum.NoParse);
1528 if (vertexEither.isRight() && vertexEither.right().value() != TitanOperationStatus.NOT_FOUND) {
1529 log.debug("failed to get vertex from graph with property normalizedName: {}", normalizedName);
1530 return Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(vertexEither.right().value()));
1532 List<GraphVertex> vertexList = vertexEither.isLeft() ? vertexEither.left().value() : null;
1533 if (vertexList != null && !vertexList.isEmpty()) {
1534 return Either.left(false);
1536 return Either.left(true);
1540 private void fillNodeTypePropsMap(Map<GraphPropertyEnum, Object> hasProps, Map<GraphPropertyEnum, Object> hasNotProps, String internalComponentType) {
1541 switch (internalComponentType.toLowerCase()) {
1544 hasNotProps.put(GraphPropertyEnum.RESOURCE_TYPE, Arrays.asList(ResourceTypeEnum.VFCMT.name(), ResourceTypeEnum.Configuration.name()));
1549 hasNotProps.put(GraphPropertyEnum.RESOURCE_TYPE, Arrays.asList(ResourceTypeEnum.VFC.name(), ResourceTypeEnum.VFCMT.name()));
1552 hasProps.put(GraphPropertyEnum.RESOURCE_TYPE, ResourceTypeEnum.VL.name());
1559 private void fillTopologyTemplatePropsMap(Map<GraphPropertyEnum, Object> hasProps, Map<GraphPropertyEnum, Object> hasNotProps, ComponentTypeEnum componentTypeEnum, String internalComponentType) {
1560 switch (componentTypeEnum) {
1562 hasProps.put(GraphPropertyEnum.COMPONENT_TYPE, ComponentTypeEnum.RESOURCE.name());
1565 hasProps.put(GraphPropertyEnum.COMPONENT_TYPE, ComponentTypeEnum.SERVICE.name());
1570 switch (internalComponentType.toLowerCase()) {
1573 hasProps.put(GraphPropertyEnum.RESOURCE_TYPE, ResourceTypeEnum.CVFC.name());
1576 hasNotProps.put(GraphPropertyEnum.RESOURCE_TYPE, ResourceTypeEnum.CVFC.name());
1583 private void fillPropsMap(Map<GraphPropertyEnum, Object> hasProps, Map<GraphPropertyEnum, Object> hasNotProps, String internalComponentType, ComponentTypeEnum componentTypeEnum, boolean isAbstract, VertexTypeEnum internalVertexType) {
1584 hasNotProps.put(GraphPropertyEnum.STATE, LifecycleStateEnum.NOT_CERTIFIED_CHECKOUT.name());
1586 hasNotProps.put(GraphPropertyEnum.IS_DELETED, true);
1587 hasProps.put(GraphPropertyEnum.IS_HIGHEST_VERSION, true);
1588 if (VertexTypeEnum.NODE_TYPE == internalVertexType) {
1589 hasProps.put(GraphPropertyEnum.IS_ABSTRACT, isAbstract);
1590 if (internalComponentType != null) {
1591 fillNodeTypePropsMap(hasProps, hasNotProps, internalComponentType);
1594 fillTopologyTemplatePropsMap(hasProps, hasNotProps, componentTypeEnum, internalComponentType);
1598 private List<VertexTypeEnum> getInternalVertexTypes(ComponentTypeEnum componentTypeEnum, String internalComponentType) {
1599 List<VertexTypeEnum> internalVertexTypes = new ArrayList<>();
1600 if (ComponentTypeEnum.RESOURCE == componentTypeEnum) {
1601 internalVertexTypes.add(VertexTypeEnum.NODE_TYPE);
1603 if (ComponentTypeEnum.SERVICE == componentTypeEnum || "service".equalsIgnoreCase(internalComponentType) || "vf".equalsIgnoreCase(internalComponentType)) {
1604 internalVertexTypes.add(VertexTypeEnum.TOPOLOGY_TEMPLATE);
1606 return internalVertexTypes;
1609 public Either<List<Component>, StorageOperationStatus> getLatestVersionNotAbstractMetadataOnly(boolean isAbstract, Boolean isHighest, ComponentTypeEnum componentTypeEnum, String internalComponentType) {
1610 List<VertexTypeEnum> internalVertexTypes = getInternalVertexTypes(componentTypeEnum, internalComponentType);
1611 List<Component> result = new ArrayList<>();
1612 for (VertexTypeEnum vertexType : internalVertexTypes) {
1613 Either<List<Component>, StorageOperationStatus> listByVertexType = getLatestVersionNotAbstractToscaElementsMetadataOnly(isAbstract, isHighest, componentTypeEnum, internalComponentType, vertexType);
1614 if (listByVertexType.isRight()) {
1615 return listByVertexType;
1617 result.addAll(listByVertexType.left().value());
1619 return Either.left(result);
1623 private Either<List<Component>, StorageOperationStatus> getLatestComponentListByUuid(String componentUuid, Map<GraphPropertyEnum, Object> additionalPropertiesToMatch) {
1624 Map<GraphPropertyEnum, Object> propertiesToMatch = new EnumMap<>(GraphPropertyEnum.class);
1625 if (additionalPropertiesToMatch != null) {
1626 propertiesToMatch.putAll(additionalPropertiesToMatch);
1628 propertiesToMatch.put(GraphPropertyEnum.IS_HIGHEST_VERSION, true);
1629 Either<List<Component>, StorageOperationStatus> componentListByUuid = getComponentListByUuid(componentUuid, propertiesToMatch);
1630 return componentListByUuid;
1633 public Either<Component, StorageOperationStatus> getComponentByUuidAndVersion(String componentUuid, String version) {
1634 Map<GraphPropertyEnum, Object> propertiesToMatch = new EnumMap<>(GraphPropertyEnum.class);
1636 propertiesToMatch.put(GraphPropertyEnum.UUID, componentUuid);
1637 propertiesToMatch.put(GraphPropertyEnum.VERSION, version);
1639 Map<GraphPropertyEnum, Object> propertiesNotToMatch = new EnumMap<>(GraphPropertyEnum.class);
1640 propertiesNotToMatch.put(GraphPropertyEnum.IS_DELETED, true);
1641 Either<List<GraphVertex>, TitanOperationStatus> vertexEither = titanDao.getByCriteria(null, propertiesToMatch, propertiesNotToMatch, JsonParseFlagEnum.ParseAll);
1642 if (vertexEither.isRight()) {
1643 return Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(vertexEither.right().value()));
1646 List<GraphVertex> vertexList = vertexEither.isLeft() ? vertexEither.left().value() : null;
1647 if (vertexList == null || vertexList.isEmpty() || vertexList.size() > 1) {
1648 return Either.right(StorageOperationStatus.NOT_FOUND);
1651 return getToscaElementByOperation(vertexList.get(0));
1654 public Either<List<Component>, StorageOperationStatus> getComponentListByUuid(String componentUuid, Map<GraphPropertyEnum, Object> additionalPropertiesToMatch) {
1656 Map<GraphPropertyEnum, Object> propertiesToMatch = new EnumMap<>(GraphPropertyEnum.class);
1658 if (additionalPropertiesToMatch != null) {
1659 propertiesToMatch.putAll(additionalPropertiesToMatch);
1662 propertiesToMatch.put(GraphPropertyEnum.UUID, componentUuid);
1664 Map<GraphPropertyEnum, Object> propertiesNotToMatch = new EnumMap<>(GraphPropertyEnum.class);
1665 propertiesNotToMatch.put(GraphPropertyEnum.IS_DELETED, true);
1667 Either<List<GraphVertex>, TitanOperationStatus> vertexEither = titanDao.getByCriteria(null, propertiesToMatch, propertiesNotToMatch, JsonParseFlagEnum.ParseAll);
1669 if (vertexEither.isRight()) {
1670 log.debug("Couldn't fetch metadata for component with type {} and uuid {}, error: {}", componentUuid, vertexEither.right().value());
1671 return Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(vertexEither.right().value()));
1673 List<GraphVertex> vertexList = vertexEither.isLeft() ? vertexEither.left().value() : null;
1675 if (vertexList == null || vertexList.isEmpty()) {
1676 log.debug("Component with uuid {} was not found", componentUuid);
1677 return Either.right(StorageOperationStatus.NOT_FOUND);
1680 ArrayList<Component> latestComponents = new ArrayList<>();
1681 for (GraphVertex vertex : vertexList) {
1682 Either<Component, StorageOperationStatus> toscaElementByOperation = getToscaElementByOperation(vertex);
1684 if (toscaElementByOperation.isRight()) {
1685 log.debug("Could not fetch the following Component by UUID {}", vertex.getUniqueId());
1686 return Either.right(toscaElementByOperation.right().value());
1689 latestComponents.add(toscaElementByOperation.left().value());
1692 if (latestComponents.size() > 1) {
1693 for (Component component : latestComponents) {
1694 if (component.isHighestVersion()) {
1695 LinkedList<Component> highestComponent = new LinkedList<>();
1696 highestComponent.add(component);
1697 return Either.left(highestComponent);
1702 return Either.left(latestComponents);
1705 public Either<Component, StorageOperationStatus> getLatestServiceByUuid(String serviceUuid) {
1706 Map<GraphPropertyEnum, Object> propertiesToMatch = new HashMap<>();
1707 propertiesToMatch.put(GraphPropertyEnum.COMPONENT_TYPE, ComponentTypeEnum.SERVICE.name());
1708 return getLatestComponentByUuid(serviceUuid, propertiesToMatch);
1711 public Either<Component, StorageOperationStatus> getLatestComponentByUuid(String componentUuid) {
1712 return getLatestComponentByUuid(componentUuid, null);
1715 public Either<Component, StorageOperationStatus> getLatestComponentByUuid(String componentUuid, Map<GraphPropertyEnum, Object> propertiesToMatch) {
1717 Either<List<Component>, StorageOperationStatus> latestVersionListEither = getLatestComponentListByUuid(componentUuid, propertiesToMatch);
1719 if (latestVersionListEither.isRight()) {
1720 return Either.right(latestVersionListEither.right().value());
1723 List<Component> latestVersionList = latestVersionListEither.left().value();
1725 if (latestVersionList.isEmpty()) {
1726 return Either.right(StorageOperationStatus.NOT_FOUND);
1728 Component component = latestVersionList.size() == 1 ? latestVersionList.get(0) : latestVersionList.stream().max((c1, c2) -> Double.compare(Double.parseDouble(c1.getVersion()), Double.parseDouble(c2.getVersion()))).get();
1730 return Either.left(component);
1733 public Either<List<Resource>, StorageOperationStatus> getAllCertifiedResources(boolean isAbstract, Boolean isHighest) {
1735 List<Resource> resources = new ArrayList<>();
1736 Map<GraphPropertyEnum, Object> propertiesToMatch = new EnumMap<>(GraphPropertyEnum.class);
1737 Map<GraphPropertyEnum, Object> propertiesNotToMatch = new EnumMap<>(GraphPropertyEnum.class);
1739 propertiesToMatch.put(GraphPropertyEnum.IS_ABSTRACT, isAbstract);
1740 if (isHighest != null) {
1741 propertiesToMatch.put(GraphPropertyEnum.IS_HIGHEST_VERSION, isHighest.booleanValue());
1743 propertiesToMatch.put(GraphPropertyEnum.STATE, LifecycleStateEnum.CERTIFIED.name());
1744 propertiesToMatch.put(GraphPropertyEnum.COMPONENT_TYPE, ComponentTypeEnum.RESOURCE.name());
1745 propertiesNotToMatch.put(GraphPropertyEnum.IS_DELETED, true);
1747 Either<List<GraphVertex>, TitanOperationStatus> getResourcesRes = titanDao.getByCriteria(null, propertiesToMatch, propertiesNotToMatch, JsonParseFlagEnum.ParseAll);
1749 if (getResourcesRes.isRight()) {
1750 log.debug("Failed to fetch all certified resources. Status is {}", getResourcesRes.right().value());
1751 return Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(getResourcesRes.right().value()));
1753 List<GraphVertex> resourceVerticies = getResourcesRes.left().value();
1754 for (GraphVertex resourceV : resourceVerticies) {
1755 Either<Resource, StorageOperationStatus> getResourceRes = getToscaElement(resourceV);
1756 if (getResourceRes.isRight()) {
1757 return Either.right(getResourceRes.right().value());
1759 resources.add(getResourceRes.left().value());
1761 return Either.left(resources);
1764 public <T extends Component> Either<T, StorageOperationStatus> getLatestByNameAndVersion(String name, String version, JsonParseFlagEnum parseFlag) {
1765 Either<T, StorageOperationStatus> result;
1767 Map<GraphPropertyEnum, Object> hasProperties = new EnumMap<>(GraphPropertyEnum.class);
1768 Map<GraphPropertyEnum, Object> hasNotProperties = new EnumMap<>(GraphPropertyEnum.class);
1770 hasProperties.put(GraphPropertyEnum.NAME, name);
1771 hasProperties.put(GraphPropertyEnum.VERSION, version);
1772 hasProperties.put(GraphPropertyEnum.IS_HIGHEST_VERSION, true);
1774 hasNotProperties.put(GraphPropertyEnum.IS_DELETED, true);
1776 Either<List<GraphVertex>, TitanOperationStatus> getResourceRes = titanDao.getByCriteria(null, hasProperties, hasNotProperties, parseFlag);
1777 if (getResourceRes.isRight()) {
1778 TitanOperationStatus status = getResourceRes.right().value();
1779 log.debug("failed to find resource with name {}, version {}. Status is {} ", name, version, status);
1780 result = Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(status));
1783 return getToscaElementByOperation(getResourceRes.left().value().get(0));
1786 public Either<Resource, StorageOperationStatus> getLatestComponentByCsarOrName(ComponentTypeEnum componentType, String csarUUID, String systemName) {
1787 return getLatestComponentByCsarOrName(componentType, csarUUID, systemName, false, JsonParseFlagEnum.ParseAll);
1790 public Either<Resource, StorageOperationStatus> getLatestComponentByCsarOrName(ComponentTypeEnum componentType, String csarUUID, String systemName, boolean allowDeleted, JsonParseFlagEnum parseFlag) {
1791 Map<GraphPropertyEnum, Object> props = new EnumMap<>(GraphPropertyEnum.class);
1792 props.put(GraphPropertyEnum.CSAR_UUID, csarUUID);
1793 props.put(GraphPropertyEnum.IS_HIGHEST_VERSION, true);
1794 if (componentType != null) {
1795 props.put(GraphPropertyEnum.COMPONENT_TYPE, componentType.name());
1797 Map<GraphPropertyEnum, Object> propsHasNot = new EnumMap<>(GraphPropertyEnum.class);
1798 propsHasNot.put(GraphPropertyEnum.IS_DELETED, true);
1800 GraphVertex resourceMetadataData = null;
1801 List<GraphVertex> resourceMetadataDataList = null;
1802 Either<List<GraphVertex>, TitanOperationStatus> byCsar = titanDao.getByCriteria(null, props, propsHasNot, JsonParseFlagEnum.ParseMetadata);
1803 if (byCsar.isRight()) {
1804 if (TitanOperationStatus.NOT_FOUND == byCsar.right().value()) {
1805 // Fix Defect DE256036
1806 if (StringUtils.isEmpty(systemName)) {
1807 return Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(TitanOperationStatus.NOT_FOUND));
1811 props.put(GraphPropertyEnum.IS_HIGHEST_VERSION, true);
1812 props.put(GraphPropertyEnum.SYSTEM_NAME, systemName);
1813 Either<List<GraphVertex>, TitanOperationStatus> bySystemname = titanDao.getByCriteria(null, props, JsonParseFlagEnum.ParseMetadata);
1814 if (bySystemname.isRight()) {
1815 log.debug("getLatestResourceByCsarOrName - Failed to find by system name {} error {} ", systemName, bySystemname.right().value());
1816 return Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(bySystemname.right().value()));
1818 if (bySystemname.left().value().size() > 2) {
1819 log.debug("getLatestResourceByCsarOrName - getByCriteria(by system name) must return only 2 latest version, but was returned - {}", bySystemname.left().value().size());
1820 return Either.right(StorageOperationStatus.GENERAL_ERROR);
1822 resourceMetadataDataList = bySystemname.left().value();
1823 if (resourceMetadataDataList.size() == 1) {
1824 resourceMetadataData = resourceMetadataDataList.get(0);
1826 for (GraphVertex curResource : resourceMetadataDataList) {
1827 if (!((String) curResource.getJsonMetadataField(JsonPresentationFields.LIFECYCLE_STATE)).equals("CERTIFIED")) {
1828 resourceMetadataData = curResource;
1833 if (resourceMetadataData == null) {
1834 log.debug("getLatestResourceByCsarOrName - getByCriteria(by system name) returned 2 latest CERTIFIED versions");
1835 return Either.right(StorageOperationStatus.GENERAL_ERROR);
1837 if (resourceMetadataData.getJsonMetadataField(JsonPresentationFields.CSAR_UUID) != null && !((String) resourceMetadataData.getJsonMetadataField(JsonPresentationFields.CSAR_UUID)).equals(csarUUID)) {
1838 log.debug("getLatestResourceByCsarOrName - same system name {} but different csarUUID. exist {} and new {} ", systemName, resourceMetadataData.getJsonMetadataField(JsonPresentationFields.CSAR_UUID), csarUUID);
1839 // correct error will be returned from create flow. with all
1840 // correct audit records!!!!!
1841 return Either.right(StorageOperationStatus.NOT_FOUND);
1843 Either<Resource, StorageOperationStatus> resource = getToscaElement((String) resourceMetadataData.getUniqueId());
1847 resourceMetadataDataList = byCsar.left().value();
1848 if (resourceMetadataDataList.size() > 2) {
1849 log.debug("getLatestResourceByCsarOrName - getByCriteria(by csar) must return only 2 latest version, but was returned - {}", byCsar.left().value().size());
1850 return Either.right(StorageOperationStatus.GENERAL_ERROR);
1852 if (resourceMetadataDataList.size() == 1) {
1853 resourceMetadataData = resourceMetadataDataList.get(0);
1855 for (GraphVertex curResource : resourceMetadataDataList) {
1856 if (!((String) curResource.getJsonMetadataField(JsonPresentationFields.LIFECYCLE_STATE)).equals("CERTIFIED")) {
1857 resourceMetadataData = curResource;
1862 if (resourceMetadataData == null) {
1863 log.debug("getLatestResourceByCsarOrName - getByCriteria(by csar) returned 2 latest CERTIFIED versions");
1864 return Either.right(StorageOperationStatus.GENERAL_ERROR);
1866 Either<Resource, StorageOperationStatus> resource = getToscaElement((String) resourceMetadataData.getJsonMetadataField(JsonPresentationFields.UNIQUE_ID), parseFlag);
1872 public Either<Boolean, StorageOperationStatus> validateToscaResourceNameExtends(String templateNameCurrent, String templateNameExtends) {
1874 String currentTemplateNameChecked = templateNameExtends;
1876 while (currentTemplateNameChecked != null && !currentTemplateNameChecked.equalsIgnoreCase(templateNameCurrent)) {
1877 Either<Resource, StorageOperationStatus> latestByToscaResourceName = getLatestByToscaResourceName(currentTemplateNameChecked);
1879 if (latestByToscaResourceName.isRight()) {
1880 return latestByToscaResourceName.right().value() == StorageOperationStatus.NOT_FOUND ? Either.left(false) : Either.right(latestByToscaResourceName.right().value());
1883 Resource value = latestByToscaResourceName.left().value();
1885 if (value.getDerivedFrom() != null) {
1886 currentTemplateNameChecked = value.getDerivedFrom().get(0);
1888 currentTemplateNameChecked = null;
1892 return (currentTemplateNameChecked != null && currentTemplateNameChecked.equalsIgnoreCase(templateNameCurrent)) ? Either.left(true) : Either.left(false);
1895 public Either<List<Component>, StorageOperationStatus> fetchMetaDataByResourceType(String resourceType, ComponentParametersView filterBy) {
1896 Map<GraphPropertyEnum, Object> props = new EnumMap<>(GraphPropertyEnum.class);
1897 props.put(GraphPropertyEnum.RESOURCE_TYPE, resourceType);
1898 props.put(GraphPropertyEnum.IS_HIGHEST_VERSION, true);
1899 Map<GraphPropertyEnum, Object> propsHasNotToMatch = new HashMap<>();
1900 propsHasNotToMatch.put(GraphPropertyEnum.IS_DELETED, true);
1901 Either<List<GraphVertex>, TitanOperationStatus> resourcesByTypeEither = titanDao.getByCriteria(null, props, propsHasNotToMatch, JsonParseFlagEnum.ParseMetadata);
1903 if (resourcesByTypeEither.isRight()) {
1904 return Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(resourcesByTypeEither.right().value()));
1907 List<GraphVertex> vertexList = resourcesByTypeEither.left().value();
1908 List<Component> components = new ArrayList<>();
1910 for (GraphVertex vertex : vertexList) {
1911 components.add(getToscaElementByOperation(vertex, filterBy).left().value());
1914 return Either.left(components);
1917 public void commit() {
1921 public Either<Service, StorageOperationStatus> updateDistributionStatus(Service service, User user, DistributionStatusEnum distributionStatus) {
1922 Either<GraphVertex, StorageOperationStatus> updateDistributionStatus = topologyTemplateOperation.updateDistributionStatus(service.getUniqueId(), user, distributionStatus);
1923 if (updateDistributionStatus.isRight()) {
1924 return Either.right(updateDistributionStatus.right().value());
1926 GraphVertex serviceV = updateDistributionStatus.left().value();
1927 service.setDistributionStatus(distributionStatus);
1928 service.setLastUpdateDate((Long) serviceV.getJsonMetadataField(JsonPresentationFields.LAST_UPDATE_DATE));
1929 return Either.left(service);
1932 public Either<ComponentMetadataData, StorageOperationStatus> updateComponentLastUpdateDateOnGraph(Component component, Long modificationTime) {
1934 Either<ComponentMetadataData, StorageOperationStatus> result = null;
1935 GraphVertex serviceVertex;
1936 Either<GraphVertex, TitanOperationStatus> updateRes = null;
1937 Either<GraphVertex, TitanOperationStatus> getRes = titanDao.getVertexById(component.getUniqueId(), JsonParseFlagEnum.ParseMetadata);
1938 if (getRes.isRight()) {
1939 TitanOperationStatus status = getRes.right().value();
1940 log.error("Failed to fetch component {}. status is {}", component.getUniqueId(), status);
1941 result = Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(status));
1943 if (result == null) {
1944 serviceVertex = getRes.left().value();
1945 long lastUpdateDate = System.currentTimeMillis();
1946 serviceVertex.setJsonMetadataField(JsonPresentationFields.LAST_UPDATE_DATE, lastUpdateDate);
1947 component.setLastUpdateDate(lastUpdateDate);
1948 updateRes = titanDao.updateVertex(serviceVertex);
1949 if (updateRes.isRight()) {
1950 result = Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(updateRes.right().value()));
1953 if (result == null) {
1954 result = Either.left(ModelConverter.convertToComponentMetadata(updateRes.left().value()));
1959 public TitanDao getTitanDao() {
1963 public Either<List<Service>, StorageOperationStatus> getCertifiedServicesWithDistStatus(Set<DistributionStatusEnum> distStatus) {
1964 Map<GraphPropertyEnum, Object> propertiesToMatch = new EnumMap<>(GraphPropertyEnum.class);
1965 propertiesToMatch.put(GraphPropertyEnum.STATE, LifecycleStateEnum.CERTIFIED.name());
1967 return getServicesWithDistStatus(distStatus, propertiesToMatch);
1970 public Either<List<Service>, StorageOperationStatus> getServicesWithDistStatus(Set<DistributionStatusEnum> distStatus, Map<GraphPropertyEnum, Object> additionalPropertiesToMatch) {
1972 List<Service> servicesAll = new ArrayList<>();
1974 Map<GraphPropertyEnum, Object> propertiesToMatch = new EnumMap<>(GraphPropertyEnum.class);
1975 Map<GraphPropertyEnum, Object> propertiesNotToMatch = new EnumMap<>(GraphPropertyEnum.class);
1977 if (additionalPropertiesToMatch != null && !additionalPropertiesToMatch.isEmpty()) {
1978 propertiesToMatch.putAll(additionalPropertiesToMatch);
1981 propertiesToMatch.put(GraphPropertyEnum.COMPONENT_TYPE, ComponentTypeEnum.SERVICE.name());
1983 propertiesNotToMatch.put(GraphPropertyEnum.IS_DELETED, true);
1985 if (distStatus != null && !distStatus.isEmpty()) {
1986 for (DistributionStatusEnum state : distStatus) {
1987 propertiesToMatch.put(GraphPropertyEnum.DISTRIBUTION_STATUS, state.name());
1988 Either<List<Service>, StorageOperationStatus> fetchServicesByCriteria = fetchServicesByCriteria(servicesAll, propertiesToMatch, propertiesNotToMatch);
1989 if (fetchServicesByCriteria.isRight()) {
1990 return fetchServicesByCriteria;
1992 servicesAll = fetchServicesByCriteria.left().value();
1995 return Either.left(servicesAll);
1997 return fetchServicesByCriteria(servicesAll, propertiesToMatch, propertiesNotToMatch);
2001 // private Either<List<Service>, StorageOperationStatus> fetchServicesByCriteria(List<Service> servicesAll, Map<GraphPropertyEnum, Object> propertiesToMatch, Map<GraphPropertyEnum, Object> propertiesNotToMatch) {
2002 // Either<List<GraphVertex>, TitanOperationStatus> getRes = titanDao.getByCriteria(VertexTypeEnum.TOPOLOGY_TEMPLATE, propertiesToMatch, propertiesNotToMatch, JsonParseFlagEnum.ParseAll);
2003 // if (getRes.isRight()) {
2004 // if (getRes.right().value() != TitanOperationStatus.NOT_FOUND) {
2005 // CommonUtility.addRecordToLog(log, LogLevelEnum.DEBUG, "Failed to fetch certified services by match properties {} not match properties {} . Status is {}. ", propertiesToMatch, propertiesNotToMatch, getRes.right().value());
2006 // return Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(getRes.right().value()));
2009 // for (GraphVertex vertex : getRes.left().value()) {
2010 // Either<Component, StorageOperationStatus> getServiceRes = getToscaElementByOperation(vertex);
2011 // if (getServiceRes.isRight()) {
2012 // CommonUtility.addRecordToLog(log, LogLevelEnum.DEBUG, "Failed to fetch certified service {}. Status is {}. ", vertex.getJsonMetadataField(JsonPresentationFields.NAME), getServiceRes.right().value());
2013 // return Either.right(getServiceRes.right().value());
2015 // servicesAll.add((Service) getToscaElementByOperation(vertex).left().value());
2019 // return Either.left(servicesAll);
2022 private Either<List<Service>, StorageOperationStatus> fetchServicesByCriteria(List<Service> servicesAll, Map<GraphPropertyEnum, Object> propertiesToMatch, Map<GraphPropertyEnum, Object> propertiesNotToMatch) {
2023 Either<List<GraphVertex>, TitanOperationStatus> getRes = titanDao.getByCriteria(VertexTypeEnum.TOPOLOGY_TEMPLATE, propertiesToMatch, propertiesNotToMatch, JsonParseFlagEnum.ParseAll);
2024 if (getRes.isRight()) {
2025 if (getRes.right().value() != TitanOperationStatus.NOT_FOUND) {
2026 CommonUtility.addRecordToLog(log, LogLevelEnum.DEBUG, "Failed to fetch certified services by match properties {} not match properties {} . Status is {}. ", propertiesToMatch, propertiesNotToMatch, getRes.right().value());
2027 return Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(getRes.right().value()));
2030 for (GraphVertex vertex : getRes.left().value()) {
2031 // Either<Component, StorageOperationStatus> getServiceRes = getToscaElementByOperation(vertex);
2032 Either<ToscaElement, StorageOperationStatus> getServiceRes = topologyTemplateOperation.getLightComponent(vertex, ComponentTypeEnum.SERVICE, new ComponentParametersView(true));
2034 if (getServiceRes.isRight()) {
2035 CommonUtility.addRecordToLog(log, LogLevelEnum.DEBUG, "Failed to fetch certified service {}. Status is {}. ", vertex.getJsonMetadataField(JsonPresentationFields.NAME), getServiceRes.right().value());
2036 return Either.right(getServiceRes.right().value());
2038 servicesAll.add(ModelConverter.convertFromToscaElement(getServiceRes.left().value()));
2042 return Either.left(servicesAll);
2045 public void rollback() {
2046 titanDao.rollback();
2049 public StorageOperationStatus addDeploymentArtifactsToInstance(String componentId, ComponentInstance componentInstance, Map<String, ArtifactDefinition> finalDeploymentArtifacts) {
2050 Map<String, ArtifactDataDefinition> instDeplArtifacts = finalDeploymentArtifacts.entrySet().stream().collect(Collectors.toMap(Map.Entry::getKey, e -> new ArtifactDataDefinition(e.getValue())));
2052 return nodeTemplateOperation.addDeploymentArtifactsToInstance(componentId, componentInstance.getUniqueId(), instDeplArtifacts);
2055 public StorageOperationStatus addInformationalArtifactsToInstance(String componentId, ComponentInstance componentInstance, Map<String, ArtifactDefinition> artifacts) {
2056 StorageOperationStatus status = StorageOperationStatus.OK;
2057 if (MapUtils.isNotEmpty(artifacts)) {
2058 Map<String, ArtifactDataDefinition> instDeplArtifacts = artifacts.entrySet().stream().collect(Collectors.toMap(Map.Entry::getKey, e -> new ArtifactDataDefinition(e.getValue())));
2059 status = nodeTemplateOperation.addInformationalArtifactsToInstance(componentId, componentInstance.getUniqueId(), instDeplArtifacts);
2064 public StorageOperationStatus generateCustomizationUUIDOnInstance(String componentId, String instanceId) {
2065 return nodeTemplateOperation.generateCustomizationUUIDOnInstance(componentId, instanceId);
2068 public StorageOperationStatus generateCustomizationUUIDOnInstanceGroup(String componentId, String instanceId, List<String> groupInstances) {
2069 return nodeTemplateOperation.generateCustomizationUUIDOnInstanceGroup(componentId, instanceId, groupInstances);
2073 * adds property to a resource
2074 * @warn this method has SIDE EFFECT on ownerId ,use it with caution
2076 public Either<PropertyDefinition, StorageOperationStatus> addPropertyToResource(String propertyName, PropertyDefinition newPropertyDefinition, Resource resource) {
2078 Either<PropertyDefinition, StorageOperationStatus> result = null;
2079 Either<Component, StorageOperationStatus> getUpdatedComponentRes = null;
2080 newPropertyDefinition.setName(propertyName);
2081 // 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
2082 StorageOperationStatus status = getToscaElementOperation(resource).addToscaDataToToscaElement(resource.getUniqueId(), EdgeLabelEnum.PROPERTIES, VertexTypeEnum.PROPERTIES, newPropertyDefinition, JsonPresentationFields.NAME);
2083 if (status != StorageOperationStatus.OK) {
2084 CommonUtility.addRecordToLog(log, LogLevelEnum.DEBUG, "Failed to add the property {} to the resource {}. Status is {}. ", propertyName, resource.getName(), status);
2085 result = Either.right(status);
2087 if (result == null) {
2088 ComponentParametersView filter = new ComponentParametersView(true);
2089 filter.setIgnoreProperties(false);
2090 getUpdatedComponentRes = getToscaElement(resource.getUniqueId(), filter);
2091 if (getUpdatedComponentRes.isRight()) {
2092 CommonUtility.addRecordToLog(log, LogLevelEnum.DEBUG, "Failed to get updated resource {}. Status is {}. ", resource.getUniqueId(), getUpdatedComponentRes.right().value());
2093 result = Either.right(status);
2096 if (result == null) {
2097 PropertyDefinition newProperty = null;
2098 List<PropertyDefinition> properties = ((Resource) getUpdatedComponentRes.left().value()).getProperties();
2099 if (CollectionUtils.isNotEmpty(properties)) {
2100 Optional<PropertyDefinition> newPropertyOptional = properties.stream().filter(p -> p.getName().equals(propertyName)).findAny();
2101 if (newPropertyOptional.isPresent()) {
2102 newProperty = newPropertyOptional.get();
2105 if (newProperty == null) {
2106 CommonUtility.addRecordToLog(log, LogLevelEnum.DEBUG, "Failed to find recently added property {} on the resource {}. Status is {}. ", propertyName, resource.getUniqueId(), StorageOperationStatus.NOT_FOUND);
2107 result = Either.right(StorageOperationStatus.NOT_FOUND);
2109 result = Either.left(newProperty);
2115 public StorageOperationStatus deletePropertyOfResource(Resource resource, String propertyName) {
2116 return getToscaElementOperation(resource).deleteToscaDataElement(resource.getUniqueId(), EdgeLabelEnum.PROPERTIES, VertexTypeEnum.PROPERTIES, propertyName, JsonPresentationFields.NAME);
2119 public StorageOperationStatus deleteAttributeOfResource(Component component, String attributeName) {
2120 return getToscaElementOperation(component).deleteToscaDataElement(component.getUniqueId(), EdgeLabelEnum.ATTRIBUTES, VertexTypeEnum.ATTRIBUTES, attributeName, JsonPresentationFields.NAME);
2123 public StorageOperationStatus deleteInputOfResource(Component resource, String inputName) {
2124 return getToscaElementOperation(resource).deleteToscaDataElement(resource.getUniqueId(), EdgeLabelEnum.INPUTS, VertexTypeEnum.INPUTS, inputName, JsonPresentationFields.NAME);
2127 public Either<PropertyDefinition, StorageOperationStatus> updatePropertyOfResource(Resource resource, PropertyDefinition newPropertyDefinition) {
2129 Either<Component, StorageOperationStatus> getUpdatedComponentRes = null;
2130 Either<PropertyDefinition, StorageOperationStatus> result = null;
2131 StorageOperationStatus status = getToscaElementOperation(resource).updateToscaDataOfToscaElement(resource.getUniqueId(), EdgeLabelEnum.PROPERTIES, VertexTypeEnum.PROPERTIES, newPropertyDefinition, JsonPresentationFields.NAME);
2132 if (status != StorageOperationStatus.OK) {
2133 CommonUtility.addRecordToLog(log, LogLevelEnum.DEBUG, "Failed to add the property {} to the resource {}. Status is {}. ", newPropertyDefinition.getName(), resource.getName(), status);
2134 result = Either.right(status);
2136 if (result == null) {
2137 ComponentParametersView filter = new ComponentParametersView(true);
2138 filter.setIgnoreProperties(false);
2139 getUpdatedComponentRes = getToscaElement(resource.getUniqueId(), filter);
2140 if (getUpdatedComponentRes.isRight()) {
2141 CommonUtility.addRecordToLog(log, LogLevelEnum.DEBUG, "Failed to get updated resource {}. Status is {}. ", resource.getUniqueId(), getUpdatedComponentRes.right().value());
2142 result = Either.right(status);
2145 if (result == null) {
2146 Optional<PropertyDefinition> newProperty = ((Resource) getUpdatedComponentRes.left().value()).getProperties().stream().filter(p -> p.getName().equals(newPropertyDefinition.getName())).findAny();
2147 if (newProperty.isPresent()) {
2148 result = Either.left(newProperty.get());
2150 CommonUtility.addRecordToLog(log, LogLevelEnum.DEBUG, "Failed to find recently added property {} on the resource {}. Status is {}. ", newPropertyDefinition.getName(), resource.getUniqueId(), StorageOperationStatus.NOT_FOUND);
2151 result = Either.right(StorageOperationStatus.NOT_FOUND);
2157 public Either<PropertyDefinition, StorageOperationStatus> addAttributeOfResource(Component component, PropertyDefinition newAttributeDef) {
2159 Either<Component, StorageOperationStatus> getUpdatedComponentRes = null;
2160 Either<PropertyDefinition, StorageOperationStatus> result = null;
2161 if (newAttributeDef.getUniqueId() == null || newAttributeDef.getUniqueId().isEmpty()) {
2162 String attUniqueId = UniqueIdBuilder.buildAttributeUid(component.getUniqueId(), newAttributeDef.getName());
2163 newAttributeDef.setUniqueId(attUniqueId);
2166 StorageOperationStatus status = getToscaElementOperation(component).addToscaDataToToscaElement(component.getUniqueId(), EdgeLabelEnum.ATTRIBUTES, VertexTypeEnum.ATTRIBUTES, newAttributeDef, JsonPresentationFields.NAME);
2167 if (status != StorageOperationStatus.OK) {
2168 CommonUtility.addRecordToLog(log, LogLevelEnum.DEBUG, "Failed to add the property {} to the resource {}. Status is {}. ", newAttributeDef.getName(), component.getName(), status);
2169 result = Either.right(status);
2171 if (result == null) {
2172 ComponentParametersView filter = new ComponentParametersView(true);
2173 filter.setIgnoreAttributesFrom(false);
2174 getUpdatedComponentRes = getToscaElement(component.getUniqueId(), filter);
2175 if (getUpdatedComponentRes.isRight()) {
2176 CommonUtility.addRecordToLog(log, LogLevelEnum.DEBUG, "Failed to get updated resource {}. Status is {}. ", component.getUniqueId(), getUpdatedComponentRes.right().value());
2177 result = Either.right(status);
2180 if (result == null) {
2181 Optional<PropertyDefinition> newAttribute = ((Resource) getUpdatedComponentRes.left().value()).getAttributes().stream().filter(p -> p.getName().equals(newAttributeDef.getName())).findAny();
2182 if (newAttribute.isPresent()) {
2183 result = Either.left(newAttribute.get());
2185 CommonUtility.addRecordToLog(log, LogLevelEnum.DEBUG, "Failed to find recently added property {} on the resource {}. Status is {}. ", newAttributeDef.getName(), component.getUniqueId(), StorageOperationStatus.NOT_FOUND);
2186 result = Either.right(StorageOperationStatus.NOT_FOUND);
2192 public Either<PropertyDefinition, StorageOperationStatus> updateAttributeOfResource(Component component, PropertyDefinition newAttributeDef) {
2194 Either<Component, StorageOperationStatus> getUpdatedComponentRes = null;
2195 Either<PropertyDefinition, StorageOperationStatus> result = null;
2196 StorageOperationStatus status = getToscaElementOperation(component).updateToscaDataOfToscaElement(component.getUniqueId(), EdgeLabelEnum.ATTRIBUTES, VertexTypeEnum.ATTRIBUTES, newAttributeDef, JsonPresentationFields.NAME);
2197 if (status != StorageOperationStatus.OK) {
2198 CommonUtility.addRecordToLog(log, LogLevelEnum.DEBUG, "Failed to add the property {} to the resource {}. Status is {}. ", newAttributeDef.getName(), component.getName(), status);
2199 result = Either.right(status);
2201 if (result == null) {
2202 ComponentParametersView filter = new ComponentParametersView(true);
2203 filter.setIgnoreAttributesFrom(false);
2204 getUpdatedComponentRes = getToscaElement(component.getUniqueId(), filter);
2205 if (getUpdatedComponentRes.isRight()) {
2206 CommonUtility.addRecordToLog(log, LogLevelEnum.DEBUG, "Failed to get updated resource {}. Status is {}. ", component.getUniqueId(), getUpdatedComponentRes.right().value());
2207 result = Either.right(status);
2210 if (result == null) {
2211 Optional<PropertyDefinition> newProperty = ((Resource) getUpdatedComponentRes.left().value()).getAttributes().stream().filter(p -> p.getName().equals(newAttributeDef.getName())).findAny();
2212 if (newProperty.isPresent()) {
2213 result = Either.left(newProperty.get());
2215 CommonUtility.addRecordToLog(log, LogLevelEnum.DEBUG, "Failed to find recently added property {} on the resource {}. Status is {}. ", newAttributeDef.getName(), component.getUniqueId(), StorageOperationStatus.NOT_FOUND);
2216 result = Either.right(StorageOperationStatus.NOT_FOUND);
2222 public Either<InputDefinition, StorageOperationStatus> updateInputOfComponent(Component component, InputDefinition newInputDefinition) {
2224 Either<Component, StorageOperationStatus> getUpdatedComponentRes = null;
2225 Either<InputDefinition, StorageOperationStatus> result = null;
2226 StorageOperationStatus status = getToscaElementOperation(component).updateToscaDataOfToscaElement(component.getUniqueId(), EdgeLabelEnum.INPUTS, VertexTypeEnum.INPUTS, newInputDefinition, JsonPresentationFields.NAME);
2227 if (status != StorageOperationStatus.OK) {
2228 CommonUtility.addRecordToLog(log, LogLevelEnum.DEBUG, "Failed to update the input {} to the component {}. Status is {}. ", newInputDefinition.getName(), component.getName(), status);
2229 result = Either.right(status);
2231 if (result == null) {
2232 ComponentParametersView filter = new ComponentParametersView(true);
2233 filter.setIgnoreInputs(false);
2234 getUpdatedComponentRes = getToscaElement(component.getUniqueId(), filter);
2235 if (getUpdatedComponentRes.isRight()) {
2236 CommonUtility.addRecordToLog(log, LogLevelEnum.DEBUG, "Failed to get updated resource {}. Status is {}. ", component.getUniqueId(), getUpdatedComponentRes.right().value());
2237 result = Either.right(status);
2240 if (result == null) {
2241 Optional<InputDefinition> updatedInput = getUpdatedComponentRes.left().value().getInputs().stream().filter(p -> p.getName().equals(newInputDefinition.getName())).findAny();
2242 if (updatedInput.isPresent()) {
2243 result = Either.left(updatedInput.get());
2245 CommonUtility.addRecordToLog(log, LogLevelEnum.DEBUG, "Failed to find recently updated inputs {} on the resource {}. Status is {}. ", newInputDefinition.getName(), component.getUniqueId(), StorageOperationStatus.NOT_FOUND);
2246 result = Either.right(StorageOperationStatus.NOT_FOUND);
2253 * method - ename the group instances after referenced container name renamed flow - VF rename -(triggers)-> Group rename
2255 * @param containerComponent
2256 * - container such as service
2257 * @param componentInstance
2258 * - context component
2259 * @param componentInstanceId
2262 * @return - successfull/failed status
2264 public Either<StorageOperationStatus, StorageOperationStatus> cleanAndAddGroupInstancesToComponentInstance(Component containerComponent, ComponentInstance componentInstance, String componentInstanceId) {
2265 String uniqueId = componentInstance.getUniqueId();
2266 StorageOperationStatus status = nodeTemplateOperation.deleteToscaDataDeepElementsBlockToToscaElement(containerComponent.getUniqueId(), EdgeLabelEnum.INST_GROUPS, VertexTypeEnum.INST_GROUPS, uniqueId);
2267 if (status != StorageOperationStatus.OK && status != StorageOperationStatus.NOT_FOUND) {
2268 CommonUtility.addRecordToLog(log, LogLevelEnum.DEBUG, "Failed to delete group instances for container {}. error {] ", componentInstanceId, status);
2269 return Either.right(status);
2271 if (componentInstance.getGroupInstances() != null) {
2272 status = addGroupInstancesToComponentInstance(containerComponent, componentInstance, componentInstance.getGroupInstances());
2273 if (status != StorageOperationStatus.OK && status != StorageOperationStatus.NOT_FOUND) {
2274 CommonUtility.addRecordToLog(log, LogLevelEnum.DEBUG, "Failed to add group instances for container {}. error {] ", componentInstanceId, status);
2275 return Either.right(status);
2278 return Either.left(status);
2281 public StorageOperationStatus addGroupInstancesToComponentInstance(Component containerComponent, ComponentInstance componentInstance, List<GroupDefinition> groups, Map<String, List<ArtifactDefinition>> groupInstancesArtifacts) {
2282 return nodeTemplateOperation.addGroupInstancesToComponentInstance(containerComponent, componentInstance, groups, groupInstancesArtifacts);
2285 public Either<List<GroupDefinition>, StorageOperationStatus> updateGroupsOnComponent(Component component, List<GroupDataDefinition> updatedGroups) {
2286 return groupsOperation.updateGroups(component, updatedGroups);
2289 public Either<List<GroupInstance>, StorageOperationStatus> updateGroupInstancesOnComponent(Component component, ComponentTypeEnum componentType, String instanceId, List<GroupInstance> updatedGroupInstances) {
2290 return groupsOperation.updateGroupInstances(component, instanceId, updatedGroupInstances);
2293 public StorageOperationStatus addGroupInstancesToComponentInstance(Component containerComponent, ComponentInstance componentInstance, List<GroupInstance> groupInstances) {
2294 return nodeTemplateOperation.addGroupInstancesToComponentInstance(containerComponent, componentInstance, groupInstances);
2297 public StorageOperationStatus addDeploymentArtifactsToComponentInstance(Component containerComponent, ComponentInstance componentInstance, Map<String, ArtifactDefinition> deploymentArtifacts) {
2298 return nodeTemplateOperation.addDeploymentArtifactsToComponentInstance(containerComponent, componentInstance, deploymentArtifacts);
2301 public StorageOperationStatus updateComponentInstanceProperty(Component containerComponent, String componentInstanceId, ComponentInstanceProperty property) {
2302 return nodeTemplateOperation.updateComponentInstanceProperty(containerComponent, componentInstanceId, property);
2305 public StorageOperationStatus updateComponentInstanceProperties(Component containerComponent, String componentInstanceId, List<ComponentInstanceProperty> properties) {
2306 return nodeTemplateOperation.updateComponentInstanceProperties(containerComponent, componentInstanceId, properties);
2310 public StorageOperationStatus addComponentInstanceProperty(Component containerComponent, String componentInstanceId, ComponentInstanceProperty property) {
2311 return nodeTemplateOperation.addComponentInstanceProperty(containerComponent, componentInstanceId, property);
2314 public StorageOperationStatus updateComponentInstanceInput(Component containerComponent, String componentInstanceId, ComponentInstanceInput property) {
2315 return nodeTemplateOperation.updateComponentInstanceInput(containerComponent, componentInstanceId, property);
2318 public StorageOperationStatus updateComponentInstanceInputs(Component containerComponent, String componentInstanceId, List<ComponentInstanceInput> instanceInputs) {
2319 return nodeTemplateOperation.updateComponentInstanceInputs(containerComponent, componentInstanceId, instanceInputs);
2322 public StorageOperationStatus addComponentInstanceInput(Component containerComponent, String componentInstanceId, ComponentInstanceInput property) {
2323 return nodeTemplateOperation.addComponentInstanceInput(containerComponent, componentInstanceId, property);
2326 public void setNodeTypeOperation(NodeTypeOperation nodeTypeOperation) {
2327 this.nodeTypeOperation = nodeTypeOperation;
2330 public void setTopologyTemplateOperation(TopologyTemplateOperation topologyTemplateOperation) {
2331 this.topologyTemplateOperation = topologyTemplateOperation;
2334 public StorageOperationStatus deleteComponentInstanceInputsFromTopologyTemplate(Component containerComponent, ComponentTypeEnum componentType, List<InputDefinition> inputsToDelete) {
2335 return topologyTemplateOperation.deleteToscaDataElements(containerComponent.getUniqueId(), EdgeLabelEnum.INPUTS, inputsToDelete.stream().map(i -> i.getName()).collect(Collectors.toList()));
2338 public StorageOperationStatus updateComponentInstanceCapabiltyProperty(Component containerComponent, String componentInstanceUniqueId, String capabilityUniqueId, ComponentInstanceProperty property) {
2339 return nodeTemplateOperation.updateComponentInstanceCapabilityProperty(containerComponent, componentInstanceUniqueId, capabilityUniqueId, property);
2342 public StorageOperationStatus updateComponentInstanceCapabilityProperties(Component containerComponent, String componentInstanceUniqueId) {
2343 return convertComponentInstanceProperties(containerComponent, componentInstanceUniqueId)
2344 .map(instanceCapProps -> topologyTemplateOperation.updateComponentInstanceCapabilityProperties(containerComponent, componentInstanceUniqueId, instanceCapProps))
2345 .orElse(StorageOperationStatus.NOT_FOUND);
2348 public StorageOperationStatus updateComponentCalculatedCapabilitiesProperties(Component containerComponent) {
2349 Map<String, MapCapabiltyProperty> mapCapabiltyPropertyMap = convertComponentCapabilitiesProperties(containerComponent);
2350 return nodeTemplateOperation.overrideComponentCapabilitiesProperties(containerComponent, mapCapabiltyPropertyMap);
2353 public StorageOperationStatus deleteAllCalculatedCapabilitiesRequirements(String topologyTemplateId) {
2354 StorageOperationStatus status = topologyTemplateOperation.removeToscaData(topologyTemplateId, EdgeLabelEnum.CALCULATED_CAPABILITIES, VertexTypeEnum.CALCULATED_CAPABILITIES);
2355 if (status == StorageOperationStatus.OK) {
2356 status = topologyTemplateOperation.removeToscaData(topologyTemplateId, EdgeLabelEnum.CALCULATED_REQUIREMENTS, VertexTypeEnum.CALCULATED_REQUIREMENTS);
2358 if(status == StorageOperationStatus.OK){
2359 status = topologyTemplateOperation.removeToscaData(topologyTemplateId, EdgeLabelEnum.CALCULATED_CAP_PROPERTIES, VertexTypeEnum.CALCULATED_CAP_PROPERTIES);
2364 public Either<Component, StorageOperationStatus> shouldUpgradeToLatestDerived(Resource clonedResource) {
2365 String componentId = clonedResource.getUniqueId();
2366 Either<GraphVertex, TitanOperationStatus> getVertexEither = titanDao.getVertexById(componentId, JsonParseFlagEnum.NoParse);
2367 if (getVertexEither.isRight()) {
2368 log.debug("Couldn't fetch component with and unique id {}, error: {}", componentId, getVertexEither.right().value());
2369 return Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(getVertexEither.right().value()));
2372 GraphVertex nodeTypeV = getVertexEither.left().value();
2374 ToscaElement toscaElementToUpdate = ModelConverter.convertToToscaElement(clonedResource);
2376 Either<ToscaElement, StorageOperationStatus> shouldUpdateDerivedVersion = nodeTypeOperation.shouldUpdateDerivedVersion(toscaElementToUpdate, nodeTypeV);
2377 if ( shouldUpdateDerivedVersion.isRight() && StorageOperationStatus.OK != shouldUpdateDerivedVersion.right().value() ){
2378 log.debug("Failed to update derived version for node type {} derived {}, error: {}", componentId, clonedResource.getDerivedFrom().get(0), shouldUpdateDerivedVersion.right().value());
2379 return Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(getVertexEither.right().value()));
2381 if ( shouldUpdateDerivedVersion.isLeft() ){
2382 return Either.left(ModelConverter.convertFromToscaElement(shouldUpdateDerivedVersion.left().value()));
2384 return Either.left(clonedResource);
2387 * Returns list of ComponentInstanceProperty belonging to component instance capability specified by name, type and ownerId
2388 * @param componentId
2390 * @param capabilityName
2391 * @param capabilityType
2395 public Either<List<ComponentInstanceProperty>, StorageOperationStatus> getComponentInstanceCapabilityProperties(String componentId, String instanceId, String capabilityName, String capabilityType, String ownerId) {
2396 return topologyTemplateOperation.getComponentInstanceCapabilityProperties(componentId, instanceId, capabilityName, capabilityType, ownerId);
2399 private Map<String, MapCapabiltyProperty> convertComponentCapabilitiesProperties(Component currComponent) {
2400 return currComponent.getComponentInstances()
2402 .collect(Collectors.toMap(ComponentInstanceDataDefinition::getUniqueId,
2403 ci -> ModelConverter.convertToMapOfMapCapabiltyProperties(ci.getCapabilities(), ci.getUniqueId(), true)));
2406 private Optional<MapCapabiltyProperty> convertComponentInstanceProperties(Component component, String instanceId) {
2407 return component.fetchInstanceById(instanceId)
2408 .map(ci -> ModelConverter.convertToMapOfMapCapabiltyProperties(ci.getCapabilities(),instanceId));
2411 public Either<PolicyDefinition, StorageOperationStatus> associatePolicyToComponent(String componentId, PolicyDefinition policyDefinition, int counter) {
2412 Either<PolicyDefinition, StorageOperationStatus> result = null;
2413 Either<GraphVertex, TitanOperationStatus> getVertexEither;
2414 getVertexEither = titanDao.getVertexById(componentId, JsonParseFlagEnum.ParseMetadata);
2415 if (getVertexEither.isRight()) {
2416 log.error("Couldn't fetch a component with and UniqueId {}, error: {}", componentId, getVertexEither.right().value());
2417 result = Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(getVertexEither.right().value()));
2419 if(getVertexEither.left().value().getLabel() != VertexTypeEnum.TOPOLOGY_TEMPLATE){
2420 log.error("Policy association to component of Tosca type {} is not allowed. ", getVertexEither.left().value().getLabel());
2421 result = Either.right(StorageOperationStatus.BAD_REQUEST);
2425 StorageOperationStatus status = topologyTemplateOperation.addPolicyToToscaElement(getVertexEither.left().value(), policyDefinition, counter);
2426 if(status != StorageOperationStatus.OK){
2427 return Either.right(status);
2431 result = Either.left(policyDefinition);
2436 public Either<PolicyDefinition, StorageOperationStatus> updatePolicyOfComponent(String componentId, PolicyDefinition policyDefinition) {
2437 Either<PolicyDefinition, StorageOperationStatus> result = null;
2438 Either<GraphVertex, TitanOperationStatus> getVertexEither;
2439 getVertexEither = titanDao.getVertexById(componentId, JsonParseFlagEnum.NoParse);
2440 if (getVertexEither.isRight()) {
2441 log.error("Couldn't fetch a component with and UniqueId {}, error: {}", componentId, getVertexEither.right().value());
2442 result = Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(getVertexEither.right().value()));
2445 StorageOperationStatus status = topologyTemplateOperation.updatePolicyOfToscaElement(getVertexEither.left().value(), policyDefinition);
2446 if(status != StorageOperationStatus.OK){
2447 return Either.right(status);
2451 result = Either.left(policyDefinition);
2456 public StorageOperationStatus updatePoliciesOfComponent(String componentId, List<PolicyDefinition> policyDefinition) {
2457 log.debug("#updatePoliciesOfComponent - updating policies for component {}", componentId);
2458 return titanDao.getVertexById(componentId, JsonParseFlagEnum.NoParse)
2460 .map(DaoStatusConverter::convertTitanStatusToStorageStatus)
2461 .either(containerVertex -> topologyTemplateOperation.updatePoliciesOfToscaElement(containerVertex, policyDefinition),
2465 public StorageOperationStatus removePolicyFromComponent(String componentId, String policyId) {
2466 StorageOperationStatus status = null;
2467 Either<GraphVertex, TitanOperationStatus> getVertexEither = titanDao.getVertexById(componentId, JsonParseFlagEnum.NoParse);
2468 if (getVertexEither.isRight()) {
2469 log.error("Couldn't fetch a component with and UniqueId {}, error: {}", componentId, getVertexEither.right().value());
2470 status = DaoStatusConverter.convertTitanStatusToStorageStatus(getVertexEither.right().value());
2473 status = topologyTemplateOperation.removePolicyFromToscaElement(getVertexEither.left().value(), policyId);