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;
24 import fj.data.Either;
25 import java.util.Map.Entry;
26 import java.util.stream.Collectors;
27 import org.apache.commons.collections.CollectionUtils;
28 import org.apache.commons.collections.MapUtils;
29 import org.apache.commons.lang3.StringUtils;
30 import org.apache.commons.lang3.tuple.ImmutablePair;
31 import org.apache.commons.lang3.tuple.Pair;
32 import org.openecomp.sdc.be.dao.jsongraph.GraphVertex;
33 import org.openecomp.sdc.be.dao.jsongraph.TitanDao;
34 import org.openecomp.sdc.be.dao.jsongraph.types.EdgeLabelEnum;
35 import org.openecomp.sdc.be.dao.jsongraph.types.JsonParseFlagEnum;
36 import org.openecomp.sdc.be.dao.jsongraph.types.VertexTypeEnum;
37 import org.openecomp.sdc.be.dao.titan.TitanOperationStatus;
38 import org.openecomp.sdc.be.datatypes.components.ComponentMetadataDataDefinition;
39 import org.openecomp.sdc.be.datatypes.components.ResourceMetadataDataDefinition;
40 import org.openecomp.sdc.be.datatypes.elements.*;
41 import org.openecomp.sdc.be.datatypes.enums.*;
42 import org.openecomp.sdc.be.model.*;
43 import org.openecomp.sdc.be.model.jsontitan.datamodel.TopologyTemplate;
44 import org.openecomp.sdc.be.model.jsontitan.datamodel.ToscaElement;
45 import org.openecomp.sdc.be.model.jsontitan.utils.ModelConverter;
46 import org.openecomp.sdc.be.model.operations.api.StorageOperationStatus;
47 import org.openecomp.sdc.be.model.operations.impl.DaoStatusConverter;
48 import org.openecomp.sdc.be.model.operations.impl.UniqueIdBuilder;
49 import org.openecomp.sdc.be.resources.data.ComponentMetadataData;
50 import org.openecomp.sdc.be.utils.CommonBeUtils;
51 import org.openecomp.sdc.common.jsongraph.util.CommonUtility;
52 import org.openecomp.sdc.common.jsongraph.util.CommonUtility.LogLevelEnum;
53 import org.openecomp.sdc.common.util.ValidationUtils;
54 import org.slf4j.Logger;
55 import org.slf4j.LoggerFactory;
56 import org.springframework.beans.factory.annotation.Autowired;
59 import java.util.Map.Entry;
60 import java.util.stream.Collectors;
62 @org.springframework.stereotype.Component("tosca-operation-facade")
63 public class ToscaOperationFacade {
65 private NodeTypeOperation nodeTypeOperation;
67 private TopologyTemplateOperation topologyTemplateOperation;
69 private NodeTemplateOperation nodeTemplateOperation;
71 private GroupsOperation groupsOperation;
73 private TitanDao titanDao;
75 private static Logger log = LoggerFactory.getLogger(ToscaOperationFacade.class.getName());
77 public <T extends Component> Either<T, StorageOperationStatus> getToscaElement(String componentId) {
79 return getToscaElement(componentId, JsonParseFlagEnum.ParseAll);
83 public <T extends Component> Either<T, StorageOperationStatus> getToscaFullElement(String componentId) {
84 ComponentParametersView filters = new ComponentParametersView();
85 filters.setIgnoreCapabiltyProperties(false);
87 return getToscaElement(componentId, filters);
90 public <T extends Component> Either<T, StorageOperationStatus> getToscaElement(String componentId, ComponentParametersView filters) {
92 Either<GraphVertex, TitanOperationStatus> getVertexEither = titanDao.getVertexById(componentId, filters.detectParseFlag());
93 if (getVertexEither.isRight()) {
94 log.debug("Couldn't fetch component with and unique id {}, error: {}", componentId, getVertexEither.right().value());
95 return Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(getVertexEither.right().value()));
98 return getToscaElementByOperation(getVertexEither.left().value(), filters);
101 public <T extends Component> Either<T, StorageOperationStatus> getToscaElement(String componentId, JsonParseFlagEnum parseFlag) {
103 Either<GraphVertex, TitanOperationStatus> getVertexEither = titanDao.getVertexById(componentId, parseFlag);
104 if (getVertexEither.isRight()) {
105 log.debug("Couldn't fetch component with and unique id {}, error: {}", componentId, getVertexEither.right().value());
106 return Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(getVertexEither.right().value()));
109 return getToscaElementByOperation(getVertexEither.left().value());
112 public <T extends Component> Either<T, StorageOperationStatus> getToscaElement(GraphVertex componentVertex) {
113 return getToscaElementByOperation(componentVertex);
116 public Either<Boolean, StorageOperationStatus> validateComponentExists(String componentId) {
118 Either<GraphVertex, TitanOperationStatus> getVertexEither = titanDao.getVertexById(componentId, JsonParseFlagEnum.NoParse);
119 if (getVertexEither.isRight()) {
120 TitanOperationStatus status = getVertexEither.right().value();
121 if (status == TitanOperationStatus.NOT_FOUND) {
122 return Either.left(false);
124 log.debug("Couldn't fetch component with and unique id {}, error: {}", componentId, getVertexEither.right().value());
125 return Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(getVertexEither.right().value()));
128 return Either.left(true);
131 public <T extends Component> Either<T, StorageOperationStatus> findLastCertifiedToscaElementByUUID(T component) {
132 Map<GraphPropertyEnum, Object> props = new HashMap<>();
133 props.put(GraphPropertyEnum.UUID, component.getUUID());
134 props.put(GraphPropertyEnum.STATE, LifecycleStateEnum.CERTIFIED.name());
135 props.put(GraphPropertyEnum.IS_HIGHEST_VERSION, true);
137 Either<List<GraphVertex>, TitanOperationStatus> getVertexEither = titanDao.getByCriteria(ModelConverter.getVertexType(component), props);
138 if (getVertexEither.isRight()) {
139 log.debug("Couldn't fetch component with and unique id {}, error: {}", component.getUniqueId(), getVertexEither.right().value());
140 return Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(getVertexEither.right().value()));
143 return getToscaElementByOperation(getVertexEither.left().value().get(0));
146 private <T extends Component> Either<T, StorageOperationStatus> getToscaElementByOperation(GraphVertex componentV) {
147 return getToscaElementByOperation(componentV, new ComponentParametersView());
150 private <T extends Component> Either<T, StorageOperationStatus> getToscaElementByOperation(GraphVertex componentV, ComponentParametersView filters) {
151 VertexTypeEnum label = componentV.getLabel();
153 ToscaElementOperation toscaOperation = getToscaElementOperation(componentV);
154 Either<ToscaElement, StorageOperationStatus> toscaElement;
155 String componentId = componentV.getUniqueId();
156 if (toscaOperation != null) {
157 log.debug("Need to fetch tosca element for id {}", componentId);
158 toscaElement = toscaOperation.getToscaElement(componentV, filters);
160 log.debug("not supported tosca type {} for id {}", label, componentId);
161 toscaElement = Either.right(StorageOperationStatus.BAD_REQUEST);
163 if (toscaElement.isRight()) {
164 return Either.right(toscaElement.right().value());
166 return Either.left(ModelConverter.convertFromToscaElement(toscaElement.left().value()));
169 private ToscaElementOperation getToscaElementOperation(GraphVertex componentV) {
170 VertexTypeEnum label = componentV.getLabel();
173 return nodeTypeOperation;
174 case TOPOLOGY_TEMPLATE:
175 return topologyTemplateOperation;
186 public <T extends Component> Either<T, StorageOperationStatus> createToscaComponent(T resource) {
187 ToscaElement toscaElement = ModelConverter.convertToToscaElement(resource);
189 ToscaElementOperation toscaElementOperation = getToscaElementOperation(resource);
190 Either<ToscaElement, StorageOperationStatus> createToscaElement = toscaElementOperation.createToscaElement(toscaElement);
191 if (createToscaElement.isLeft()) {
192 log.debug("Component created successfully!!!");
193 T dataModel = ModelConverter.convertFromToscaElement(createToscaElement.left().value());
194 return Either.left(dataModel);
196 return Either.right(createToscaElement.right().value());
201 * @param componentToDelete
204 public StorageOperationStatus markComponentToDelete(Component componentToDelete) {
206 if ((componentToDelete.getIsDeleted() != null) && componentToDelete.getIsDeleted() && !componentToDelete.isHighestVersion()) {
207 // component already marked for delete
208 return StorageOperationStatus.OK;
211 Either<GraphVertex, TitanOperationStatus> getResponse = titanDao.getVertexById(componentToDelete.getUniqueId(), JsonParseFlagEnum.ParseAll);
212 if (getResponse.isRight()) {
213 log.debug("Couldn't fetch component with and unique id {}, error: {}", componentToDelete.getUniqueId(), getResponse.right().value());
214 return DaoStatusConverter.convertTitanStatusToStorageStatus(getResponse.right().value());
217 GraphVertex componentV = getResponse.left().value();
219 // same operation for node type and topology template operations
220 Either<GraphVertex, StorageOperationStatus> result = nodeTypeOperation.markComponentToDelete(componentV);
221 if (result.isRight()) {
222 return result.right().value();
224 return StorageOperationStatus.OK;
233 public <T extends Component> Either<T, StorageOperationStatus> deleteToscaComponent(String componentId) {
235 Either<GraphVertex, TitanOperationStatus> getVertexEither = titanDao.getVertexById(componentId, JsonParseFlagEnum.ParseAll);
236 if (getVertexEither.isRight()) {
237 log.debug("Couldn't fetch component vertex with and unique id {}, error: {}", componentId, getVertexEither.right().value());
238 return Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(getVertexEither.right().value()));
241 Either<ToscaElement, StorageOperationStatus> deleteElement = deleteToscaElement(getVertexEither.left().value());
242 if (deleteElement.isRight()) {
243 log.debug("Failed to delete component with and unique id {}, error: {}", componentId, deleteElement.right().value());
244 return Either.right(deleteElement.right().value());
246 T dataModel = ModelConverter.convertFromToscaElement(deleteElement.left().value());
248 return Either.left(dataModel);
251 private Either<ToscaElement, StorageOperationStatus> deleteToscaElement(GraphVertex componentV) {
252 VertexTypeEnum label = componentV.getLabel();
253 Either<ToscaElement, StorageOperationStatus> toscaElement;
254 Object componentId = componentV.getUniqueId();
257 log.debug("Need to fetch node type for id {}", componentId);
258 toscaElement = nodeTypeOperation.deleteToscaElement(componentV);
260 case TOPOLOGY_TEMPLATE:
261 log.debug("Need to fetch topology template for id {}", componentId);
262 toscaElement = topologyTemplateOperation.deleteToscaElement(componentV);
265 log.debug("not supported tosca type {} for id {}", label, componentId);
266 toscaElement = Either.right(StorageOperationStatus.BAD_REQUEST);
272 private ToscaElementOperation getToscaElementOperation(Component component) {
273 return ModelConverter.isAtomicComponent(component) ? nodeTypeOperation : topologyTemplateOperation;
276 public <T extends Component> Either<T, StorageOperationStatus> getLatestByToscaResourceName(String toscaResourceName) {
277 return getLatestByName(GraphPropertyEnum.TOSCA_RESOURCE_NAME, toscaResourceName);
281 public <T extends Component> Either<T, StorageOperationStatus> getLatestByName(String resourceName) {
282 return getLatestByName(GraphPropertyEnum.NAME, resourceName);
286 public Either<Integer, StorageOperationStatus> validateCsarUuidUniqueness(String csarUUID) {
287 Either<List<ToscaElement>, StorageOperationStatus> byCsar = null;
289 Map<GraphPropertyEnum, Object> properties = new HashMap<GraphPropertyEnum, Object>();
290 properties.put(GraphPropertyEnum.CSAR_UUID, csarUUID);
292 Either<List<GraphVertex>, TitanOperationStatus> resources = titanDao.getByCriteria(null, properties, JsonParseFlagEnum.ParseMetadata);
294 if (resources.isRight()) {
295 if (resources.right().value() == TitanOperationStatus.NOT_FOUND) {
296 return Either.left(new Integer(0));
298 log.debug("failed to get resources from graph with property name: {}", csarUUID);
299 return Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(resources.right().value()));
303 List<GraphVertex> resourceList = (resources.isLeft() ? resources.left().value() : null);
305 return Either.left(new Integer(resourceList.size()));
309 public <T extends Component> Either<Set<T>, StorageOperationStatus> getFollowed(String userId, Set<LifecycleStateEnum> lifecycleStates, Set<LifecycleStateEnum> lastStateStates, ComponentTypeEnum componentType) {
310 Either<List<ToscaElement>, StorageOperationStatus> followedResources;
311 if (componentType == ComponentTypeEnum.RESOURCE) {
312 followedResources = nodeTypeOperation.getFollowedComponent(userId, lifecycleStates, lastStateStates, componentType);
314 followedResources = topologyTemplateOperation.getFollowedComponent(userId, lifecycleStates, lastStateStates, componentType);
317 Set<T> components = new HashSet<>();
318 if (followedResources.isRight() && followedResources.right().value() != StorageOperationStatus.NOT_FOUND) {
319 return Either.right(followedResources.right().value());
321 if (followedResources.isLeft()) {
322 List<ToscaElement> toscaElements = followedResources.left().value();
323 toscaElements.forEach(te -> {
324 T component = ModelConverter.convertFromToscaElement(te);
325 components.add(component);
328 return Either.left(components);
331 public Either<Resource, StorageOperationStatus> getLatestCertifiedNodeTypeByToscaResourceName(String toscaResourceName) {
333 return getLatestCertifiedByToscaResourceName(toscaResourceName, VertexTypeEnum.NODE_TYPE, JsonParseFlagEnum.ParseMetadata);
336 public Either<Resource, StorageOperationStatus> getLatestCertifiedByToscaResourceName(String toscaResourceName, VertexTypeEnum vertexType, JsonParseFlagEnum parseFlag) {
338 Either<Resource, StorageOperationStatus> result = null;
339 Map<GraphPropertyEnum, Object> props = new HashMap<GraphPropertyEnum, Object>();
340 props.put(GraphPropertyEnum.TOSCA_RESOURCE_NAME, toscaResourceName);
341 props.put(GraphPropertyEnum.IS_HIGHEST_VERSION, true);
342 props.put(GraphPropertyEnum.STATE, LifecycleStateEnum.CERTIFIED.name());
343 Either<List<GraphVertex>, TitanOperationStatus> getLatestRes = titanDao.getByCriteria(vertexType, props, parseFlag);
345 if (getLatestRes.isRight()) {
346 TitanOperationStatus status = getLatestRes.right().value();
347 CommonUtility.addRecordToLog(log, LogLevelEnum.DEBUG, "Failed to fetch {} with name {}. status={} ", vertexType, toscaResourceName, status);
348 result = Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(status));
350 if (result == null) {
351 List<GraphVertex> resources = getLatestRes.left().value();
352 double version = 0.0;
353 GraphVertex highestResource = null;
354 for (GraphVertex resource : resources) {
355 double resourceVersion = Double.parseDouble((String) resource.getJsonMetadataField(JsonPresentationFields.VERSION));
356 if (resourceVersion > version) {
357 version = resourceVersion;
358 highestResource = resource;
361 result = getToscaElement(highestResource.getUniqueId());
366 public Either<Boolean, StorageOperationStatus> validateToscaResourceNameExists(String templateName) {
367 Either<Boolean, StorageOperationStatus> validateUniquenessRes = validateToscaResourceNameUniqueness(templateName);
368 if (validateUniquenessRes.isLeft()) {
369 return Either.left(!validateUniquenessRes.left().value());
371 return validateUniquenessRes;
374 public Either<RequirementCapabilityRelDef, StorageOperationStatus> dissociateResourceInstances(String componentId, RequirementCapabilityRelDef requirementDef) {
375 return nodeTemplateOperation.dissociateResourceInstances(componentId, requirementDef);
379 public StorageOperationStatus associateResourceInstances(String componentId, List<RequirementCapabilityRelDef> relations) {
380 Either<List<RequirementCapabilityRelDef>, StorageOperationStatus> status = nodeTemplateOperation.associateResourceInstances(componentId, relations);
381 if (status.isRight()) {
382 return status.right().value();
384 return StorageOperationStatus.OK;
387 protected Either<Boolean, StorageOperationStatus> validateToscaResourceNameUniqueness(String name) {
389 Map<GraphPropertyEnum, Object> properties = new HashMap<GraphPropertyEnum, Object>();
390 properties.put(GraphPropertyEnum.TOSCA_RESOURCE_NAME, name);
392 Either<List<GraphVertex>, TitanOperationStatus> resources = titanDao.getByCriteria(null, properties, JsonParseFlagEnum.ParseMetadata);
394 if (resources.isRight() && resources.right().value() != TitanOperationStatus.NOT_FOUND) {
395 log.debug("failed to get resources from graph with property name: {}", name);
396 return Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(resources.right().value()));
398 List<GraphVertex> resourceList = (resources.isLeft() ? resources.left().value() : null);
399 if (resourceList != null && resourceList.size() > 0) {
400 if (log.isDebugEnabled()) {
401 StringBuilder builder = new StringBuilder();
402 for (GraphVertex resourceData : resourceList) {
403 builder.append(resourceData.getUniqueId() + "|");
405 log.debug("resources with property name:{} exists in graph. found {}", name, builder.toString());
407 return Either.left(false);
409 log.debug("resources with property name:{} does not exists in graph", name);
410 return Either.left(true);
417 * @param newComponent
418 * @param oldComponent
421 public <T extends Component> Either<T, StorageOperationStatus> overrideComponent(T newComponent, T oldComponent) {
424 // newComponent.setInterfaces(oldComponent.getInterfaces);
425 newComponent.setArtifacts(oldComponent.getArtifacts());
426 newComponent.setDeploymentArtifacts(oldComponent.getDeploymentArtifacts());
427 newComponent.setGroups(oldComponent.getGroups());
428 newComponent.setInputs(null);
429 newComponent.setLastUpdateDate(null);
430 newComponent.setHighestVersion(true);
432 Either<GraphVertex, TitanOperationStatus> componentVEither = titanDao.getVertexById(oldComponent.getUniqueId(), JsonParseFlagEnum.NoParse);
433 if (componentVEither.isRight()) {
434 log.debug("Falied to fetch component {} error {}", oldComponent.getUniqueId(), componentVEither.right().value());
435 return Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(componentVEither.right().value()));
437 GraphVertex componentv = componentVEither.left().value();
438 Either<GraphVertex, TitanOperationStatus> parentVertexEither = titanDao.getParentVertex(componentv, EdgeLabelEnum.VERSION, JsonParseFlagEnum.NoParse);
439 if (parentVertexEither.isRight() && parentVertexEither.right().value() != TitanOperationStatus.NOT_FOUND) {
440 log.debug("Falied to fetch parent version for component {} error {}", oldComponent.getUniqueId(), parentVertexEither.right().value());
441 return Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(parentVertexEither.right().value()));
444 Either<ToscaElement, StorageOperationStatus> deleteToscaComponent = deleteToscaElement(componentv);
445 if (deleteToscaComponent.isRight()) {
446 log.debug("Falied to remove old component {} error {}", oldComponent.getUniqueId(), deleteToscaComponent.right().value());
447 return Either.right(deleteToscaComponent.right().value());
449 Either<T, StorageOperationStatus> createToscaComponent = createToscaComponent(newComponent);
450 if (createToscaComponent.isRight()) {
451 log.debug("Falied to create tosca element component {} error {}", newComponent.getUniqueId(), createToscaComponent.right().value());
452 return Either.right(createToscaComponent.right().value());
454 T newElement = createToscaComponent.left().value();
455 Either<GraphVertex, TitanOperationStatus> newVersionEither = titanDao.getVertexById(newElement.getUniqueId(), JsonParseFlagEnum.NoParse);
456 if (newVersionEither.isRight()) {
457 log.debug("Falied to fetch new tosca element component {} error {}", newComponent.getUniqueId(), newVersionEither.right().value());
458 return Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(newVersionEither.right().value()));
460 if (parentVertexEither.isLeft()) {
461 GraphVertex previousVersionV = parentVertexEither.left().value();
462 TitanOperationStatus createEdge = titanDao.createEdge(previousVersionV, newVersionEither.left().value(), EdgeLabelEnum.VERSION, null);
463 if (createEdge != TitanOperationStatus.OK) {
464 log.debug("Falied to associate to previous version {} new version {} error {}", previousVersionV.getUniqueId(), newVersionEither.right().value(), createEdge);
465 return Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(createEdge));
468 return Either.left(newElement);
473 * @param componentToUpdate
476 public <T extends Component> Either<T, StorageOperationStatus> updateToscaElement(T componentToUpdate) {
477 return updateToscaElement(componentToUpdate, new ComponentParametersView());
482 * @param componentToUpdate
484 * @param filterResult
487 public <T extends Component> Either<T, StorageOperationStatus> updateToscaElement(T componentToUpdate, ComponentParametersView filterResult) {
488 String componentId = componentToUpdate.getUniqueId();
489 Either<GraphVertex, TitanOperationStatus> getVertexEither = titanDao.getVertexById(componentId, JsonParseFlagEnum.ParseAll);
490 if (getVertexEither.isRight()) {
491 log.debug("Couldn't fetch component with and unique id {}, error: {}", componentId, getVertexEither.right().value());
492 return Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(getVertexEither.right().value()));
494 GraphVertex elementV = getVertexEither.left().value();
495 ToscaElementOperation toscaElementOperation = getToscaElementOperation(elementV);
497 ToscaElement toscaElementToUpdate = ModelConverter.convertToToscaElement(componentToUpdate);
498 Either<ToscaElement, StorageOperationStatus> updateToscaElement = toscaElementOperation.updateToscaElement(toscaElementToUpdate, elementV, filterResult);
499 if (updateToscaElement.isRight()) {
500 log.debug("Failed to update tosca element {} error {}", componentId, updateToscaElement.right().value());
501 return Either.right(updateToscaElement.right().value());
503 return Either.left(ModelConverter.convertFromToscaElement(updateToscaElement.left().value()));
506 private <T extends Component> Either<T, StorageOperationStatus> getLatestByName(GraphPropertyEnum property, String nodeName) {
507 Either<T, StorageOperationStatus> result;
509 Map<GraphPropertyEnum, Object> propertiesToMatch = new EnumMap<>(GraphPropertyEnum.class);
510 Map<GraphPropertyEnum, Object> propertiesNotToMatch = new EnumMap<>(GraphPropertyEnum.class);
512 propertiesToMatch.put(property, nodeName);
513 propertiesToMatch.put(GraphPropertyEnum.IS_HIGHEST_VERSION, true);
515 propertiesNotToMatch.put(GraphPropertyEnum.IS_DELETED, true);
517 Either<List<GraphVertex>, TitanOperationStatus> highestResources = titanDao.getByCriteria(null, propertiesToMatch, propertiesNotToMatch, JsonParseFlagEnum.ParseMetadata);
518 if (highestResources.isRight()) {
519 TitanOperationStatus status = highestResources.right().value();
520 log.debug("failed to find resource with name {}. status={} ", nodeName, status);
521 result = Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(status));
525 List<GraphVertex> resources = highestResources.left().value();
526 double version = 0.0;
527 GraphVertex highestResource = null;
528 for (GraphVertex vertex : resources) {
529 Object versionObj = vertex.getMetadataProperty(GraphPropertyEnum.VERSION);
530 double resourceVersion = Double.valueOf((String) versionObj);
531 if (resourceVersion > version) {
532 version = resourceVersion;
533 highestResource = vertex;
536 return getToscaElementByOperation(highestResource);
539 public <T extends Component> Either<List<T>, StorageOperationStatus> getBySystemName(ComponentTypeEnum componentType, String systemName) {
541 Either<List<T>, StorageOperationStatus> result = null;
542 Either<T, StorageOperationStatus> getComponentRes;
543 List<T> components = new ArrayList<>();
544 List<GraphVertex> componentVertices;
545 Map<GraphPropertyEnum, Object> propertiesToMatch = new EnumMap<>(GraphPropertyEnum.class);
546 Map<GraphPropertyEnum, Object> propertiesNotToMatch = new EnumMap<>(GraphPropertyEnum.class);
548 propertiesToMatch.put(GraphPropertyEnum.SYSTEM_NAME, systemName);
549 if (componentType != null)
550 propertiesToMatch.put(GraphPropertyEnum.COMPONENT_TYPE, componentType.name());
552 propertiesNotToMatch.put(GraphPropertyEnum.IS_DELETED, true);
554 Either<List<GraphVertex>, TitanOperationStatus> getComponentsRes = titanDao.getByCriteria(null, propertiesToMatch, propertiesNotToMatch, JsonParseFlagEnum.ParseAll);
555 if (getComponentsRes.isRight()) {
556 TitanOperationStatus status = getComponentsRes.right().value();
557 log.debug("Failed to fetch the component with system name {}. Status is {} ", systemName, status);
558 result = Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(status));
560 if (result == null) {
561 componentVertices = getComponentsRes.left().value();
562 for (GraphVertex componentVertex : componentVertices) {
563 getComponentRes = getToscaElementByOperation(componentVertex);
564 if (getComponentRes.isRight()) {
565 log.debug("Failed to get the component {}. Status is {} ", componentVertex.getJsonMetadataField(JsonPresentationFields.NAME), getComponentRes.right().value());
566 result = Either.right(getComponentRes.right().value());
569 T componentBySystemName = getComponentRes.left().value();
570 log.debug("Found component, id: {}", componentBySystemName.getUniqueId());
571 components.add(componentBySystemName);
574 if (result == null) {
575 result = Either.left(components);
580 public <T extends Component> Either<T, StorageOperationStatus> getComponentByNameAndVersion(ComponentTypeEnum componentType, String name, String version) {
581 return getComponentByNameAndVersion(componentType, name, version, JsonParseFlagEnum.ParseAll);
584 public <T extends Component> Either<T, StorageOperationStatus> getComponentByNameAndVersion(ComponentTypeEnum componentType, String name, String version, JsonParseFlagEnum parseFlag) {
585 Either<T, StorageOperationStatus> result;
587 Map<GraphPropertyEnum, Object> hasProperties = new EnumMap<>(GraphPropertyEnum.class);
588 Map<GraphPropertyEnum, Object> hasNotProperties = new EnumMap<>(GraphPropertyEnum.class);
590 hasProperties.put(GraphPropertyEnum.NAME, name);
591 hasProperties.put(GraphPropertyEnum.VERSION, version);
592 hasNotProperties.put(GraphPropertyEnum.IS_DELETED, true);
593 if (componentType != null) {
594 hasProperties.put(GraphPropertyEnum.COMPONENT_TYPE, componentType.name());
596 Either<List<GraphVertex>, TitanOperationStatus> getResourceRes = titanDao.getByCriteria(null, hasProperties, hasNotProperties, parseFlag);
597 if (getResourceRes.isRight()) {
598 TitanOperationStatus status = getResourceRes.right().value();
599 log.debug("failed to find resource with name {}, version {}. Status is {} ", name, version, status);
600 result = Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(status));
603 return getToscaElementByOperation(getResourceRes.left().value().get(0));
606 public <T extends Component> Either<List<T>, StorageOperationStatus> getCatalogComponents(ComponentTypeEnum componentType, List<OriginTypeEnum> excludeTypes, boolean isHighestVersions) {
607 List<T> components = new ArrayList<>();
608 Either<List<ToscaElement>, StorageOperationStatus> catalogDataResult;
609 List<ToscaElement> toscaElements = new ArrayList<>();
610 List<ResourceTypeEnum> excludedResourceTypes =
611 Optional.ofNullable(excludeTypes).orElse(Collections.emptyList())
613 .filter(type -> !type.equals(OriginTypeEnum.SERVICE))
614 .map(type -> ResourceTypeEnum.getTypeByName(type.name())).collect(Collectors.toList());
616 switch (componentType) {
618 catalogDataResult = nodeTypeOperation.getElementCatalogData(ComponentTypeEnum.RESOURCE,excludedResourceTypes , isHighestVersions);
619 if (catalogDataResult.isRight()) {
620 return Either.right(catalogDataResult.right().value());
622 toscaElements = catalogDataResult.left().value();
625 if (excludeTypes!= null && excludeTypes.contains(OriginTypeEnum.SERVICE)) {
628 catalogDataResult = topologyTemplateOperation.getElementCatalogData(ComponentTypeEnum.SERVICE, null, isHighestVersions);
629 if (catalogDataResult.isRight()) {
630 return Either.right(catalogDataResult.right().value());
632 toscaElements = catalogDataResult.left().value();
635 log.debug("Not supported component type {}", componentType);
636 return Either.right(StorageOperationStatus.BAD_REQUEST);
638 toscaElements.forEach(te -> {
639 T component = ModelConverter.convertFromToscaElement(te);
640 components.add(component);
642 return Either.left(components);
645 public Either<List<String>, StorageOperationStatus> deleteMarkedElements(ComponentTypeEnum componentType) {
646 Either<List<GraphVertex>, StorageOperationStatus> allComponentsMarkedForDeletion;
647 List<String> deleted = new ArrayList<>();
648 switch (componentType) {
650 allComponentsMarkedForDeletion = nodeTypeOperation.getAllComponentsMarkedForDeletion(componentType);
654 allComponentsMarkedForDeletion = topologyTemplateOperation.getAllComponentsMarkedForDeletion(componentType);
657 log.debug("Not supported component type {}", componentType);
658 return Either.right(StorageOperationStatus.BAD_REQUEST);
660 if (allComponentsMarkedForDeletion.isRight()) {
661 return Either.right(allComponentsMarkedForDeletion.right().value());
663 List<GraphVertex> allMarked = allComponentsMarkedForDeletion.left().value();
665 Either<List<GraphVertex>, TitanOperationStatus> allNotDeletedElements = topologyTemplateOperation.getAllNotDeletedElements();
666 if (allNotDeletedElements.isRight()) {
667 return Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(allNotDeletedElements.right().value()));
669 List<GraphVertex> allNonMarked = allNotDeletedElements.left().value();
670 for (GraphVertex elementV : allMarked) {
671 if (topologyTemplateOperation.isInUse(elementV, allNonMarked) == false) {
672 Either<ToscaElement, StorageOperationStatus> deleteToscaElement = deleteToscaElement(elementV);
673 if (deleteToscaElement.isRight()) {
674 log.debug("Failed to delete marked element {} error {}", elementV.getUniqueId(), deleteToscaElement.right().value());
677 deleted.add(elementV.getUniqueId());
678 log.debug("Marked element {} in use. don't delete it", elementV.getUniqueId());
681 return Either.left(deleted);
684 public Either<List<String>, StorageOperationStatus> getAllComponentsMarkedForDeletion(ComponentTypeEnum componentType) {
685 Either<List<GraphVertex>, StorageOperationStatus> allComponentsMarkedForDeletion;
686 switch (componentType) {
688 allComponentsMarkedForDeletion = nodeTypeOperation.getAllComponentsMarkedForDeletion(componentType);
692 allComponentsMarkedForDeletion = topologyTemplateOperation.getAllComponentsMarkedForDeletion(componentType);
695 log.debug("Not supported component type {}", componentType);
696 return Either.right(StorageOperationStatus.BAD_REQUEST);
698 if (allComponentsMarkedForDeletion.isRight()) {
699 return Either.right(allComponentsMarkedForDeletion.right().value());
701 return Either.left(allComponentsMarkedForDeletion.left().value().stream().map(v -> v.getUniqueId()).collect(Collectors.toList()));
704 public Either<Boolean, StorageOperationStatus> isComponentInUse(String componentId) {
705 Either<Boolean, StorageOperationStatus> result;
706 Either<List<GraphVertex>, TitanOperationStatus> allNotDeletedElements = topologyTemplateOperation.getAllNotDeletedElements();
707 if (allNotDeletedElements.isRight()) {
708 result = Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(allNotDeletedElements.right().value()));
710 result = Either.left(topologyTemplateOperation.isInUse(componentId, allNotDeletedElements.left().value()));
715 public Either<ImmutablePair<Component, String>, StorageOperationStatus> addComponentInstanceToTopologyTemplate(Component containerComponent, Component origComponent, ComponentInstance componentInstance, boolean allowDeleted, User user) {
717 Either<ImmutablePair<Component, String>, StorageOperationStatus> result = null;
718 Either<ToscaElement, StorageOperationStatus> updateContainerComponentRes = null;
719 componentInstance.setIcon(origComponent.getIcon());
720 Either<ImmutablePair<TopologyTemplate, String>, StorageOperationStatus> addResult = nodeTemplateOperation.addComponentInstanceToTopologyTemplate(ModelConverter.convertToToscaElement(containerComponent),
721 ModelConverter.convertToToscaElement(origComponent), getNextComponentInstanceCounter(containerComponent, origComponent.getName()), componentInstance, allowDeleted, user);
723 if (addResult.isRight()) {
724 CommonUtility.addRecordToLog(log, LogLevelEnum.DEBUG, "Failed to add the component instance {} to container component {}. ", componentInstance.getName(), containerComponent.getName());
725 result = Either.right(addResult.right().value());
727 if (result == null) {
728 updateContainerComponentRes = topologyTemplateOperation.getToscaElement(containerComponent.getUniqueId());
729 if (updateContainerComponentRes.isRight()) {
730 CommonUtility.addRecordToLog(log, LogLevelEnum.DEBUG, "Failed to fetch updated topology template {} with updated component instance {}. ", containerComponent.getName(), componentInstance.getName());
731 result = Either.right(updateContainerComponentRes.right().value());
734 if (result == null) {
735 Component updatedComponent = ModelConverter.convertFromToscaElement(updateContainerComponentRes.left().value());
736 String createdInstanceId = addResult.left().value().getRight();
737 CommonUtility.addRecordToLog(log, LogLevelEnum.TRACE, "The component instance {} has been added to container component {}. ", createdInstanceId, updatedComponent.getName());
738 result = Either.left(new ImmutablePair<>(updatedComponent, createdInstanceId));
743 public StorageOperationStatus associateComponentInstancesToComponent(Component containerComponent, Map<ComponentInstance, Resource> resourcesInstancesMap, boolean allowDeleted) {
745 StorageOperationStatus result = null;
746 CommonUtility.addRecordToLog(log, LogLevelEnum.DEBUG, "Going to add component instances to component {}", containerComponent.getUniqueId());
748 Either<GraphVertex, TitanOperationStatus> metadataVertex = titanDao.getVertexById(containerComponent.getUniqueId(), JsonParseFlagEnum.ParseAll);
749 if (metadataVertex.isRight()) {
750 TitanOperationStatus status = metadataVertex.right().value();
751 if (status == TitanOperationStatus.NOT_FOUND) {
752 status = TitanOperationStatus.INVALID_ID;
754 result = DaoStatusConverter.convertTitanStatusToStorageStatus(status);
756 if (result == null) {
757 result = nodeTemplateOperation.associateComponentInstancesToComponent(containerComponent, resourcesInstancesMap, metadataVertex.left().value(), allowDeleted);
762 public Either<ImmutablePair<Component, String>, StorageOperationStatus> updateComponentInstanceMetadataOfTopologyTemplate(Component containerComponent, Component origComponent, ComponentInstance componentInstance) {
764 Either<ImmutablePair<Component, String>, StorageOperationStatus> result = null;
766 CommonUtility.addRecordToLog(log, LogLevelEnum.TRACE, "Going to update the metadata of the component instance {} belonging to container component {}. ", componentInstance.getName(), containerComponent.getName());
767 componentInstance.setIcon(origComponent.getIcon());
768 Either<ImmutablePair<TopologyTemplate, String>, StorageOperationStatus> updateResult = nodeTemplateOperation.updateComponentInstanceMetadataOfTopologyTemplate(ModelConverter.convertToToscaElement(containerComponent),
769 ModelConverter.convertToToscaElement(origComponent), componentInstance);
770 if (updateResult.isRight()) {
771 CommonUtility.addRecordToLog(log, LogLevelEnum.DEBUG, "Failed to update the metadata of the component instance {} belonging to container component {}. ", componentInstance.getName(), containerComponent.getName());
772 result = Either.right(updateResult.right().value());
774 if (result == null) {
775 Component updatedComponent = ModelConverter.convertFromToscaElement(updateResult.left().value().getLeft());
776 String createdInstanceId = updateResult.left().value().getRight();
777 CommonUtility.addRecordToLog(log, LogLevelEnum.TRACE, "The metadata of the component instance {} has been updated to container component {}. ", createdInstanceId, updatedComponent.getName());
778 result = Either.left(new ImmutablePair<>(updatedComponent, createdInstanceId));
783 public Either<Component, StorageOperationStatus> updateComponentInstanceMetadataOfTopologyTemplate(Component containerComponent) {
785 Either<Component, StorageOperationStatus> result = null;
787 CommonUtility.addRecordToLog(log, LogLevelEnum.TRACE, "Going to update the metadata belonging to container component {}. ", containerComponent.getName());
789 Either<TopologyTemplate, StorageOperationStatus> updateResult = nodeTemplateOperation.updateComponentInstanceMetadataOfTopologyTemplate(ModelConverter.convertToToscaElement(containerComponent));
790 if (updateResult.isRight()) {
791 CommonUtility.addRecordToLog(log, LogLevelEnum.DEBUG, "Failed to update the metadata belonging to container component {}. ", containerComponent.getName());
792 result = Either.right(updateResult.right().value());
794 if (result == null) {
795 Component updatedComponent = ModelConverter.convertFromToscaElement(updateResult.left().value());
796 CommonUtility.addRecordToLog(log, LogLevelEnum.TRACE, "The metadata has been updated to container component {}. ", updatedComponent.getName());
797 result = Either.left(updatedComponent);
802 public Either<ImmutablePair<Component, String>, StorageOperationStatus> deleteComponentInstanceFromTopologyTemplate(Component containerComponent, String resourceInstanceId) {
804 Either<ImmutablePair<Component, String>, StorageOperationStatus> result = null;
806 CommonUtility.addRecordToLog(log, LogLevelEnum.TRACE, "Going to delete the component instance {} belonging to container component {}. ", resourceInstanceId, containerComponent.getName());
808 Either<ImmutablePair<TopologyTemplate, String>, StorageOperationStatus> updateResult = nodeTemplateOperation.deleteComponentInstanceFromTopologyTemplate(ModelConverter.convertToToscaElement(containerComponent), resourceInstanceId);
809 if (updateResult.isRight()) {
810 CommonUtility.addRecordToLog(log, LogLevelEnum.DEBUG, "Failed to delete the component instance {} belonging to container component {}. ", resourceInstanceId, containerComponent.getName());
811 result = Either.right(updateResult.right().value());
813 if (result == null) {
814 Component updatedComponent = ModelConverter.convertFromToscaElement(updateResult.left().value().getLeft());
815 String deletedInstanceId = updateResult.left().value().getRight();
816 CommonUtility.addRecordToLog(log, LogLevelEnum.TRACE, "The component instance {} has been deleted from container component {}. ", deletedInstanceId, updatedComponent.getName());
817 result = Either.left(new ImmutablePair<>(updatedComponent, deletedInstanceId));
822 private String getNextComponentInstanceCounter(Component containerComponent, String originResourceName) {
824 Integer nextCounter = 0;
826 if (CollectionUtils.isNotEmpty(containerComponent.getComponentInstances())) {
828 String normalizedName = ValidationUtils.normalizeComponentInstanceName(originResourceName);
829 Integer maxCounterFromNames = getMaxCounterFromNames(containerComponent, normalizedName);
830 Integer maxCounterFromIds = getMaxCounterFromIds(containerComponent, normalizedName);
832 if (maxCounterFromNames == null && maxCounterFromIds != null) {
833 nextCounter = maxCounterFromIds + 1;
834 } else if (maxCounterFromIds == null && maxCounterFromNames != null) {
835 nextCounter = maxCounterFromNames + 1;
836 } else if (maxCounterFromIds != null && maxCounterFromNames != null) {
837 nextCounter = maxCounterFromNames > maxCounterFromIds ? maxCounterFromNames + 1 : maxCounterFromIds + 1;
840 return nextCounter.toString();
843 private Integer getMaxCounterFromNames(Component containerComponent, String normalizedName) {
845 Integer maxCounter = 0;
846 List<String> countersStr = containerComponent.getComponentInstances().stream().filter(ci -> ci.getNormalizedName() != null && ci.getNormalizedName().startsWith(normalizedName)).map(ci -> ci.getNormalizedName().split(normalizedName)[1])
847 .collect(Collectors.toList());
849 if (CollectionUtils.isEmpty(countersStr)) {
852 Integer currCounter = null;
853 for (String counter : countersStr) {
854 if (StringUtils.isEmpty(counter)) {
858 currCounter = Integer.parseInt(counter);
859 } catch (Exception e) {
862 maxCounter = maxCounter < currCounter ? currCounter : maxCounter;
864 if (currCounter == null) {
870 private Integer getMaxCounterFromIds(Component containerComponent, String normalizedName) {
872 Integer maxCounter = 0;
873 List<String> countersStr = containerComponent.getComponentInstances().stream().filter(ci -> ci.getUniqueId() != null && ci.getUniqueId().contains(normalizedName)).map(ci -> ci.getUniqueId().split(normalizedName)[1])
874 .collect(Collectors.toList());
876 if (CollectionUtils.isEmpty(countersStr)) {
879 Integer currCounter = null;
880 for (String counter : countersStr) {
881 if (StringUtils.isEmpty(counter)) {
885 currCounter = Integer.parseInt(counter);
886 } catch (Exception e) {
889 maxCounter = maxCounter < currCounter ? currCounter : maxCounter;
891 if (currCounter == null) {
897 public Either<RequirementCapabilityRelDef, StorageOperationStatus> associateResourceInstances(String componentId, RequirementCapabilityRelDef requirementDef) {
898 return nodeTemplateOperation.associateResourceInstances(componentId, requirementDef);
902 public Either<List<InputDefinition>, StorageOperationStatus> createAndAssociateInputs(Map<String, InputDefinition> inputs, String componentId) {
904 Either<GraphVertex, TitanOperationStatus> getVertexEither = titanDao.getVertexById(componentId, JsonParseFlagEnum.NoParse);
905 if (getVertexEither.isRight()) {
906 log.debug("Couldn't fetch component with and unique id {}, error: {}", componentId, getVertexEither.right().value());
907 return Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(getVertexEither.right().value()));
911 GraphVertex vertex = getVertexEither.left().value();
912 Map<String, PropertyDataDefinition> inputsMap = inputs.entrySet().stream().collect(Collectors.toMap(Map.Entry::getKey, e -> new PropertyDataDefinition(e.getValue())));
914 StorageOperationStatus status = topologyTemplateOperation.associateInputsToComponent(vertex, inputsMap, componentId);
916 if (StorageOperationStatus.OK == status) {
917 log.debug("Component created successfully!!!");
918 List<InputDefinition> inputsResList = null;
919 if (inputsMap != null && !inputsMap.isEmpty()) {
920 inputsResList = inputsMap.values().stream().map(i -> new InputDefinition(i)).collect(Collectors.toList());
922 return Either.left(inputsResList);
924 return Either.right(status);
928 public Either<List<InputDefinition>, StorageOperationStatus> addInputsToComponent(Map<String, InputDefinition> inputs, String componentId) {
930 Either<GraphVertex, TitanOperationStatus> getVertexEither = titanDao.getVertexById(componentId, JsonParseFlagEnum.NoParse);
931 if (getVertexEither.isRight()) {
932 log.debug("Couldn't fetch component with and unique id {}, error: {}", componentId, getVertexEither.right().value());
933 return Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(getVertexEither.right().value()));
937 GraphVertex vertex = getVertexEither.left().value();
938 Map<String, PropertyDataDefinition> inputsMap = inputs.entrySet().stream().collect(Collectors.toMap(Map.Entry::getKey, e -> new PropertyDataDefinition(e.getValue())));
940 StorageOperationStatus status = topologyTemplateOperation.addToscaDataToToscaElement(vertex, EdgeLabelEnum.INPUTS, VertexTypeEnum.INPUTS, inputsMap, JsonPresentationFields.NAME);
942 if (StorageOperationStatus.OK == status) {
943 log.debug("Component created successfully!!!");
944 List<InputDefinition> inputsResList = null;
945 if (inputsMap != null && !inputsMap.isEmpty()) {
946 inputsResList = inputsMap.values().stream().map(i -> new InputDefinition(i)).collect(Collectors.toList());
948 return Either.left(inputsResList);
950 return Either.right(status);
954 public Either<Map<String, List<ComponentInstanceProperty>>, StorageOperationStatus> associateComponentInstancePropertiesToComponent(Map<String, List<ComponentInstanceProperty>> instProperties, String componentId) {
956 Either<GraphVertex, TitanOperationStatus> getVertexEither = titanDao.getVertexById(componentId, JsonParseFlagEnum.NoParse);
957 if (getVertexEither.isRight()) {
958 log.debug("Couldn't fetch component with and unique id {}, error: {}", componentId, getVertexEither.right().value());
959 return Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(getVertexEither.right().value()));
963 GraphVertex vertex = getVertexEither.left().value();
964 Map<String, MapPropertiesDataDefinition> instPropsMap = new HashMap<>();
965 if (instProperties != null) {
967 MapPropertiesDataDefinition propertiesMap;
968 for (Entry<String, List<ComponentInstanceProperty>> entry : instProperties.entrySet()) {
969 propertiesMap = new MapPropertiesDataDefinition();
971 propertiesMap.setMapToscaDataDefinition(entry.getValue().stream().map(e -> new PropertyDataDefinition(e)).collect(Collectors.toMap(e -> e.getName(), e -> e)));
973 instPropsMap.put(entry.getKey(), propertiesMap);
977 StorageOperationStatus status = topologyTemplateOperation.associateInstPropertiesToComponent(vertex, instPropsMap);
979 if (StorageOperationStatus.OK == status) {
980 log.debug("Component created successfully!!!");
981 return Either.left(instProperties);
983 return Either.right(status);
986 public Either<Map<String, List<ComponentInstanceInput>>, StorageOperationStatus> associateComponentInstanceInputsToComponent(Map<String, List<ComponentInstanceInput>> instInputs, String componentId) {
988 Either<GraphVertex, TitanOperationStatus> getVertexEither = titanDao.getVertexById(componentId, JsonParseFlagEnum.NoParse);
989 if (getVertexEither.isRight()) {
990 log.debug("Couldn't fetch component with and unique id {}, error: {}", componentId, getVertexEither.right().value());
991 return Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(getVertexEither.right().value()));
994 GraphVertex vertex = getVertexEither.left().value();
995 Map<String, MapPropertiesDataDefinition> instPropsMap = new HashMap<>();
996 if (instInputs != null) {
998 MapPropertiesDataDefinition propertiesMap;
999 for (Entry<String, List<ComponentInstanceInput>> entry : instInputs.entrySet()) {
1000 propertiesMap = new MapPropertiesDataDefinition();
1002 propertiesMap.setMapToscaDataDefinition(entry.getValue().stream().map(e -> new PropertyDataDefinition(e)).collect(Collectors.toMap(e -> e.getName(), e -> e)));
1004 instPropsMap.put(entry.getKey(), propertiesMap);
1008 StorageOperationStatus status = topologyTemplateOperation.associateInstInputsToComponent(vertex, instPropsMap);
1010 if (StorageOperationStatus.OK == status) {
1011 log.debug("Component created successfully!!!");
1012 return Either.left(instInputs);
1014 return Either.right(status);
1017 public Either<Map<String, List<ComponentInstanceInput>>, StorageOperationStatus> addComponentInstanceInputsToComponent(Component containerComponent, Map<String, List<ComponentInstanceInput>> instProperties) {
1019 StorageOperationStatus status = StorageOperationStatus.OK;
1020 if (instProperties != null) {
1022 for (Entry<String, List<ComponentInstanceInput>> entry : instProperties.entrySet()) {
1023 List<ComponentInstanceInput> props = entry.getValue();
1024 String componentInstanseId = entry.getKey();
1025 if (props != null && !props.isEmpty()) {
1026 for (ComponentInstanceInput property : props) {
1027 List<ComponentInstanceInput> componentInstancesInputs = containerComponent.getComponentInstancesInputs().get(componentInstanseId);
1028 Optional<ComponentInstanceInput> instanceProperty = componentInstancesInputs.stream().filter(p -> p.getName().equals(property.getName())).findAny();
1029 if (instanceProperty.isPresent()) {
1030 status = updateComponentInstanceInput(containerComponent, componentInstanseId, property);
1032 status = addComponentInstanceInput(containerComponent, componentInstanseId, property);
1034 if (status != StorageOperationStatus.OK) {
1035 log.debug("Failed to update instance input {} for instance {} error {} ", property, componentInstanseId, status);
1036 return Either.right(status);
1038 log.trace("instance input {} for instance {} updated", property, componentInstanseId);
1044 return Either.left(instProperties);
1047 public StorageOperationStatus deleteComponentInstanceInputsToComponent(Map<String, List<ComponentInstanceInput>> instProperties, String componentId) {
1049 Either<GraphVertex, TitanOperationStatus> getVertexEither = titanDao.getVertexById(componentId, JsonParseFlagEnum.NoParse);
1050 if (getVertexEither.isRight()) {
1051 log.debug("Couldn't fetch component with and unique id {}, error: {}", componentId, getVertexEither.right().value());
1052 return DaoStatusConverter.convertTitanStatusToStorageStatus(getVertexEither.right().value());
1056 GraphVertex vertex = getVertexEither.left().value();
1057 Map<String, MapPropertiesDataDefinition> instPropsMap = new HashMap<>();
1058 if (instProperties != null) {
1060 MapPropertiesDataDefinition propertiesMap;
1061 for (Entry<String, List<ComponentInstanceInput>> entry : instProperties.entrySet()) {
1062 propertiesMap = new MapPropertiesDataDefinition();
1064 propertiesMap.setMapToscaDataDefinition(entry.getValue().stream().map(e -> new PropertyDataDefinition(e)).collect(Collectors.toMap(e -> e.getName(), e -> e)));
1066 instPropsMap.put(entry.getKey(), propertiesMap);
1070 return topologyTemplateOperation.deleteInstInputsToComponent(vertex, instPropsMap);
1074 public Either<Map<String, List<ComponentInstanceProperty>>, StorageOperationStatus> addComponentInstancePropertiesToComponent(Component containerComponent, Map<String, List<ComponentInstanceProperty>> instProperties, String componentId) {
1076 StorageOperationStatus status = StorageOperationStatus.OK;
1077 if (instProperties != null) {
1079 for (Entry<String, List<ComponentInstanceProperty>> entry : instProperties.entrySet()) {
1080 List<ComponentInstanceProperty> props = entry.getValue();
1081 String componentInstanseId = entry.getKey();
1082 List<ComponentInstanceProperty> instanceProperties = containerComponent.getComponentInstancesProperties().get(componentInstanseId);
1083 if (props != null && !props.isEmpty()) {
1084 for (ComponentInstanceProperty property : props) {
1085 Optional<ComponentInstanceProperty> instanceProperty = instanceProperties.stream().filter(p -> p.getUniqueId().equals(property.getUniqueId())).findAny();
1086 if (instanceProperty.isPresent()) {
1087 status = updateComponentInstanceProperty(containerComponent, componentInstanseId, property);
1089 status = addComponentInstanceProperty(containerComponent, componentInstanseId, property);
1097 return Either.left(instProperties);
1101 public StorageOperationStatus associateDeploymentArtifactsToInstances(Map<String, Map<String, ArtifactDefinition>> instDeploymentArtifacts, String componentId, User user) {
1103 Either<GraphVertex, TitanOperationStatus> getVertexEither = titanDao.getVertexById(componentId, JsonParseFlagEnum.NoParse);
1104 if (getVertexEither.isRight()) {
1105 log.debug("Couldn't fetch component with and unique id {}, error: {}", componentId, getVertexEither.right().value());
1106 return DaoStatusConverter.convertTitanStatusToStorageStatus(getVertexEither.right().value());
1110 GraphVertex vertex = getVertexEither.left().value();
1111 Map<String, MapArtifactDataDefinition> instArtMap = new HashMap<>();
1112 if (instDeploymentArtifacts != null) {
1114 MapArtifactDataDefinition artifactsMap;
1115 for (Entry<String, Map<String, ArtifactDefinition>> entry : instDeploymentArtifacts.entrySet()) {
1116 Map<String, ArtifactDefinition> artList = entry.getValue();
1117 Map<String, ArtifactDataDefinition> artifacts = artList.entrySet().stream().collect(Collectors.toMap(Map.Entry::getKey, e -> new ArtifactDataDefinition(e.getValue())));
1118 artifactsMap = nodeTemplateOperation.prepareInstDeploymentArtifactPerInstance(artifacts, entry.getKey(), user, NodeTemplateOperation.HEAT_VF_ENV_NAME);
1120 instArtMap.put(entry.getKey(), artifactsMap);
1124 return topologyTemplateOperation.associateInstDeploymentArtifactsToComponent(vertex, instArtMap);
1128 public StorageOperationStatus associateArtifactsToInstances(Map<String, Map<String, ArtifactDefinition>> instArtifacts, String componentId, User user) {
1130 Either<GraphVertex, TitanOperationStatus> getVertexEither = titanDao.getVertexById(componentId, JsonParseFlagEnum.NoParse);
1131 if (getVertexEither.isRight()) {
1132 log.debug("Couldn't fetch component with and unique id {}, error: {}", componentId, getVertexEither.right().value());
1133 return DaoStatusConverter.convertTitanStatusToStorageStatus(getVertexEither.right().value());
1137 GraphVertex vertex = getVertexEither.left().value();
1138 Map<String, MapArtifactDataDefinition> instArtMap = new HashMap<>();
1139 if (instArtifacts != null) {
1141 MapArtifactDataDefinition artifactsMap;
1142 for (Entry<String, Map<String, ArtifactDefinition>> entry : instArtifacts.entrySet()) {
1143 Map<String, ArtifactDefinition> artList = entry.getValue();
1144 Map<String, ArtifactDataDefinition> artifacts = artList.entrySet().stream().collect(Collectors.toMap(Map.Entry::getKey, e -> new ArtifactDataDefinition(e.getValue())));
1145 artifactsMap = new MapArtifactDataDefinition(artifacts);
1147 instArtMap.put(entry.getKey(), artifactsMap);
1151 return topologyTemplateOperation.associateInstArtifactsToComponent(vertex, instArtMap);
1155 public StorageOperationStatus associateInstAttributeToComponentToInstances(Map<String, List<PropertyDefinition>> instArttributes, String componentId) {
1157 Either<GraphVertex, TitanOperationStatus> getVertexEither = titanDao.getVertexById(componentId, JsonParseFlagEnum.NoParse);
1158 if (getVertexEither.isRight()) {
1159 log.debug("Couldn't fetch component with and unique id {}, error: {}", componentId, getVertexEither.right().value());
1160 return DaoStatusConverter.convertTitanStatusToStorageStatus(getVertexEither.right().value());
1164 GraphVertex vertex = getVertexEither.left().value();
1165 Map<String, MapPropertiesDataDefinition> instAttr = new HashMap<>();
1166 if (instArttributes != null) {
1168 MapPropertiesDataDefinition attributesMap;
1169 for (Entry<String, List<PropertyDefinition>> entry : instArttributes.entrySet()) {
1170 attributesMap = new MapPropertiesDataDefinition();
1171 attributesMap.setMapToscaDataDefinition(entry.getValue().stream().map(e -> new PropertyDataDefinition(e)).collect(Collectors.toMap(e -> e.getName(), e -> e)));
1172 instAttr.put(entry.getKey(), attributesMap);
1176 return topologyTemplateOperation.associateInstAttributeToComponent(vertex, instAttr);
1180 public StorageOperationStatus associateCalculatedCapReq(Map<ComponentInstance, Map<String, List<CapabilityDefinition>>> instCapabilties, Map<ComponentInstance, Map<String, List<RequirementDefinition>>> instReg, String componentId) {
1181 Either<GraphVertex, TitanOperationStatus> getVertexEither = titanDao.getVertexById(componentId, JsonParseFlagEnum.NoParse);
1182 if (getVertexEither.isRight()) {
1183 log.debug("Couldn't fetch component with and unique id {}, error: {}", componentId, getVertexEither.right().value());
1184 return DaoStatusConverter.convertTitanStatusToStorageStatus(getVertexEither.right().value());
1188 GraphVertex vertex = getVertexEither.left().value();
1190 Map<String, MapListRequirementDataDefinition> calcRequirements = new HashMap<>();
1192 Map<String, MapListCapabiltyDataDefinition> calcCapabilty = new HashMap<>();
1193 Map<String, MapCapabiltyProperty> calculatedCapabilitiesProperties = new HashMap<>();
1195 if (instCapabilties != null) {
1196 for (Entry<ComponentInstance, Map<String, List<CapabilityDefinition>>> entry : instCapabilties.entrySet()) {
1198 Map<String, List<CapabilityDefinition>> caps = entry.getValue();
1199 Map<String, ListCapabilityDataDefinition> mapToscaDataDefinition = new HashMap<>();
1200 for (Entry<String, List<CapabilityDefinition>> instCapability : caps.entrySet()) {
1201 mapToscaDataDefinition.put(instCapability.getKey(), new ListCapabilityDataDefinition(instCapability.getValue().stream().map(iCap -> new CapabilityDataDefinition(iCap)).collect(Collectors.toList())));
1204 ComponentInstanceDataDefinition componentInstance = new ComponentInstanceDataDefinition(entry.getKey());
1205 MapListCapabiltyDataDefinition capMap = nodeTemplateOperation.prepareCalculatedCapabiltyForNodeType(mapToscaDataDefinition, componentInstance);
1207 MapCapabiltyProperty mapCapabiltyProperty = ModelConverter.convertToMapOfMapCapabiltyProperties(caps, componentInstance.getUniqueId(), true);
1209 calcCapabilty.put(entry.getKey().getUniqueId(), capMap);
1210 calculatedCapabilitiesProperties.put(entry.getKey().getUniqueId(), mapCapabiltyProperty);
1214 if (instReg != null) {
1215 for (Entry<ComponentInstance, Map<String, List<RequirementDefinition>>> entry : instReg.entrySet()) {
1217 Map<String, List<RequirementDefinition>> req = entry.getValue();
1218 Map<String, ListRequirementDataDefinition> mapToscaDataDefinition = new HashMap<>();
1219 for (Entry<String, List<RequirementDefinition>> instReq : req.entrySet()) {
1220 mapToscaDataDefinition.put(instReq.getKey(), new ListRequirementDataDefinition(instReq.getValue().stream().map(iCap -> new RequirementDataDefinition(iCap)).collect(Collectors.toList())));
1223 MapListRequirementDataDefinition capMap = nodeTemplateOperation.prepareCalculatedRequirementForNodeType(mapToscaDataDefinition, new ComponentInstanceDataDefinition(entry.getKey()));
1225 calcRequirements.put(entry.getKey().getUniqueId(), capMap);
1229 StorageOperationStatus status = topologyTemplateOperation.associateCalcCapReqToComponent(vertex, calcRequirements, calcCapabilty, calculatedCapabilitiesProperties);
1234 private Either<List<Component>, StorageOperationStatus> getLatestVersionNotAbstractToscaElementsMetadataOnly(boolean isAbstract, Boolean isHighest, ComponentTypeEnum componentTypeEnum, String internalComponentType, VertexTypeEnum vertexType) {
1236 Map<GraphPropertyEnum, Object> hasProps = new EnumMap<>(GraphPropertyEnum.class);
1237 Map<GraphPropertyEnum, Object> hasNotProps = new EnumMap<>(GraphPropertyEnum.class);
1239 fillPropsMap(hasProps, hasNotProps, internalComponentType, componentTypeEnum, isAbstract, vertexType);
1241 Either<List<GraphVertex>, TitanOperationStatus> getRes = titanDao.getByCriteria(vertexType, hasProps, hasNotProps, JsonParseFlagEnum.ParseMetadata);
1242 if (getRes.isRight()) {
1243 if (getRes.right().value().equals(TitanOperationStatus.NOT_FOUND)) {
1244 return Either.left(new ArrayList<>());
1246 return Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(getRes.right().value()));
1249 List<Component> nonAbstractLatestComponents = new ArrayList<>();
1250 ComponentParametersView params = new ComponentParametersView(true);
1251 params.setIgnoreAllVersions(false);
1252 for (GraphVertex vertexComponent : getRes.left().value()) {
1253 Either<ToscaElement, StorageOperationStatus> componentRes = topologyTemplateOperation.getLightComponent(vertexComponent, componentTypeEnum, params);
1254 if (componentRes.isRight()) {
1255 log.debug("Failed to fetch ligth element for {} error {}", vertexComponent.getUniqueId(), componentRes.right().value());
1256 return Either.right(componentRes.right().value());
1258 Component component = ModelConverter.convertFromToscaElement(componentRes.left().value());
1260 nonAbstractLatestComponents.add(component);
1264 return Either.left(nonAbstractLatestComponents);
1268 public Either<ComponentMetadataData, StorageOperationStatus> getLatestComponentMetadataByUuid(String componentUuid, JsonParseFlagEnum parseFlag, Boolean isHighest) {
1270 Either<ComponentMetadataData, StorageOperationStatus> result;
1272 Map<GraphPropertyEnum, Object> hasProperties = new EnumMap<>(GraphPropertyEnum.class);
1274 hasProperties.put(GraphPropertyEnum.UUID, componentUuid);
1275 if (isHighest != null) {
1276 hasProperties.put(GraphPropertyEnum.IS_HIGHEST_VERSION, isHighest.booleanValue());
1279 Map<GraphPropertyEnum, Object> propertiesNotToMatch = new EnumMap<>(GraphPropertyEnum.class);
1280 propertiesNotToMatch.put(GraphPropertyEnum.IS_DELETED, true);
1282 Either<List<GraphVertex>, TitanOperationStatus> getRes = titanDao.getByCriteria(null, hasProperties, propertiesNotToMatch, parseFlag);
1283 if (getRes.isRight()) {
1284 result = Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(getRes.right().value()));
1286 List<ComponentMetadataData> latestVersionList = getRes.left().value().stream().map(ModelConverter::convertToComponentMetadata).collect(Collectors.toList());
1287 ComponentMetadataData latestVersion = latestVersionList.size() == 1 ? latestVersionList.get(0)
1288 : latestVersionList.stream().max((c1, c2) -> Double.compare(Double.parseDouble(c1.getMetadataDataDefinition().getVersion()), Double.parseDouble(c2.getMetadataDataDefinition().getVersion()))).get();
1289 result = Either.left(latestVersion);
1294 public Either<ComponentMetadataData, StorageOperationStatus> getComponentMetadata(String componentId) {
1296 Either<ComponentMetadataData, StorageOperationStatus> result;
1297 Either<GraphVertex, TitanOperationStatus> getRes = titanDao.getVertexById(componentId, JsonParseFlagEnum.ParseMetadata);
1298 if (getRes.isRight()) {
1299 result = Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(getRes.right().value()));
1301 ComponentMetadataData componentMetadata = ModelConverter.convertToComponentMetadata(getRes.left().value());
1302 result = Either.left(componentMetadata);
1307 private Map<String, ComponentMetadataData> findLatestVersion(List<ComponentMetadataData> resourceDataList) {
1308 Map<Pair<String, String>, ComponentMetadataData> latestVersionMap = new HashMap<Pair<String, String>, ComponentMetadataData>();
1309 for (ComponentMetadataData resourceData : resourceDataList) {
1310 ComponentMetadataData latestVersionData = resourceData;
1312 ComponentMetadataDataDefinition metadataDataDefinition = resourceData.getMetadataDataDefinition();
1313 Pair<String, String> pair = createKeyPair(latestVersionData);
1314 if (latestVersionMap.containsKey(pair)) {
1315 latestVersionData = latestVersionMap.get(pair);
1316 String currentVersion = latestVersionData.getMetadataDataDefinition().getVersion();
1317 String newVersion = metadataDataDefinition.getVersion();
1318 if (CommonBeUtils.compareAsdcComponentVersions(newVersion, currentVersion)) {
1319 latestVersionData = resourceData;
1322 if (log.isDebugEnabled())
1323 log.debug("last certified version of resource = {} version is {}", latestVersionData.getMetadataDataDefinition().getName(), latestVersionData.getMetadataDataDefinition().getVersion());
1325 latestVersionMap.put(pair, latestVersionData);
1328 Map<String, ComponentMetadataData> resVersionMap = new HashMap<String, ComponentMetadataData>();
1329 for (ComponentMetadataData resourceData : latestVersionMap.values()) {
1330 ComponentMetadataData latestVersionData = resourceData;
1331 ComponentMetadataDataDefinition metadataDataDefinition = resourceData.getMetadataDataDefinition();
1332 if (resVersionMap.containsKey(metadataDataDefinition.getUUID())) {
1333 latestVersionData = resVersionMap.get(metadataDataDefinition.getUUID());
1334 String currentVersion = latestVersionData.getMetadataDataDefinition().getVersion();
1335 String newVersion = metadataDataDefinition.getVersion();
1336 if (CommonBeUtils.compareAsdcComponentVersions(newVersion, currentVersion)) {
1337 latestVersionData = resourceData;
1340 if (log.isDebugEnabled())
1341 log.debug("last uuid version of resource = {} version is {}", latestVersionData.getMetadataDataDefinition().getName(), latestVersionData.getMetadataDataDefinition().getVersion());
1342 resVersionMap.put(latestVersionData.getMetadataDataDefinition().getUUID(), latestVersionData);
1345 return resVersionMap;
1348 private Pair<String, String> createKeyPair(ComponentMetadataData metadataData) {
1349 Pair<String, String> pair;
1350 NodeTypeEnum label = NodeTypeEnum.getByName(metadataData.getLabel());
1353 pair = new ImmutablePair<>(metadataData.getMetadataDataDefinition().getName(), ((ResourceMetadataDataDefinition) metadataData.getMetadataDataDefinition()).getResourceType().name());
1356 pair = new ImmutablePair<>(metadataData.getMetadataDataDefinition().getName(), metadataData.getLabel());
1363 public Either<List<Component>, StorageOperationStatus> getLatestVersionNotAbstractComponents(boolean isAbstract, Boolean isHighest, ComponentTypeEnum componentTypeEnum, String internalComponentType, List<String> componentUids) {
1365 Either<List<Component>, StorageOperationStatus> result = null;
1366 List<Component> components = new ArrayList<>();
1367 if (componentUids == null) {
1368 Either<List<String>, StorageOperationStatus> componentUidsRes = getComponentUids(isAbstract, isHighest, componentTypeEnum, internalComponentType, componentUids);
1369 if (componentUidsRes.isRight()) {
1370 result = Either.right(componentUidsRes.right().value());
1372 componentUids = componentUidsRes.left().value();
1375 if (!componentUids.isEmpty()) {
1376 for (String componentUid : componentUids) {
1377 ComponentParametersView componentParametersView = buildComponentViewForNotAbstract();
1378 if (internalComponentType != null && "vl".equalsIgnoreCase(internalComponentType)) {
1379 componentParametersView.setIgnoreCapabilities(false);
1380 componentParametersView.setIgnoreRequirements(false);
1382 Either<ToscaElement, StorageOperationStatus> getToscaElementRes = nodeTemplateOperation.getToscaElementOperation(componentTypeEnum).getLightComponent(componentUid, componentTypeEnum, componentParametersView);
1383 if (getToscaElementRes.isRight()) {
1384 if (log.isDebugEnabled())
1385 log.debug("Failed to fetch resource for error is {}", getToscaElementRes.right().value());
1386 result = Either.right(getToscaElementRes.right().value());
1389 Component component = ModelConverter.convertFromToscaElement(getToscaElementRes.left().value());
1390 component.setContactId(null);
1391 component.setCreationDate(null);
1392 component.setCreatorUserId(null);
1393 component.setCreatorFullName(null);
1394 component.setLastUpdateDate(null);
1395 component.setLastUpdaterUserId(null);
1396 component.setLastUpdaterFullName(null);
1397 component.setNormalizedName(null);
1398 components.add(component);
1401 if (result == null) {
1402 result = Either.left(components);
1407 private Either<List<String>, StorageOperationStatus> getComponentUids(boolean isAbstract, Boolean isHighest, ComponentTypeEnum componentTypeEnum, String internalComponentType, List<String> componentUids) {
1409 Either<List<String>, StorageOperationStatus> result = null;
1410 Either<List<Component>, StorageOperationStatus> getToscaElementsRes = getLatestVersionNotAbstractMetadataOnly(isAbstract, isHighest, componentTypeEnum, internalComponentType);
1411 if (getToscaElementsRes.isRight()) {
1412 result = Either.right(getToscaElementsRes.right().value());
1414 List<Component> collection = getToscaElementsRes.left().value();
1415 if (collection == null) {
1416 componentUids = new ArrayList<>();
1418 componentUids = collection.stream().map(p -> p.getUniqueId()).collect(Collectors.toList());
1421 if (result == null) {
1422 result = Either.left(componentUids);
1427 private ComponentParametersView buildComponentViewForNotAbstract() {
1428 ComponentParametersView componentParametersView = new ComponentParametersView();
1429 componentParametersView.disableAll();
1430 componentParametersView.setIgnoreCategories(false);
1431 componentParametersView.setIgnoreAllVersions(false);
1432 return componentParametersView;
1435 public Either<Boolean, StorageOperationStatus> validateComponentNameExists(String name, ResourceTypeEnum resourceType, ComponentTypeEnum componentType) {
1436 Either<Boolean, StorageOperationStatus> result = validateComponentNameUniqueness(name, resourceType, componentType);
1437 if (result.isLeft()) {
1438 result = Either.left(!result.left().value());
1443 public Either<Boolean, StorageOperationStatus> validateComponentNameUniqueness(String name, ResourceTypeEnum resourceType, ComponentTypeEnum componentType) {
1444 VertexTypeEnum vertexType = ModelConverter.isAtomicComponent(resourceType) ? VertexTypeEnum.NODE_TYPE : VertexTypeEnum.TOPOLOGY_TEMPLATE;
1445 String normalizedName = ValidationUtils.normaliseComponentName(name);
1446 Map<GraphPropertyEnum, Object> properties = new EnumMap<>(GraphPropertyEnum.class);
1447 properties.put(GraphPropertyEnum.NORMALIZED_NAME, normalizedName);
1448 properties.put(GraphPropertyEnum.COMPONENT_TYPE, componentType.name());
1450 Either<List<GraphVertex>, TitanOperationStatus> vertexEither = titanDao.getByCriteria(vertexType, properties, JsonParseFlagEnum.NoParse);
1451 if (vertexEither.isRight() && vertexEither.right().value() != TitanOperationStatus.NOT_FOUND) {
1452 log.debug("failed to get vertex from graph with property normalizedName: {}", normalizedName);
1453 return Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(vertexEither.right().value()));
1455 List<GraphVertex> vertexList = vertexEither.isLeft() ? vertexEither.left().value() : null;
1456 if (vertexList != null && !vertexList.isEmpty()) {
1457 return Either.left(false);
1459 return Either.left(true);
1464 private void fillNodeTypePropsMap(Map<GraphPropertyEnum, Object> hasProps, Map<GraphPropertyEnum, Object> hasNotProps, String internalComponentType) {
1465 switch (internalComponentType.toLowerCase()) {
1468 hasNotProps.put(GraphPropertyEnum.RESOURCE_TYPE, ResourceTypeEnum.VFCMT.name());
1472 hasNotProps.put(GraphPropertyEnum.RESOURCE_TYPE, Arrays.asList(ResourceTypeEnum.VFC.name(), ResourceTypeEnum.VFCMT.name()));
1475 hasProps.put(GraphPropertyEnum.RESOURCE_TYPE, ResourceTypeEnum.VL.name());
1483 private void fillTopologyTemplatePropsMap(Map<GraphPropertyEnum, Object> hasProps, Map<GraphPropertyEnum, Object> hasNotProps, ComponentTypeEnum componentTypeEnum, String internalComponentType) {
1484 switch (componentTypeEnum) {
1486 hasProps.put(GraphPropertyEnum.COMPONENT_TYPE, ComponentTypeEnum.RESOURCE.name());
1489 hasProps.put(GraphPropertyEnum.COMPONENT_TYPE, ComponentTypeEnum.SERVICE.name());
1494 switch (internalComponentType.toLowerCase()) {
1497 hasProps.put(GraphPropertyEnum.RESOURCE_TYPE, ResourceTypeEnum.CVFC.name());
1500 hasNotProps.put(GraphPropertyEnum.RESOURCE_TYPE, ResourceTypeEnum.CVFC.name());
1507 private void fillPropsMap(Map<GraphPropertyEnum, Object> hasProps, Map<GraphPropertyEnum, Object> hasNotProps, String internalComponentType, ComponentTypeEnum componentTypeEnum, boolean isAbstract, VertexTypeEnum internalVertexType) {
1508 hasNotProps.put(GraphPropertyEnum.STATE, LifecycleStateEnum.NOT_CERTIFIED_CHECKOUT.name());
1510 hasNotProps.put(GraphPropertyEnum.IS_DELETED, true);
1511 hasProps.put(GraphPropertyEnum.IS_HIGHEST_VERSION, true);
1512 if (VertexTypeEnum.NODE_TYPE == internalVertexType) {
1513 hasProps.put(GraphPropertyEnum.IS_ABSTRACT, isAbstract);
1514 if (internalComponentType != null) {
1515 fillNodeTypePropsMap(hasProps, hasNotProps, internalComponentType);
1518 fillTopologyTemplatePropsMap(hasProps, hasNotProps, componentTypeEnum, internalComponentType);
1522 private List<VertexTypeEnum> getInternalVertexTypes(ComponentTypeEnum componentTypeEnum, String internalComponentType) {
1523 List<VertexTypeEnum> internalVertexTypes = new ArrayList<>();
1524 if (ComponentTypeEnum.RESOURCE == componentTypeEnum) {
1525 internalVertexTypes.add(VertexTypeEnum.NODE_TYPE);
1527 if (ComponentTypeEnum.SERVICE == componentTypeEnum || "service".equalsIgnoreCase(internalComponentType) || "vf".equalsIgnoreCase(internalComponentType)) {
1528 internalVertexTypes.add(VertexTypeEnum.TOPOLOGY_TEMPLATE);
1530 return internalVertexTypes;
1533 public Either<List<Component>, StorageOperationStatus> getLatestVersionNotAbstractMetadataOnly(boolean isAbstract, Boolean isHighest, ComponentTypeEnum componentTypeEnum, String internalComponentType) {
1534 List<VertexTypeEnum> internalVertexTypes = getInternalVertexTypes(componentTypeEnum, internalComponentType);
1535 List<Component> result = new ArrayList<>();
1536 for (VertexTypeEnum vertexType : internalVertexTypes) {
1537 Either<List<Component>, StorageOperationStatus> listByVertexType = getLatestVersionNotAbstractToscaElementsMetadataOnly(isAbstract, isHighest, componentTypeEnum, internalComponentType, vertexType);
1538 if (listByVertexType.isRight()) {
1539 return listByVertexType;
1541 result.addAll(listByVertexType.left().value());
1543 return Either.left(result);
1547 public Either<List<Component>, StorageOperationStatus> getLatestComponentListByUuid(String componentUuid) {
1548 Map<GraphPropertyEnum, Object> propertiesToMatch = new EnumMap<>(GraphPropertyEnum.class);
1549 propertiesToMatch.put(GraphPropertyEnum.IS_HIGHEST_VERSION, true);
1550 Either<List<Component>, StorageOperationStatus> componentListByUuid = getComponentListByUuid(componentUuid, propertiesToMatch);
1551 return componentListByUuid;
1554 public Either<List<Component>, StorageOperationStatus> getComponentListByUuid(String componentUuid, Map<GraphPropertyEnum, Object> additionalPropertiesToMatch) {
1556 Map<GraphPropertyEnum, Object> propertiesToMatch = new EnumMap<>(GraphPropertyEnum.class);
1558 if (additionalPropertiesToMatch != null) {
1559 propertiesToMatch.putAll(additionalPropertiesToMatch);
1562 propertiesToMatch.put(GraphPropertyEnum.UUID, componentUuid);
1564 Map<GraphPropertyEnum, Object> propertiesNotToMatch = new EnumMap<>(GraphPropertyEnum.class);
1565 propertiesNotToMatch.put(GraphPropertyEnum.IS_DELETED, true);
1567 Either<List<GraphVertex>, TitanOperationStatus> vertexEither = titanDao.getByCriteria(null, propertiesToMatch, propertiesNotToMatch, JsonParseFlagEnum.ParseAll);
1569 if (vertexEither.isRight()) {
1570 log.debug("Couldn't fetch metadata for component with type {} and uuid {}, error: {}", componentUuid, vertexEither.right().value());
1571 return Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(vertexEither.right().value()));
1573 List<GraphVertex> vertexList = vertexEither.isLeft() ? vertexEither.left().value() : null;
1575 if (vertexList == null || vertexList.isEmpty()) {
1576 log.debug("Component with uuid {} was not found", componentUuid);
1577 return Either.right(StorageOperationStatus.NOT_FOUND);
1580 ArrayList<Component> latestComponents = new ArrayList<>();
1581 for (GraphVertex vertex : vertexList) {
1582 Either<Component, StorageOperationStatus> toscaElementByOperation = getToscaElementByOperation(vertex);
1584 if(toscaElementByOperation.isRight()){
1585 log.debug("Could not fetch the following Component by UUID {}", vertex.getUniqueId());
1586 return Either.right(toscaElementByOperation.right().value());
1589 latestComponents.add(toscaElementByOperation.left().value());
1592 if(latestComponents.size() > 1) {
1593 for (Component component : latestComponents) {
1594 if(component.isHighestVersion()){
1595 LinkedList<Component> highestComponent = new LinkedList<>();
1596 highestComponent.add(component);
1597 return Either.left(highestComponent);
1602 return Either.left(latestComponents);
1605 public Either<Component, StorageOperationStatus> getLatestComponentByUuid(String componentUuid) {
1607 Either<List<Component>, StorageOperationStatus> latestVersionListEither = getLatestComponentListByUuid(componentUuid);
1609 if (latestVersionListEither.isRight()) {
1610 return Either.right(latestVersionListEither.right().value());
1613 List<Component> latestVersionList = latestVersionListEither.left().value();
1615 if (latestVersionList.isEmpty()) {
1616 return Either.right(StorageOperationStatus.NOT_FOUND);
1618 Component component = latestVersionList.size() == 1 ? latestVersionList.get(0) : latestVersionList.stream().max((c1, c2) -> Double.compare(Double.parseDouble(c1.getVersion()), Double.parseDouble(c2.getVersion()))).get();
1620 return Either.left(component);
1623 public Either<List<Resource>, StorageOperationStatus> getAllCertifiedResources(boolean isAbstract, Boolean isHighest) {
1625 List<Resource> resources = new ArrayList<>();
1626 Map<GraphPropertyEnum, Object> propertiesToMatch = new EnumMap<>(GraphPropertyEnum.class);
1627 Map<GraphPropertyEnum, Object> propertiesNotToMatch = new EnumMap<>(GraphPropertyEnum.class);
1629 propertiesToMatch.put(GraphPropertyEnum.IS_ABSTRACT, isAbstract);
1630 if (isHighest != null) {
1631 propertiesToMatch.put(GraphPropertyEnum.IS_HIGHEST_VERSION, isHighest.booleanValue());
1633 propertiesToMatch.put(GraphPropertyEnum.STATE, LifecycleStateEnum.CERTIFIED.name());
1634 propertiesToMatch.put(GraphPropertyEnum.COMPONENT_TYPE, ComponentTypeEnum.RESOURCE.name());
1635 propertiesNotToMatch.put(GraphPropertyEnum.IS_DELETED, true);
1637 Either<List<GraphVertex>, TitanOperationStatus> getResourcesRes = titanDao.getByCriteria(null, propertiesToMatch, propertiesNotToMatch, JsonParseFlagEnum.ParseAll);
1639 if (getResourcesRes.isRight()) {
1640 log.debug("Failed to fetch all certified resources. Status is {}", getResourcesRes.right().value());
1641 return Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(getResourcesRes.right().value()));
1643 List<GraphVertex> resourceVerticies = getResourcesRes.left().value();
1644 for (GraphVertex resourceV : resourceVerticies) {
1645 Either<Resource, StorageOperationStatus> getResourceRes = getToscaElement(resourceV);
1646 if (getResourceRes.isRight()) {
1647 return Either.right(getResourceRes.right().value());
1649 resources.add(getResourceRes.left().value());
1651 return Either.left(resources);
1654 public <T extends Component> Either<T, StorageOperationStatus> getLatestByNameAndVersion(String name, String version, JsonParseFlagEnum parseFlag) {
1655 Either<T, StorageOperationStatus> result;
1657 Map<GraphPropertyEnum, Object> hasProperties = new EnumMap<>(GraphPropertyEnum.class);
1658 Map<GraphPropertyEnum, Object> hasNotProperties = new EnumMap<>(GraphPropertyEnum.class);
1660 hasProperties.put(GraphPropertyEnum.NAME, name);
1661 hasProperties.put(GraphPropertyEnum.VERSION, version);
1662 hasProperties.put(GraphPropertyEnum.IS_HIGHEST_VERSION, true);
1664 hasNotProperties.put(GraphPropertyEnum.IS_DELETED, true);
1666 Either<List<GraphVertex>, TitanOperationStatus> getResourceRes = titanDao.getByCriteria(null, hasProperties, hasNotProperties, parseFlag);
1667 if (getResourceRes.isRight()) {
1668 TitanOperationStatus status = getResourceRes.right().value();
1669 log.debug("failed to find resource with name {}, version {}. Status is {} ", name, version, status);
1670 result = Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(status));
1673 return getToscaElementByOperation(getResourceRes.left().value().get(0));
1676 public Either<Resource, StorageOperationStatus> getLatestComponentByCsarOrName(ComponentTypeEnum componentType, String csarUUID, String systemName) {
1677 return getLatestComponentByCsarOrName(componentType, csarUUID, systemName, false, JsonParseFlagEnum.ParseAll);
1680 public Either<Resource, StorageOperationStatus> getLatestComponentByCsarOrName(ComponentTypeEnum componentType, String csarUUID, String systemName, boolean allowDeleted, JsonParseFlagEnum parseFlag) {
1681 Map<GraphPropertyEnum, Object> props = new EnumMap<>(GraphPropertyEnum.class);
1682 props.put(GraphPropertyEnum.CSAR_UUID, csarUUID);
1683 props.put(GraphPropertyEnum.IS_HIGHEST_VERSION, true);
1684 if (componentType != null) {
1685 props.put(GraphPropertyEnum.COMPONENT_TYPE, componentType.name());
1687 Map<GraphPropertyEnum, Object> propsHasNot = new EnumMap<>(GraphPropertyEnum.class);
1688 propsHasNot.put(GraphPropertyEnum.IS_DELETED, true);
1690 GraphVertex resourceMetadataData = null;
1691 List<GraphVertex> resourceMetadataDataList = null;
1692 Either<List<GraphVertex>, TitanOperationStatus> byCsar = titanDao.getByCriteria(null, props, propsHasNot, JsonParseFlagEnum.ParseMetadata);
1693 if (byCsar.isRight()) {
1694 if (TitanOperationStatus.NOT_FOUND == byCsar.right().value()) {
1695 // Fix Defect DE256036
1696 if (StringUtils.isEmpty(systemName)) {
1697 return Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(TitanOperationStatus.NOT_FOUND));
1701 props.put(GraphPropertyEnum.IS_HIGHEST_VERSION, true);
1702 props.put(GraphPropertyEnum.SYSTEM_NAME, systemName);
1703 Either<List<GraphVertex>, TitanOperationStatus> bySystemname = titanDao.getByCriteria(null, props, JsonParseFlagEnum.ParseMetadata);
1704 if (bySystemname.isRight()) {
1705 log.debug("getLatestResourceByCsarOrName - Failed to find by system name {} error {} ", systemName, bySystemname.right().value());
1706 return Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(bySystemname.right().value()));
1708 if (bySystemname.left().value().size() > 2) {
1709 log.debug("getLatestResourceByCsarOrName - getByCriteria(by system name) must return only 2 latest version, but was returned - {}", bySystemname.left().value().size());
1710 return Either.right(StorageOperationStatus.GENERAL_ERROR);
1712 resourceMetadataDataList = bySystemname.left().value();
1713 if (resourceMetadataDataList.size() == 1) {
1714 resourceMetadataData = resourceMetadataDataList.get(0);
1716 for (GraphVertex curResource : resourceMetadataDataList) {
1717 if (!((String) curResource.getJsonMetadataField(JsonPresentationFields.LIFECYCLE_STATE)).equals("CERTIFIED")) {
1718 resourceMetadataData = curResource;
1723 if (resourceMetadataData == null) {
1724 log.debug("getLatestResourceByCsarOrName - getByCriteria(by system name) returned 2 latest CERTIFIED versions");
1725 return Either.right(StorageOperationStatus.GENERAL_ERROR);
1727 if (resourceMetadataData.getJsonMetadataField(JsonPresentationFields.CSAR_UUID) != null && !((String) resourceMetadataData.getJsonMetadataField(JsonPresentationFields.CSAR_UUID)).equals(csarUUID)) {
1728 log.debug("getLatestResourceByCsarOrName - same system name {} but different csarUUID. exist {} and new {} ", systemName, resourceMetadataData.getJsonMetadataField(JsonPresentationFields.CSAR_UUID), csarUUID);
1729 // correct error will be returned from create flow. with all
1730 // correct audit records!!!!!
1731 return Either.right(StorageOperationStatus.NOT_FOUND);
1733 Either<Resource, StorageOperationStatus> resource = getToscaElement((String) resourceMetadataData.getUniqueId());
1737 resourceMetadataDataList = byCsar.left().value();
1738 if (resourceMetadataDataList.size() > 2) {
1739 log.debug("getLatestResourceByCsarOrName - getByCriteria(by csar) must return only 2 latest version, but was returned - {}", byCsar.left().value().size());
1740 return Either.right(StorageOperationStatus.GENERAL_ERROR);
1742 if (resourceMetadataDataList.size() == 1) {
1743 resourceMetadataData = resourceMetadataDataList.get(0);
1745 for (GraphVertex curResource : resourceMetadataDataList) {
1746 if (!((String) curResource.getJsonMetadataField(JsonPresentationFields.LIFECYCLE_STATE)).equals("CERTIFIED")) {
1747 resourceMetadataData = curResource;
1752 if (resourceMetadataData == null) {
1753 log.debug("getLatestResourceByCsarOrName - getByCriteria(by csar) returned 2 latest CERTIFIED versions");
1754 return Either.right(StorageOperationStatus.GENERAL_ERROR);
1756 Either<Resource, StorageOperationStatus> resource = getToscaElement((String) resourceMetadataData.getJsonMetadataField(JsonPresentationFields.UNIQUE_ID), parseFlag);
1762 public Either<Boolean, StorageOperationStatus> validateToscaResourceNameExtends(String templateNameCurrent, String templateNameExtends) {
1764 String currentTemplateNameChecked = templateNameExtends;
1766 while (currentTemplateNameChecked != null && !currentTemplateNameChecked.equalsIgnoreCase(templateNameCurrent)) {
1767 Either<Resource, StorageOperationStatus> latestByToscaResourceName = getLatestByToscaResourceName(currentTemplateNameChecked);
1769 if (latestByToscaResourceName.isRight()) {
1770 return latestByToscaResourceName.right().value() == StorageOperationStatus.NOT_FOUND ? Either.left(false) : Either.right(latestByToscaResourceName.right().value());
1773 Resource value = latestByToscaResourceName.left().value();
1775 if (value.getDerivedFrom() != null) {
1776 currentTemplateNameChecked = value.getDerivedFrom().get(0);
1778 currentTemplateNameChecked = null;
1782 return (currentTemplateNameChecked != null && currentTemplateNameChecked.equalsIgnoreCase(templateNameCurrent)) ? Either.left(true) : Either.left(false);
1785 public Either<List<Component>, StorageOperationStatus> fetchMetaDataByResourceType(String resourceType, ComponentParametersView filterBy) {
1786 Map<GraphPropertyEnum, Object> props = new EnumMap<>(GraphPropertyEnum.class);
1787 props.put(GraphPropertyEnum.RESOURCE_TYPE, resourceType);
1788 props.put(GraphPropertyEnum.IS_HIGHEST_VERSION, true);
1789 Either<List<GraphVertex>, TitanOperationStatus> resourcesByTypeEither = titanDao.getByCriteria(null, props, JsonParseFlagEnum.ParseMetadata);
1791 if (resourcesByTypeEither.isRight()) {
1792 return Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(resourcesByTypeEither.right().value()));
1795 List<GraphVertex> vertexList = resourcesByTypeEither.left().value();
1796 List<Component> components = new ArrayList<>();
1798 for (GraphVertex vertex : vertexList) {
1799 components.add(getToscaElementByOperation(vertex, filterBy).left().value());
1802 return Either.left(components);
1805 public void commit() {
1809 public Either<Service, StorageOperationStatus> updateDistributionStatus(Service service, User user, DistributionStatusEnum distributionStatus) {
1810 Either<GraphVertex, StorageOperationStatus> updateDistributionStatus = topologyTemplateOperation.updateDistributionStatus(service.getUniqueId(), user, distributionStatus);
1811 if (updateDistributionStatus.isRight()) {
1812 return Either.right(updateDistributionStatus.right().value());
1814 GraphVertex serviceV = updateDistributionStatus.left().value();
1815 service.setDistributionStatus(distributionStatus);
1816 service.setLastUpdateDate((Long) serviceV.getJsonMetadataField(JsonPresentationFields.LAST_UPDATE_DATE));
1817 return Either.left(service);
1820 public Either<ComponentMetadataData, StorageOperationStatus> updateComponentLastUpdateDateOnGraph(Component component, Long modificationTime) {
1822 Either<ComponentMetadataData, StorageOperationStatus> result = null;
1823 GraphVertex serviceVertex;
1824 Either<GraphVertex, TitanOperationStatus> updateRes = null;
1825 Either<GraphVertex, TitanOperationStatus> getRes = titanDao.getVertexById(component.getUniqueId(), JsonParseFlagEnum.ParseMetadata);
1826 if (getRes.isRight()) {
1827 TitanOperationStatus status = getRes.right().value();
1828 log.error("Failed to fetch component {}. status is {}", component.getUniqueId(), status);
1829 result = Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(status));
1831 if (result == null) {
1832 serviceVertex = getRes.left().value();
1833 long lastUpdateDate = System.currentTimeMillis();
1834 serviceVertex.setJsonMetadataField(JsonPresentationFields.LAST_UPDATE_DATE, lastUpdateDate);
1835 component.setLastUpdateDate(lastUpdateDate);
1836 updateRes = titanDao.updateVertex(serviceVertex);
1837 if (updateRes.isRight()) {
1838 result = Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(updateRes.right().value()));
1841 if (result == null) {
1842 result = Either.left(ModelConverter.convertToComponentMetadata(updateRes.left().value()));
1847 public TitanDao getTitanDao() {
1851 public Either<List<Service>, StorageOperationStatus> getCertifiedServicesWithDistStatus(Set<DistributionStatusEnum> distStatus) {
1852 Map<GraphPropertyEnum, Object> propertiesToMatch = new EnumMap<>(GraphPropertyEnum.class);
1853 propertiesToMatch.put(GraphPropertyEnum.STATE, LifecycleStateEnum.CERTIFIED.name());
1855 return getServicesWithDistStatus(distStatus, propertiesToMatch);
1858 public Either<List<Service>, StorageOperationStatus> getServicesWithDistStatus(Set<DistributionStatusEnum> distStatus, Map<GraphPropertyEnum, Object> additionalPropertiesToMatch) {
1860 List<Service> servicesAll = new ArrayList<>();
1862 Map<GraphPropertyEnum, Object> propertiesToMatch = new EnumMap<>(GraphPropertyEnum.class);
1863 Map<GraphPropertyEnum, Object> propertiesNotToMatch = new EnumMap<>(GraphPropertyEnum.class);
1865 if (additionalPropertiesToMatch != null && !additionalPropertiesToMatch.isEmpty()) {
1866 propertiesToMatch.putAll(additionalPropertiesToMatch);
1869 propertiesToMatch.put(GraphPropertyEnum.COMPONENT_TYPE, ComponentTypeEnum.SERVICE.name());
1871 propertiesNotToMatch.put(GraphPropertyEnum.IS_DELETED, true);
1873 if (distStatus != null && !distStatus.isEmpty()) {
1874 for (DistributionStatusEnum state : distStatus) {
1875 propertiesToMatch.put(GraphPropertyEnum.DISTRIBUTION_STATUS, state.name());
1876 Either<List<Service>, StorageOperationStatus> fetchServicesByCriteria = fetchServicesByCriteria(servicesAll, propertiesToMatch, propertiesNotToMatch);
1877 if (fetchServicesByCriteria.isRight()) {
1878 return fetchServicesByCriteria;
1880 servicesAll = fetchServicesByCriteria.left().value();
1883 return Either.left(servicesAll);
1885 return fetchServicesByCriteria(servicesAll, propertiesToMatch, propertiesNotToMatch);
1889 // private Either<List<Service>, StorageOperationStatus> fetchServicesByCriteria(List<Service> servicesAll, Map<GraphPropertyEnum, Object> propertiesToMatch, Map<GraphPropertyEnum, Object> propertiesNotToMatch) {
1890 // Either<List<GraphVertex>, TitanOperationStatus> getRes = titanDao.getByCriteria(VertexTypeEnum.TOPOLOGY_TEMPLATE, propertiesToMatch, propertiesNotToMatch, JsonParseFlagEnum.ParseAll);
1891 // if (getRes.isRight()) {
1892 // if (getRes.right().value() != TitanOperationStatus.NOT_FOUND) {
1893 // CommonUtility.addRecordToLog(log, LogLevelEnum.DEBUG, "Failed to fetch certified services by match properties {} not match properties {} . Status is {}. ", propertiesToMatch, propertiesNotToMatch, getRes.right().value());
1894 // return Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(getRes.right().value()));
1897 // for (GraphVertex vertex : getRes.left().value()) {
1898 // Either<Component, StorageOperationStatus> getServiceRes = getToscaElementByOperation(vertex);
1899 // if (getServiceRes.isRight()) {
1900 // CommonUtility.addRecordToLog(log, LogLevelEnum.DEBUG, "Failed to fetch certified service {}. Status is {}. ", vertex.getJsonMetadataField(JsonPresentationFields.NAME), getServiceRes.right().value());
1901 // return Either.right(getServiceRes.right().value());
1903 // servicesAll.add((Service) getToscaElementByOperation(vertex).left().value());
1907 // return Either.left(servicesAll);
1910 private Either<List<Service>, StorageOperationStatus> fetchServicesByCriteria(List<Service> servicesAll, Map<GraphPropertyEnum, Object> propertiesToMatch, Map<GraphPropertyEnum, Object> propertiesNotToMatch) {
1911 Either<List<GraphVertex>, TitanOperationStatus> getRes = titanDao.getByCriteria(VertexTypeEnum.TOPOLOGY_TEMPLATE, propertiesToMatch, propertiesNotToMatch, JsonParseFlagEnum.ParseAll);
1912 if (getRes.isRight()) {
1913 if (getRes.right().value() != TitanOperationStatus.NOT_FOUND) {
1914 CommonUtility.addRecordToLog(log, LogLevelEnum.DEBUG, "Failed to fetch certified services by match properties {} not match properties {} . Status is {}. ", propertiesToMatch, propertiesNotToMatch, getRes.right().value());
1915 return Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(getRes.right().value()));
1918 for (GraphVertex vertex : getRes.left().value()) {
1919 // Either<Component, StorageOperationStatus> getServiceRes = getToscaElementByOperation(vertex);
1920 Either<ToscaElement, StorageOperationStatus> getServiceRes = topologyTemplateOperation.getLightComponent(vertex, ComponentTypeEnum.SERVICE, new ComponentParametersView(true));
1922 if (getServiceRes.isRight()) {
1923 CommonUtility.addRecordToLog(log, LogLevelEnum.DEBUG, "Failed to fetch certified service {}. Status is {}. ", vertex.getJsonMetadataField(JsonPresentationFields.NAME), getServiceRes.right().value());
1924 return Either.right(getServiceRes.right().value());
1926 servicesAll.add(ModelConverter.convertFromToscaElement(getServiceRes.left().value()));
1930 return Either.left(servicesAll);
1933 public void rollback() {
1934 titanDao.rollback();
1937 public StorageOperationStatus addDeploymentArtifactsToInstance(String componentId, ComponentInstance componentInstance, Map<String, ArtifactDefinition> finalDeploymentArtifacts) {
1938 Map<String, ArtifactDataDefinition> instDeplArtifacts = finalDeploymentArtifacts.entrySet().stream().collect(Collectors.toMap(Map.Entry::getKey, e -> new ArtifactDataDefinition(e.getValue())));
1940 return nodeTemplateOperation.addDeploymentArtifactsToInstance(componentId, componentInstance.getUniqueId(), instDeplArtifacts);
1943 public StorageOperationStatus addInformationalArtifactsToInstance(String componentId, ComponentInstance componentInstance, Map<String, ArtifactDefinition> artifacts) {
1944 StorageOperationStatus status = StorageOperationStatus.OK;
1945 if(MapUtils.isNotEmpty(artifacts)){
1946 Map<String, ArtifactDataDefinition> instDeplArtifacts = artifacts.entrySet().stream().collect(Collectors.toMap(Map.Entry::getKey, e -> new ArtifactDataDefinition(e.getValue())));
1947 status= nodeTemplateOperation.addInformationalArtifactsToInstance(componentId, componentInstance.getUniqueId(), instDeplArtifacts);
1952 public StorageOperationStatus generateCustomizationUUIDOnInstance(String componentId, String instanceId) {
1953 return nodeTemplateOperation.generateCustomizationUUIDOnInstance(componentId, instanceId);
1956 public StorageOperationStatus generateCustomizationUUIDOnInstanceGroup(String componentId, String instanceId, List<String> groupInstances) {
1957 return nodeTemplateOperation.generateCustomizationUUIDOnInstanceGroup(componentId, instanceId, groupInstances);
1960 public Either<PropertyDefinition, StorageOperationStatus> addPropertyToResource(String propertyName, PropertyDefinition newPropertyDefinition, Resource resource) {
1962 Either<PropertyDefinition, StorageOperationStatus> result = null;
1963 Either<Component, StorageOperationStatus> getUpdatedComponentRes = null;
1964 newPropertyDefinition.setName(propertyName);
1965 newPropertyDefinition.setParentUniqueId(resource.getUniqueId());
1966 StorageOperationStatus status = getToscaElementOperation(resource).addToscaDataToToscaElement(resource.getUniqueId(), EdgeLabelEnum.PROPERTIES, VertexTypeEnum.PROPERTIES, newPropertyDefinition, JsonPresentationFields.NAME);
1967 if (status != StorageOperationStatus.OK) {
1968 CommonUtility.addRecordToLog(log, LogLevelEnum.DEBUG, "Failed to add the property {} to the resource {}. Status is {}. ", propertyName, resource.getName(), status);
1969 result = Either.right(status);
1971 if (result == null) {
1972 ComponentParametersView filter = new ComponentParametersView(true);
1973 filter.setIgnoreProperties(false);
1974 getUpdatedComponentRes = getToscaElement(resource.getUniqueId(), filter);
1975 if (getUpdatedComponentRes.isRight()) {
1976 CommonUtility.addRecordToLog(log, LogLevelEnum.DEBUG, "Failed to get updated resource {}. Status is {}. ", resource.getUniqueId(), getUpdatedComponentRes.right().value());
1977 result = Either.right(status);
1980 if (result == null) {
1981 PropertyDefinition newProperty = null;
1982 List<PropertyDefinition> properties = ((Resource) getUpdatedComponentRes.left().value()).getProperties();
1983 if (CollectionUtils.isNotEmpty(properties)) {
1984 Optional<PropertyDefinition> newPropertyOptional = properties.stream().filter(p -> p.getName().equals(propertyName)).findAny();
1985 if (newPropertyOptional.isPresent()) {
1986 newProperty = newPropertyOptional.get();
1989 if (newProperty == null) {
1990 CommonUtility.addRecordToLog(log, LogLevelEnum.DEBUG, "Failed to find recently added property {} on the resource {}. Status is {}. ", propertyName, resource.getUniqueId(), StorageOperationStatus.NOT_FOUND);
1991 result = Either.right(StorageOperationStatus.NOT_FOUND);
1993 result = Either.left(newProperty);
1999 public StorageOperationStatus deletePropertyOfResource(Resource resource, String propertyName) {
2000 return getToscaElementOperation(resource).deleteToscaDataElement(resource.getUniqueId(), EdgeLabelEnum.PROPERTIES, VertexTypeEnum.PROPERTIES, propertyName, JsonPresentationFields.NAME);
2003 public StorageOperationStatus deleteAttributeOfResource(Component component, String attributeName) {
2004 return getToscaElementOperation(component).deleteToscaDataElement(component.getUniqueId(), EdgeLabelEnum.ATTRIBUTES, VertexTypeEnum.ATTRIBUTES, attributeName, JsonPresentationFields.NAME);
2007 public StorageOperationStatus deleteInputOfResource(Component resource, String inputName) {
2008 return getToscaElementOperation(resource).deleteToscaDataElement(resource.getUniqueId(), EdgeLabelEnum.INPUTS, VertexTypeEnum.INPUTS, inputName, JsonPresentationFields.NAME);
2011 public Either<PropertyDefinition, StorageOperationStatus> updatePropertyOfResource(Resource resource, PropertyDefinition newPropertyDefinition) {
2013 Either<Component, StorageOperationStatus> getUpdatedComponentRes = null;
2014 Either<PropertyDefinition, StorageOperationStatus> result = null;
2015 StorageOperationStatus status = getToscaElementOperation(resource).updateToscaDataOfToscaElement(resource.getUniqueId(), EdgeLabelEnum.PROPERTIES, VertexTypeEnum.PROPERTIES, newPropertyDefinition, JsonPresentationFields.NAME);
2016 if (status != StorageOperationStatus.OK) {
2017 CommonUtility.addRecordToLog(log, LogLevelEnum.DEBUG, "Failed to add the property {} to the resource {}. Status is {}. ", newPropertyDefinition.getName(), resource.getName(), status);
2018 result = Either.right(status);
2020 if (result == null) {
2021 ComponentParametersView filter = new ComponentParametersView(true);
2022 filter.setIgnoreProperties(false);
2023 getUpdatedComponentRes = getToscaElement(resource.getUniqueId(), filter);
2024 if (getUpdatedComponentRes.isRight()) {
2025 CommonUtility.addRecordToLog(log, LogLevelEnum.DEBUG, "Failed to get updated resource {}. Status is {}. ", resource.getUniqueId(), getUpdatedComponentRes.right().value());
2026 result = Either.right(status);
2029 if (result == null) {
2030 Optional<PropertyDefinition> newProperty = ((Resource) getUpdatedComponentRes.left().value()).getProperties().stream().filter(p -> p.getName().equals(newPropertyDefinition.getName())).findAny();
2031 if (newProperty.isPresent()) {
2032 result = Either.left(newProperty.get());
2034 CommonUtility.addRecordToLog(log, LogLevelEnum.DEBUG, "Failed to find recently added property {} on the resource {}. Status is {}. ", newPropertyDefinition.getName(), resource.getUniqueId(), StorageOperationStatus.NOT_FOUND);
2035 result = Either.right(StorageOperationStatus.NOT_FOUND);
2041 public Either<PropertyDefinition, StorageOperationStatus> addAttributeOfResource(Component component, PropertyDefinition newAttributeDef) {
2043 Either<Component, StorageOperationStatus> getUpdatedComponentRes = null;
2044 Either<PropertyDefinition, StorageOperationStatus> result = null;
2045 if (newAttributeDef.getUniqueId() == null || newAttributeDef.getUniqueId().isEmpty()) {
2046 String attUniqueId = UniqueIdBuilder.buildAttributeUid(component.getUniqueId(), newAttributeDef.getName());
2047 newAttributeDef.setUniqueId(attUniqueId);
2050 StorageOperationStatus status = getToscaElementOperation(component).addToscaDataToToscaElement(component.getUniqueId(), EdgeLabelEnum.ATTRIBUTES, VertexTypeEnum.ATTRIBUTES, newAttributeDef, JsonPresentationFields.NAME);
2051 if (status != StorageOperationStatus.OK) {
2052 CommonUtility.addRecordToLog(log, LogLevelEnum.DEBUG, "Failed to add the property {} to the resource {}. Status is {}. ", newAttributeDef.getName(), component.getName(), status);
2053 result = Either.right(status);
2055 if (result == null) {
2056 ComponentParametersView filter = new ComponentParametersView(true);
2057 filter.setIgnoreAttributesFrom(false);
2058 getUpdatedComponentRes = getToscaElement(component.getUniqueId(), filter);
2059 if (getUpdatedComponentRes.isRight()) {
2060 CommonUtility.addRecordToLog(log, LogLevelEnum.DEBUG, "Failed to get updated resource {}. Status is {}. ", component.getUniqueId(), getUpdatedComponentRes.right().value());
2061 result = Either.right(status);
2064 if (result == null) {
2065 Optional<PropertyDefinition> newAttribute = ((Resource) getUpdatedComponentRes.left().value()).getAttributes().stream().filter(p -> p.getName().equals(newAttributeDef.getName())).findAny();
2066 if (newAttribute.isPresent()) {
2067 result = Either.left(newAttribute.get());
2069 CommonUtility.addRecordToLog(log, LogLevelEnum.DEBUG, "Failed to find recently added property {} on the resource {}. Status is {}. ", newAttributeDef.getName(), component.getUniqueId(), StorageOperationStatus.NOT_FOUND);
2070 result = Either.right(StorageOperationStatus.NOT_FOUND);
2076 public Either<PropertyDefinition, StorageOperationStatus> updateAttributeOfResource(Component component, PropertyDefinition newAttributeDef) {
2078 Either<Component, StorageOperationStatus> getUpdatedComponentRes = null;
2079 Either<PropertyDefinition, StorageOperationStatus> result = null;
2080 StorageOperationStatus status = getToscaElementOperation(component).updateToscaDataOfToscaElement(component.getUniqueId(), EdgeLabelEnum.ATTRIBUTES, VertexTypeEnum.ATTRIBUTES, newAttributeDef, JsonPresentationFields.NAME);
2081 if (status != StorageOperationStatus.OK) {
2082 CommonUtility.addRecordToLog(log, LogLevelEnum.DEBUG, "Failed to add the property {} to the resource {}. Status is {}. ", newAttributeDef.getName(), component.getName(), status);
2083 result = Either.right(status);
2085 if (result == null) {
2086 ComponentParametersView filter = new ComponentParametersView(true);
2087 filter.setIgnoreAttributesFrom(false);
2088 getUpdatedComponentRes = getToscaElement(component.getUniqueId(), filter);
2089 if (getUpdatedComponentRes.isRight()) {
2090 CommonUtility.addRecordToLog(log, LogLevelEnum.DEBUG, "Failed to get updated resource {}. Status is {}. ", component.getUniqueId(), getUpdatedComponentRes.right().value());
2091 result = Either.right(status);
2094 if (result == null) {
2095 Optional<PropertyDefinition> newProperty = ((Resource) getUpdatedComponentRes.left().value()).getAttributes().stream().filter(p -> p.getName().equals(newAttributeDef.getName())).findAny();
2096 if (newProperty.isPresent()) {
2097 result = Either.left(newProperty.get());
2099 CommonUtility.addRecordToLog(log, LogLevelEnum.DEBUG, "Failed to find recently added property {} on the resource {}. Status is {}. ", newAttributeDef.getName(), component.getUniqueId(), StorageOperationStatus.NOT_FOUND);
2100 result = Either.right(StorageOperationStatus.NOT_FOUND);
2106 public Either<InputDefinition, StorageOperationStatus> updateInputOfComponent(Component component, InputDefinition newInputDefinition) {
2108 Either<Component, StorageOperationStatus> getUpdatedComponentRes = null;
2109 Either<InputDefinition, StorageOperationStatus> result = null;
2110 StorageOperationStatus status = getToscaElementOperation(component).updateToscaDataOfToscaElement(component.getUniqueId(), EdgeLabelEnum.INPUTS, VertexTypeEnum.INPUTS, newInputDefinition, JsonPresentationFields.NAME);
2111 if (status != StorageOperationStatus.OK) {
2112 CommonUtility.addRecordToLog(log, LogLevelEnum.DEBUG, "Failed to update the input {} to the component {}. Status is {}. ", newInputDefinition.getName(), component.getName(), status);
2113 result = Either.right(status);
2115 if (result == null) {
2116 ComponentParametersView filter = new ComponentParametersView(true);
2117 filter.setIgnoreInputs(false);
2118 getUpdatedComponentRes = getToscaElement(component.getUniqueId(), filter);
2119 if (getUpdatedComponentRes.isRight()) {
2120 CommonUtility.addRecordToLog(log, LogLevelEnum.DEBUG, "Failed to get updated resource {}. Status is {}. ", component.getUniqueId(), getUpdatedComponentRes.right().value());
2121 result = Either.right(status);
2124 if (result == null) {
2125 Optional<InputDefinition> updatedInput = getUpdatedComponentRes.left().value().getInputs().stream().filter(p -> p.getName().equals(newInputDefinition.getName())).findAny();
2126 if (updatedInput.isPresent()) {
2127 result = Either.left(updatedInput.get());
2129 CommonUtility.addRecordToLog(log, LogLevelEnum.DEBUG, "Failed to find recently updated inputs {} on the resource {}. Status is {}. ", newInputDefinition.getName(), component.getUniqueId(), StorageOperationStatus.NOT_FOUND);
2130 result = Either.right(StorageOperationStatus.NOT_FOUND);
2137 * method - ename the group instances after referenced container name renamed
2138 * flow - VF rename -(triggers)-> Group rename
2140 * @param containerComponent - container such as service
2141 * @param componentInstance - context component
2142 * @param componentInstanceId - id
2144 * @return - successfull/failed status
2146 public Either<StorageOperationStatus,StorageOperationStatus> cleanAndAddGroupInstancesToComponentInstance(Component containerComponent, ComponentInstance componentInstance, String componentInstanceId){
2147 String uniqueId = componentInstance.getUniqueId();
2148 StorageOperationStatus status = nodeTemplateOperation.deleteToscaDataDeepElementsBlockToToscaElement( containerComponent.getUniqueId(), EdgeLabelEnum.INST_GROUPS, VertexTypeEnum.INST_GROUPS, uniqueId );
2149 if (status != StorageOperationStatus.OK && status != StorageOperationStatus.NOT_FOUND) {
2150 CommonUtility.addRecordToLog(log, LogLevelEnum.DEBUG, "Failed to delete group instances for container {}. error {] ", componentInstanceId, status);
2151 return Either.right(status);
2153 if(componentInstance.getGroupInstances() != null){
2154 status = addGroupInstancesToComponentInstance( containerComponent , componentInstance, componentInstance.getGroupInstances() );
2155 if (status != StorageOperationStatus.OK && status != StorageOperationStatus.NOT_FOUND) {
2156 CommonUtility.addRecordToLog(log, LogLevelEnum.DEBUG, "Failed to add group instances for container {}. error {] ", componentInstanceId, status);
2157 return Either.right(status);
2160 return Either.left(status);
2163 public StorageOperationStatus addGroupInstancesToComponentInstance(Component containerComponent, ComponentInstance componentInstance, List<GroupDefinition> groups, Map<String, List<ArtifactDefinition>> groupInstancesArtifacts) {
2164 return nodeTemplateOperation.addGroupInstancesToComponentInstance(containerComponent, componentInstance, groups, groupInstancesArtifacts);
2167 public Either<List<GroupDefinition>, StorageOperationStatus> updateGroupsOnComponent(Component component, ComponentTypeEnum componentType, List<GroupDataDefinition> updatedGroups) {
2168 return groupsOperation.updateGroups(component, componentType, updatedGroups);
2171 public Either<List<GroupInstance>, StorageOperationStatus> updateGroupInstancesOnComponent(Component component, ComponentTypeEnum componentType, String instanceId, List<GroupInstance> updatedGroupInstances) {
2172 return groupsOperation.updateGroupInstances(component, componentType, instanceId, updatedGroupInstances);
2175 public StorageOperationStatus addGroupInstancesToComponentInstance(Component containerComponent, ComponentInstance componentInstance, List<GroupInstance> groupInstances) {
2176 return nodeTemplateOperation.addGroupInstancesToComponentInstance(containerComponent, componentInstance, groupInstances);
2179 public StorageOperationStatus addDeploymentArtifactsToComponentInstance(Component containerComponent, ComponentInstance componentInstance, Map<String, ArtifactDefinition> deploymentArtifacts) {
2180 return nodeTemplateOperation.addDeploymentArtifactsToComponentInstance(containerComponent, componentInstance, deploymentArtifacts);
2183 public StorageOperationStatus updateComponentInstanceProperty(Component containerComponent, String componentInstanceId, ComponentInstanceProperty property) {
2184 return nodeTemplateOperation.updateComponentInstanceProperty(containerComponent, componentInstanceId, property);
2187 public StorageOperationStatus addComponentInstanceProperty(Component containerComponent, String componentInstanceId, ComponentInstanceProperty property) {
2188 return nodeTemplateOperation.addComponentInstanceProperty(containerComponent, componentInstanceId, property);
2191 public StorageOperationStatus updateComponentInstanceInput(Component containerComponent, String componentInstanceId, ComponentInstanceInput property) {
2192 return nodeTemplateOperation.updateComponentInstanceInput(containerComponent, componentInstanceId, property);
2195 public StorageOperationStatus addComponentInstanceInput(Component containerComponent, String componentInstanceId, ComponentInstanceInput property) {
2196 return nodeTemplateOperation.addComponentInstanceInput(containerComponent, componentInstanceId, property);
2199 public void setNodeTypeOperation(NodeTypeOperation nodeTypeOperation) {
2200 this.nodeTypeOperation = nodeTypeOperation;
2203 public void setTopologyTemplateOperation(TopologyTemplateOperation topologyTemplateOperation) {
2204 this.topologyTemplateOperation = topologyTemplateOperation;
2207 public StorageOperationStatus deleteComponentInstanceInputsFromTopologyTemplate(Component containerComponent, ComponentTypeEnum componentType, List<InputDefinition> inputsToDelete) {
2208 return topologyTemplateOperation.deleteToscaDataElements(containerComponent.getUniqueId(), EdgeLabelEnum.INPUTS, inputsToDelete.stream().map(i -> i.getName()).collect(Collectors.toList()));
2211 public StorageOperationStatus deleteAllCalculatedCapabilitiesRequirements(String topologyTemplateId) {
2212 StorageOperationStatus status = topologyTemplateOperation.removeToscaData(topologyTemplateId, EdgeLabelEnum.CALCULATED_CAPABILITIES, VertexTypeEnum.CALCULATED_CAPABILITIES);
2213 if(status == StorageOperationStatus.OK){
2214 status = topologyTemplateOperation.removeToscaData(topologyTemplateId, EdgeLabelEnum.CALCULATED_REQUIREMENTS, VertexTypeEnum.CALCULATED_REQUIREMENTS);