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);
280 public <T extends Component> Either<T, StorageOperationStatus> getFullLatestComponentByToscaResourceName(String toscaResourceName) {
281 return getLatestByName(GraphPropertyEnum.TOSCA_RESOURCE_NAME, toscaResourceName, JsonParseFlagEnum.ParseAll);
284 public <T extends Component> Either<T, StorageOperationStatus> getLatestByName(String resourceName) {
285 return getLatestByName(GraphPropertyEnum.NAME, resourceName);
289 public Either<Integer, StorageOperationStatus> validateCsarUuidUniqueness(String csarUUID) {
290 Either<List<ToscaElement>, StorageOperationStatus> byCsar = null;
292 Map<GraphPropertyEnum, Object> properties = new HashMap<GraphPropertyEnum, Object>();
293 properties.put(GraphPropertyEnum.CSAR_UUID, csarUUID);
295 Either<List<GraphVertex>, TitanOperationStatus> resources = titanDao.getByCriteria(null, properties, JsonParseFlagEnum.ParseMetadata);
297 if (resources.isRight()) {
298 if (resources.right().value() == TitanOperationStatus.NOT_FOUND) {
299 return Either.left(new Integer(0));
301 log.debug("failed to get resources from graph with property name: {}", csarUUID);
302 return Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(resources.right().value()));
306 List<GraphVertex> resourceList = (resources.isLeft() ? resources.left().value() : null);
308 return Either.left(new Integer(resourceList.size()));
312 public <T extends Component> Either<Set<T>, StorageOperationStatus> getFollowed(String userId, Set<LifecycleStateEnum> lifecycleStates, Set<LifecycleStateEnum> lastStateStates, ComponentTypeEnum componentType) {
313 Either<List<ToscaElement>, StorageOperationStatus> followedResources;
314 if (componentType == ComponentTypeEnum.RESOURCE) {
315 followedResources = nodeTypeOperation.getFollowedComponent(userId, lifecycleStates, lastStateStates, componentType);
317 followedResources = topologyTemplateOperation.getFollowedComponent(userId, lifecycleStates, lastStateStates, componentType);
320 Set<T> components = new HashSet<>();
321 if (followedResources.isRight() && followedResources.right().value() != StorageOperationStatus.NOT_FOUND) {
322 return Either.right(followedResources.right().value());
324 if (followedResources.isLeft()) {
325 List<ToscaElement> toscaElements = followedResources.left().value();
326 toscaElements.forEach(te -> {
327 T component = ModelConverter.convertFromToscaElement(te);
328 components.add(component);
331 return Either.left(components);
334 public Either<Resource, StorageOperationStatus> getLatestCertifiedNodeTypeByToscaResourceName(String toscaResourceName) {
336 return getLatestCertifiedByToscaResourceName(toscaResourceName, VertexTypeEnum.NODE_TYPE, JsonParseFlagEnum.ParseMetadata);
339 public Either<Resource, StorageOperationStatus> getLatestCertifiedByToscaResourceName(String toscaResourceName, VertexTypeEnum vertexType, JsonParseFlagEnum parseFlag) {
341 Either<Resource, StorageOperationStatus> result = null;
342 Map<GraphPropertyEnum, Object> props = new HashMap<GraphPropertyEnum, Object>();
343 props.put(GraphPropertyEnum.TOSCA_RESOURCE_NAME, toscaResourceName);
344 props.put(GraphPropertyEnum.IS_HIGHEST_VERSION, true);
345 props.put(GraphPropertyEnum.STATE, LifecycleStateEnum.CERTIFIED.name());
346 Either<List<GraphVertex>, TitanOperationStatus> getLatestRes = titanDao.getByCriteria(vertexType, props, parseFlag);
348 if (getLatestRes.isRight()) {
349 TitanOperationStatus status = getLatestRes.right().value();
350 CommonUtility.addRecordToLog(log, LogLevelEnum.DEBUG, "Failed to fetch {} with name {}. status={} ", vertexType, toscaResourceName, status);
351 result = Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(status));
353 if (result == null) {
354 List<GraphVertex> resources = getLatestRes.left().value();
355 double version = 0.0;
356 GraphVertex highestResource = null;
357 for (GraphVertex resource : resources) {
358 double resourceVersion = Double.parseDouble((String) resource.getJsonMetadataField(JsonPresentationFields.VERSION));
359 if (resourceVersion > version) {
360 version = resourceVersion;
361 highestResource = resource;
364 result = getToscaElement(highestResource.getUniqueId());
369 public Either<Boolean, StorageOperationStatus> validateToscaResourceNameExists(String templateName) {
370 Either<Boolean, StorageOperationStatus> validateUniquenessRes = validateToscaResourceNameUniqueness(templateName);
371 if (validateUniquenessRes.isLeft()) {
372 return Either.left(!validateUniquenessRes.left().value());
374 return validateUniquenessRes;
377 public Either<RequirementCapabilityRelDef, StorageOperationStatus> dissociateResourceInstances(String componentId, RequirementCapabilityRelDef requirementDef) {
378 return nodeTemplateOperation.dissociateResourceInstances(componentId, requirementDef);
382 public StorageOperationStatus associateResourceInstances(String componentId, List<RequirementCapabilityRelDef> relations) {
383 Either<List<RequirementCapabilityRelDef>, StorageOperationStatus> status = nodeTemplateOperation.associateResourceInstances(componentId, relations);
384 if (status.isRight()) {
385 return status.right().value();
387 return StorageOperationStatus.OK;
390 protected Either<Boolean, StorageOperationStatus> validateToscaResourceNameUniqueness(String name) {
392 Map<GraphPropertyEnum, Object> properties = new HashMap<GraphPropertyEnum, Object>();
393 properties.put(GraphPropertyEnum.TOSCA_RESOURCE_NAME, name);
395 Either<List<GraphVertex>, TitanOperationStatus> resources = titanDao.getByCriteria(null, properties, JsonParseFlagEnum.ParseMetadata);
397 if (resources.isRight() && resources.right().value() != TitanOperationStatus.NOT_FOUND) {
398 log.debug("failed to get resources from graph with property name: {}", name);
399 return Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(resources.right().value()));
401 List<GraphVertex> resourceList = (resources.isLeft() ? resources.left().value() : null);
402 if (resourceList != null && resourceList.size() > 0) {
403 if (log.isDebugEnabled()) {
404 StringBuilder builder = new StringBuilder();
405 for (GraphVertex resourceData : resourceList) {
406 builder.append(resourceData.getUniqueId() + "|");
408 log.debug("resources with property name:{} exists in graph. found {}", name, builder.toString());
410 return Either.left(false);
412 log.debug("resources with property name:{} does not exists in graph", name);
413 return Either.left(true);
420 * @param newComponent
421 * @param oldComponent
424 public <T extends Component> Either<T, StorageOperationStatus> overrideComponent(T newComponent, T oldComponent) {
427 // newComponent.setInterfaces(oldComponent.getInterfaces);
428 newComponent.setArtifacts(oldComponent.getArtifacts());
429 newComponent.setDeploymentArtifacts(oldComponent.getDeploymentArtifacts());
430 newComponent.setGroups(oldComponent.getGroups());
431 newComponent.setInputs(null);
432 newComponent.setLastUpdateDate(null);
433 newComponent.setHighestVersion(true);
435 Either<GraphVertex, TitanOperationStatus> componentVEither = titanDao.getVertexById(oldComponent.getUniqueId(), JsonParseFlagEnum.NoParse);
436 if (componentVEither.isRight()) {
437 log.debug("Falied to fetch component {} error {}", oldComponent.getUniqueId(), componentVEither.right().value());
438 return Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(componentVEither.right().value()));
440 GraphVertex componentv = componentVEither.left().value();
441 Either<GraphVertex, TitanOperationStatus> parentVertexEither = titanDao.getParentVertex(componentv, EdgeLabelEnum.VERSION, JsonParseFlagEnum.NoParse);
442 if (parentVertexEither.isRight() && parentVertexEither.right().value() != TitanOperationStatus.NOT_FOUND) {
443 log.debug("Falied to fetch parent version for component {} error {}", oldComponent.getUniqueId(), parentVertexEither.right().value());
444 return Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(parentVertexEither.right().value()));
447 Either<ToscaElement, StorageOperationStatus> deleteToscaComponent = deleteToscaElement(componentv);
448 if (deleteToscaComponent.isRight()) {
449 log.debug("Falied to remove old component {} error {}", oldComponent.getUniqueId(), deleteToscaComponent.right().value());
450 return Either.right(deleteToscaComponent.right().value());
452 Either<T, StorageOperationStatus> createToscaComponent = createToscaComponent(newComponent);
453 if (createToscaComponent.isRight()) {
454 log.debug("Falied to create tosca element component {} error {}", newComponent.getUniqueId(), createToscaComponent.right().value());
455 return Either.right(createToscaComponent.right().value());
457 T newElement = createToscaComponent.left().value();
458 Either<GraphVertex, TitanOperationStatus> newVersionEither = titanDao.getVertexById(newElement.getUniqueId(), JsonParseFlagEnum.NoParse);
459 if (newVersionEither.isRight()) {
460 log.debug("Falied to fetch new tosca element component {} error {}", newComponent.getUniqueId(), newVersionEither.right().value());
461 return Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(newVersionEither.right().value()));
463 if (parentVertexEither.isLeft()) {
464 GraphVertex previousVersionV = parentVertexEither.left().value();
465 TitanOperationStatus createEdge = titanDao.createEdge(previousVersionV, newVersionEither.left().value(), EdgeLabelEnum.VERSION, null);
466 if (createEdge != TitanOperationStatus.OK) {
467 log.debug("Falied to associate to previous version {} new version {} error {}", previousVersionV.getUniqueId(), newVersionEither.right().value(), createEdge);
468 return Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(createEdge));
471 return Either.left(newElement);
476 * @param componentToUpdate
479 public <T extends Component> Either<T, StorageOperationStatus> updateToscaElement(T componentToUpdate) {
480 return updateToscaElement(componentToUpdate, new ComponentParametersView());
485 * @param componentToUpdate
487 * @param filterResult
490 public <T extends Component> Either<T, StorageOperationStatus> updateToscaElement(T componentToUpdate, ComponentParametersView filterResult) {
491 String componentId = componentToUpdate.getUniqueId();
492 Either<GraphVertex, TitanOperationStatus> getVertexEither = titanDao.getVertexById(componentId, JsonParseFlagEnum.ParseAll);
493 if (getVertexEither.isRight()) {
494 log.debug("Couldn't fetch component with and unique id {}, error: {}", componentId, getVertexEither.right().value());
495 return Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(getVertexEither.right().value()));
497 GraphVertex elementV = getVertexEither.left().value();
498 ToscaElementOperation toscaElementOperation = getToscaElementOperation(elementV);
500 ToscaElement toscaElementToUpdate = ModelConverter.convertToToscaElement(componentToUpdate);
501 Either<ToscaElement, StorageOperationStatus> updateToscaElement = toscaElementOperation.updateToscaElement(toscaElementToUpdate, elementV, filterResult);
502 if (updateToscaElement.isRight()) {
503 log.debug("Failed to update tosca element {} error {}", componentId, updateToscaElement.right().value());
504 return Either.right(updateToscaElement.right().value());
506 return Either.left(ModelConverter.convertFromToscaElement(updateToscaElement.left().value()));
509 private <T extends Component> Either<T, StorageOperationStatus> getLatestByName(GraphPropertyEnum property, String nodeName) {
510 Either<T, StorageOperationStatus> result;
512 Map<GraphPropertyEnum, Object> propertiesToMatch = new EnumMap<>(GraphPropertyEnum.class);
513 Map<GraphPropertyEnum, Object> propertiesNotToMatch = new EnumMap<>(GraphPropertyEnum.class);
515 propertiesToMatch.put(property, nodeName);
516 propertiesToMatch.put(GraphPropertyEnum.IS_HIGHEST_VERSION, true);
518 propertiesNotToMatch.put(GraphPropertyEnum.IS_DELETED, true);
520 Either<List<GraphVertex>, TitanOperationStatus> highestResources = titanDao.getByCriteria(null, propertiesToMatch, propertiesNotToMatch, JsonParseFlagEnum.ParseMetadata);
521 if (highestResources.isRight()) {
522 TitanOperationStatus status = highestResources.right().value();
523 log.debug("failed to find resource with name {}. status={} ", nodeName, status);
524 result = Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(status));
528 List<GraphVertex> resources = highestResources.left().value();
529 double version = 0.0;
530 GraphVertex highestResource = null;
531 for (GraphVertex vertex : resources) {
532 Object versionObj = vertex.getMetadataProperty(GraphPropertyEnum.VERSION);
533 double resourceVersion = Double.valueOf((String) versionObj);
534 if (resourceVersion > version) {
535 version = resourceVersion;
536 highestResource = vertex;
539 return getToscaElementByOperation(highestResource);
542 private <T extends Component> Either<T, StorageOperationStatus> getLatestByName(GraphPropertyEnum property, String nodeName, JsonParseFlagEnum parseFlag) {
543 Either<T, StorageOperationStatus> result;
545 Map<GraphPropertyEnum, Object> propertiesToMatch = new EnumMap<>(GraphPropertyEnum.class);
546 Map<GraphPropertyEnum, Object> propertiesNotToMatch = new EnumMap<>(GraphPropertyEnum.class);
548 propertiesToMatch.put(property, nodeName);
549 propertiesToMatch.put(GraphPropertyEnum.IS_HIGHEST_VERSION, true);
551 propertiesNotToMatch.put(GraphPropertyEnum.IS_DELETED, true);
553 Either<List<GraphVertex>, TitanOperationStatus> highestResources = titanDao.getByCriteria(null, propertiesToMatch, propertiesNotToMatch, parseFlag);
554 if (highestResources.isRight()) {
555 TitanOperationStatus status = highestResources.right().value();
556 log.debug("failed to find resource with name {}. status={} ", nodeName, status);
557 result = Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(status));
561 List<GraphVertex> resources = highestResources.left().value();
562 double version = 0.0;
563 GraphVertex highestResource = null;
564 for (GraphVertex vertex : resources) {
565 Object versionObj = vertex.getMetadataProperty(GraphPropertyEnum.VERSION);
566 double resourceVersion = Double.valueOf((String) versionObj);
567 if (resourceVersion > version) {
568 version = resourceVersion;
569 highestResource = vertex;
572 return getToscaElementByOperation(highestResource);
575 public <T extends Component> Either<List<T>, StorageOperationStatus> getBySystemName(ComponentTypeEnum componentType, String systemName) {
577 Either<List<T>, StorageOperationStatus> result = null;
578 Either<T, StorageOperationStatus> getComponentRes;
579 List<T> components = new ArrayList<>();
580 List<GraphVertex> componentVertices;
581 Map<GraphPropertyEnum, Object> propertiesToMatch = new EnumMap<>(GraphPropertyEnum.class);
582 Map<GraphPropertyEnum, Object> propertiesNotToMatch = new EnumMap<>(GraphPropertyEnum.class);
584 propertiesToMatch.put(GraphPropertyEnum.SYSTEM_NAME, systemName);
585 if (componentType != null)
586 propertiesToMatch.put(GraphPropertyEnum.COMPONENT_TYPE, componentType.name());
588 propertiesNotToMatch.put(GraphPropertyEnum.IS_DELETED, true);
590 Either<List<GraphVertex>, TitanOperationStatus> getComponentsRes = titanDao.getByCriteria(null, propertiesToMatch, propertiesNotToMatch, JsonParseFlagEnum.ParseAll);
591 if (getComponentsRes.isRight()) {
592 TitanOperationStatus status = getComponentsRes.right().value();
593 log.debug("Failed to fetch the component with system name {}. Status is {} ", systemName, status);
594 result = Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(status));
596 if (result == null) {
597 componentVertices = getComponentsRes.left().value();
598 for (GraphVertex componentVertex : componentVertices) {
599 getComponentRes = getToscaElementByOperation(componentVertex);
600 if (getComponentRes.isRight()) {
601 log.debug("Failed to get the component {}. Status is {} ", componentVertex.getJsonMetadataField(JsonPresentationFields.NAME), getComponentRes.right().value());
602 result = Either.right(getComponentRes.right().value());
605 T componentBySystemName = getComponentRes.left().value();
606 log.debug("Found component, id: {}", componentBySystemName.getUniqueId());
607 components.add(componentBySystemName);
610 if (result == null) {
611 result = Either.left(components);
616 public <T extends Component> Either<T, StorageOperationStatus> getComponentByNameAndVersion(ComponentTypeEnum componentType, String name, String version) {
617 return getComponentByNameAndVersion(componentType, name, version, JsonParseFlagEnum.ParseAll);
620 public <T extends Component> Either<T, StorageOperationStatus> getComponentByNameAndVersion(ComponentTypeEnum componentType, String name, String version, JsonParseFlagEnum parseFlag) {
621 Either<T, StorageOperationStatus> result;
623 Map<GraphPropertyEnum, Object> hasProperties = new EnumMap<>(GraphPropertyEnum.class);
624 Map<GraphPropertyEnum, Object> hasNotProperties = new EnumMap<>(GraphPropertyEnum.class);
626 hasProperties.put(GraphPropertyEnum.NAME, name);
627 hasProperties.put(GraphPropertyEnum.VERSION, version);
628 hasNotProperties.put(GraphPropertyEnum.IS_DELETED, true);
629 if (componentType != null) {
630 hasProperties.put(GraphPropertyEnum.COMPONENT_TYPE, componentType.name());
632 Either<List<GraphVertex>, TitanOperationStatus> getResourceRes = titanDao.getByCriteria(null, hasProperties, hasNotProperties, parseFlag);
633 if (getResourceRes.isRight()) {
634 TitanOperationStatus status = getResourceRes.right().value();
635 log.debug("failed to find resource with name {}, version {}. Status is {} ", name, version, status);
636 result = Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(status));
639 return getToscaElementByOperation(getResourceRes.left().value().get(0));
642 public <T extends Component> Either<List<T>, StorageOperationStatus> getCatalogComponents(ComponentTypeEnum componentType, List<OriginTypeEnum> excludeTypes, boolean isHighestVersions) {
643 List<T> components = new ArrayList<>();
644 Either<List<ToscaElement>, StorageOperationStatus> catalogDataResult;
645 List<ToscaElement> toscaElements = new ArrayList<>();
646 List<ResourceTypeEnum> excludedResourceTypes =
647 Optional.ofNullable(excludeTypes).orElse(Collections.emptyList())
649 .filter(type -> !type.equals(OriginTypeEnum.SERVICE))
650 .map(type -> ResourceTypeEnum.getTypeByName(type.name())).collect(Collectors.toList());
652 switch (componentType) {
654 catalogDataResult = nodeTypeOperation.getElementCatalogData(ComponentTypeEnum.RESOURCE,excludedResourceTypes , isHighestVersions);
655 if (catalogDataResult.isRight()) {
656 return Either.right(catalogDataResult.right().value());
658 toscaElements = catalogDataResult.left().value();
661 if (excludeTypes!= null && excludeTypes.contains(OriginTypeEnum.SERVICE)) {
664 catalogDataResult = topologyTemplateOperation.getElementCatalogData(ComponentTypeEnum.SERVICE, null, isHighestVersions);
665 if (catalogDataResult.isRight()) {
666 return Either.right(catalogDataResult.right().value());
668 toscaElements = catalogDataResult.left().value();
671 log.debug("Not supported component type {}", componentType);
672 return Either.right(StorageOperationStatus.BAD_REQUEST);
674 toscaElements.forEach(te -> {
675 T component = ModelConverter.convertFromToscaElement(te);
676 components.add(component);
678 return Either.left(components);
681 public Either<List<String>, StorageOperationStatus> deleteMarkedElements(ComponentTypeEnum componentType) {
682 Either<List<GraphVertex>, StorageOperationStatus> allComponentsMarkedForDeletion;
683 List<String> deleted = new ArrayList<>();
684 switch (componentType) {
686 allComponentsMarkedForDeletion = nodeTypeOperation.getAllComponentsMarkedForDeletion(componentType);
690 allComponentsMarkedForDeletion = topologyTemplateOperation.getAllComponentsMarkedForDeletion(componentType);
693 log.debug("Not supported component type {}", componentType);
694 return Either.right(StorageOperationStatus.BAD_REQUEST);
696 if (allComponentsMarkedForDeletion.isRight()) {
697 return Either.right(allComponentsMarkedForDeletion.right().value());
699 List<GraphVertex> allMarked = allComponentsMarkedForDeletion.left().value();
701 Either<List<GraphVertex>, TitanOperationStatus> allNotDeletedElements = topologyTemplateOperation.getAllNotDeletedElements();
702 if (allNotDeletedElements.isRight()) {
703 return Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(allNotDeletedElements.right().value()));
705 List<GraphVertex> allNonMarked = allNotDeletedElements.left().value();
706 for (GraphVertex elementV : allMarked) {
707 if (topologyTemplateOperation.isInUse(elementV, allNonMarked) == false) {
708 Either<ToscaElement, StorageOperationStatus> deleteToscaElement = deleteToscaElement(elementV);
709 if (deleteToscaElement.isRight()) {
710 log.debug("Failed to delete marked element {} error {}", elementV.getUniqueId(), deleteToscaElement.right().value());
713 deleted.add(elementV.getUniqueId());
714 log.debug("Marked element {} in use. don't delete it", elementV.getUniqueId());
717 return Either.left(deleted);
720 public Either<List<String>, StorageOperationStatus> getAllComponentsMarkedForDeletion(ComponentTypeEnum componentType) {
721 Either<List<GraphVertex>, StorageOperationStatus> allComponentsMarkedForDeletion;
722 switch (componentType) {
724 allComponentsMarkedForDeletion = nodeTypeOperation.getAllComponentsMarkedForDeletion(componentType);
728 allComponentsMarkedForDeletion = topologyTemplateOperation.getAllComponentsMarkedForDeletion(componentType);
731 log.debug("Not supported component type {}", componentType);
732 return Either.right(StorageOperationStatus.BAD_REQUEST);
734 if (allComponentsMarkedForDeletion.isRight()) {
735 return Either.right(allComponentsMarkedForDeletion.right().value());
737 return Either.left(allComponentsMarkedForDeletion.left().value().stream().map(v -> v.getUniqueId()).collect(Collectors.toList()));
740 public Either<Boolean, StorageOperationStatus> isComponentInUse(String componentId) {
741 Either<Boolean, StorageOperationStatus> result;
742 Either<List<GraphVertex>, TitanOperationStatus> allNotDeletedElements = topologyTemplateOperation.getAllNotDeletedElements();
743 if (allNotDeletedElements.isRight()) {
744 result = Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(allNotDeletedElements.right().value()));
746 result = Either.left(topologyTemplateOperation.isInUse(componentId, allNotDeletedElements.left().value()));
751 public Either<ImmutablePair<Component, String>, StorageOperationStatus> addComponentInstanceToTopologyTemplate(Component containerComponent, Component origComponent, ComponentInstance componentInstance, boolean allowDeleted, User user) {
753 Either<ImmutablePair<Component, String>, StorageOperationStatus> result = null;
754 Either<ToscaElement, StorageOperationStatus> updateContainerComponentRes = null;
755 componentInstance.setIcon(origComponent.getIcon());
756 Either<ImmutablePair<TopologyTemplate, String>, StorageOperationStatus> addResult = nodeTemplateOperation.addComponentInstanceToTopologyTemplate(ModelConverter.convertToToscaElement(containerComponent),
757 ModelConverter.convertToToscaElement(origComponent), getNextComponentInstanceCounter(containerComponent, origComponent.getName()), componentInstance, allowDeleted, user);
759 if (addResult.isRight()) {
760 CommonUtility.addRecordToLog(log, LogLevelEnum.DEBUG, "Failed to add the component instance {} to container component {}. ", componentInstance.getName(), containerComponent.getName());
761 result = Either.right(addResult.right().value());
763 if (result == null) {
764 updateContainerComponentRes = topologyTemplateOperation.getToscaElement(containerComponent.getUniqueId());
765 if (updateContainerComponentRes.isRight()) {
766 CommonUtility.addRecordToLog(log, LogLevelEnum.DEBUG, "Failed to fetch updated topology template {} with updated component instance {}. ", containerComponent.getName(), componentInstance.getName());
767 result = Either.right(updateContainerComponentRes.right().value());
770 if (result == null) {
771 Component updatedComponent = ModelConverter.convertFromToscaElement(updateContainerComponentRes.left().value());
772 String createdInstanceId = addResult.left().value().getRight();
773 CommonUtility.addRecordToLog(log, LogLevelEnum.TRACE, "The component instance {} has been added to container component {}. ", createdInstanceId, updatedComponent.getName());
774 result = Either.left(new ImmutablePair<>(updatedComponent, createdInstanceId));
779 public StorageOperationStatus associateComponentInstancesToComponent(Component containerComponent, Map<ComponentInstance, Resource> resourcesInstancesMap, boolean allowDeleted) {
781 StorageOperationStatus result = null;
782 CommonUtility.addRecordToLog(log, LogLevelEnum.DEBUG, "Going to add component instances to component {}", containerComponent.getUniqueId());
784 Either<GraphVertex, TitanOperationStatus> metadataVertex = titanDao.getVertexById(containerComponent.getUniqueId(), JsonParseFlagEnum.ParseAll);
785 if (metadataVertex.isRight()) {
786 TitanOperationStatus status = metadataVertex.right().value();
787 if (status == TitanOperationStatus.NOT_FOUND) {
788 status = TitanOperationStatus.INVALID_ID;
790 result = DaoStatusConverter.convertTitanStatusToStorageStatus(status);
792 if (result == null) {
793 result = nodeTemplateOperation.associateComponentInstancesToComponent(containerComponent, resourcesInstancesMap, metadataVertex.left().value(), allowDeleted);
798 public Either<ImmutablePair<Component, String>, StorageOperationStatus> updateComponentInstanceMetadataOfTopologyTemplate(Component containerComponent, Component origComponent, ComponentInstance componentInstance) {
800 Either<ImmutablePair<Component, String>, StorageOperationStatus> result = null;
802 CommonUtility.addRecordToLog(log, LogLevelEnum.TRACE, "Going to update the metadata of the component instance {} belonging to container component {}. ", componentInstance.getName(), containerComponent.getName());
803 componentInstance.setIcon(origComponent.getIcon());
804 Either<ImmutablePair<TopologyTemplate, String>, StorageOperationStatus> updateResult = nodeTemplateOperation.updateComponentInstanceMetadataOfTopologyTemplate(ModelConverter.convertToToscaElement(containerComponent),
805 ModelConverter.convertToToscaElement(origComponent), componentInstance);
806 if (updateResult.isRight()) {
807 CommonUtility.addRecordToLog(log, LogLevelEnum.DEBUG, "Failed to update the metadata of the component instance {} belonging to container component {}. ", componentInstance.getName(), containerComponent.getName());
808 result = Either.right(updateResult.right().value());
810 if (result == null) {
811 Component updatedComponent = ModelConverter.convertFromToscaElement(updateResult.left().value().getLeft());
812 String createdInstanceId = updateResult.left().value().getRight();
813 CommonUtility.addRecordToLog(log, LogLevelEnum.TRACE, "The metadata of the component instance {} has been updated to container component {}. ", createdInstanceId, updatedComponent.getName());
814 result = Either.left(new ImmutablePair<>(updatedComponent, createdInstanceId));
819 public Either<Component, StorageOperationStatus> updateComponentInstanceMetadataOfTopologyTemplate(Component containerComponent) {
821 Either<Component, StorageOperationStatus> result = null;
823 CommonUtility.addRecordToLog(log, LogLevelEnum.TRACE, "Going to update the metadata belonging to container component {}. ", containerComponent.getName());
825 Either<TopologyTemplate, StorageOperationStatus> updateResult = nodeTemplateOperation.updateComponentInstanceMetadataOfTopologyTemplate(ModelConverter.convertToToscaElement(containerComponent));
826 if (updateResult.isRight()) {
827 CommonUtility.addRecordToLog(log, LogLevelEnum.DEBUG, "Failed to update the metadata belonging to container component {}. ", containerComponent.getName());
828 result = Either.right(updateResult.right().value());
830 if (result == null) {
831 Component updatedComponent = ModelConverter.convertFromToscaElement(updateResult.left().value());
832 CommonUtility.addRecordToLog(log, LogLevelEnum.TRACE, "The metadata has been updated to container component {}. ", updatedComponent.getName());
833 result = Either.left(updatedComponent);
838 public Either<ImmutablePair<Component, String>, StorageOperationStatus> deleteComponentInstanceFromTopologyTemplate(Component containerComponent, String resourceInstanceId) {
840 Either<ImmutablePair<Component, String>, StorageOperationStatus> result = null;
842 CommonUtility.addRecordToLog(log, LogLevelEnum.TRACE, "Going to delete the component instance {} belonging to container component {}. ", resourceInstanceId, containerComponent.getName());
844 Either<ImmutablePair<TopologyTemplate, String>, StorageOperationStatus> updateResult = nodeTemplateOperation.deleteComponentInstanceFromTopologyTemplate(ModelConverter.convertToToscaElement(containerComponent), resourceInstanceId);
845 if (updateResult.isRight()) {
846 CommonUtility.addRecordToLog(log, LogLevelEnum.DEBUG, "Failed to delete the component instance {} belonging to container component {}. ", resourceInstanceId, containerComponent.getName());
847 result = Either.right(updateResult.right().value());
849 if (result == null) {
850 Component updatedComponent = ModelConverter.convertFromToscaElement(updateResult.left().value().getLeft());
851 String deletedInstanceId = updateResult.left().value().getRight();
852 CommonUtility.addRecordToLog(log, LogLevelEnum.TRACE, "The component instance {} has been deleted from container component {}. ", deletedInstanceId, updatedComponent.getName());
853 result = Either.left(new ImmutablePair<>(updatedComponent, deletedInstanceId));
858 private String getNextComponentInstanceCounter(Component containerComponent, String originResourceName) {
860 Integer nextCounter = 0;
862 if (CollectionUtils.isNotEmpty(containerComponent.getComponentInstances())) {
864 String normalizedName = ValidationUtils.normalizeComponentInstanceName(originResourceName);
865 Integer maxCounterFromNames = getMaxCounterFromNames(containerComponent, normalizedName);
866 Integer maxCounterFromIds = getMaxCounterFromIds(containerComponent, normalizedName);
868 if (maxCounterFromNames == null && maxCounterFromIds != null) {
869 nextCounter = maxCounterFromIds + 1;
870 } else if (maxCounterFromIds == null && maxCounterFromNames != null) {
871 nextCounter = maxCounterFromNames + 1;
872 } else if (maxCounterFromIds != null && maxCounterFromNames != null) {
873 nextCounter = maxCounterFromNames > maxCounterFromIds ? maxCounterFromNames + 1 : maxCounterFromIds + 1;
876 return nextCounter.toString();
879 private Integer getMaxCounterFromNames(Component containerComponent, String normalizedName) {
881 Integer maxCounter = 0;
882 List<String> countersStr = containerComponent.getComponentInstances().stream().filter(ci -> ci.getNormalizedName() != null && ci.getNormalizedName().startsWith(normalizedName)).map(ci -> ci.getNormalizedName().split(normalizedName)[1])
883 .collect(Collectors.toList());
885 if (CollectionUtils.isEmpty(countersStr)) {
888 Integer currCounter = null;
889 for (String counter : countersStr) {
890 if (StringUtils.isEmpty(counter)) {
894 currCounter = Integer.parseInt(counter);
895 } catch (Exception e) {
898 maxCounter = maxCounter < currCounter ? currCounter : maxCounter;
900 if (currCounter == null) {
906 private Integer getMaxCounterFromIds(Component containerComponent, String normalizedName) {
908 Integer maxCounter = 0;
909 List<String> countersStr = containerComponent.getComponentInstances().stream().filter(ci -> ci.getUniqueId() != null && ci.getUniqueId().contains(normalizedName)).map(ci -> ci.getUniqueId().split(normalizedName)[1])
910 .collect(Collectors.toList());
912 if (CollectionUtils.isEmpty(countersStr)) {
915 Integer currCounter = null;
916 for (String counter : countersStr) {
917 if (StringUtils.isEmpty(counter)) {
921 currCounter = Integer.parseInt(counter);
922 } catch (Exception e) {
925 maxCounter = maxCounter < currCounter ? currCounter : maxCounter;
927 if (currCounter == null) {
933 public Either<RequirementCapabilityRelDef, StorageOperationStatus> associateResourceInstances(String componentId, RequirementCapabilityRelDef requirementDef) {
934 return nodeTemplateOperation.associateResourceInstances(componentId, requirementDef);
938 public Either<List<InputDefinition>, StorageOperationStatus> createAndAssociateInputs(Map<String, InputDefinition> inputs, String componentId) {
940 Either<GraphVertex, TitanOperationStatus> getVertexEither = titanDao.getVertexById(componentId, JsonParseFlagEnum.NoParse);
941 if (getVertexEither.isRight()) {
942 log.debug("Couldn't fetch component with and unique id {}, error: {}", componentId, getVertexEither.right().value());
943 return Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(getVertexEither.right().value()));
947 GraphVertex vertex = getVertexEither.left().value();
948 Map<String, PropertyDataDefinition> inputsMap = inputs.entrySet().stream().collect(Collectors.toMap(Map.Entry::getKey, e -> new PropertyDataDefinition(e.getValue())));
950 StorageOperationStatus status = topologyTemplateOperation.associateInputsToComponent(vertex, inputsMap, componentId);
952 if (StorageOperationStatus.OK == status) {
953 log.debug("Component created successfully!!!");
954 List<InputDefinition> inputsResList = null;
955 if (inputsMap != null && !inputsMap.isEmpty()) {
956 inputsResList = inputsMap.values().stream().map(i -> new InputDefinition(i)).collect(Collectors.toList());
958 return Either.left(inputsResList);
960 return Either.right(status);
964 public Either<List<InputDefinition>, StorageOperationStatus> addInputsToComponent(Map<String, InputDefinition> inputs, String componentId) {
966 Either<GraphVertex, TitanOperationStatus> getVertexEither = titanDao.getVertexById(componentId, JsonParseFlagEnum.NoParse);
967 if (getVertexEither.isRight()) {
968 log.debug("Couldn't fetch component with and unique id {}, error: {}", componentId, getVertexEither.right().value());
969 return Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(getVertexEither.right().value()));
973 GraphVertex vertex = getVertexEither.left().value();
974 Map<String, PropertyDataDefinition> inputsMap = inputs.entrySet().stream().collect(Collectors.toMap(Map.Entry::getKey, e -> new PropertyDataDefinition(e.getValue())));
976 StorageOperationStatus status = topologyTemplateOperation.addToscaDataToToscaElement(vertex, EdgeLabelEnum.INPUTS, VertexTypeEnum.INPUTS, inputsMap, JsonPresentationFields.NAME);
978 if (StorageOperationStatus.OK == status) {
979 log.debug("Component created successfully!!!");
980 List<InputDefinition> inputsResList = null;
981 if (inputsMap != null && !inputsMap.isEmpty()) {
982 inputsResList = inputsMap.values().stream().map(i -> new InputDefinition(i)).collect(Collectors.toList());
984 return Either.left(inputsResList);
986 return Either.right(status);
990 public Either<Map<String, List<ComponentInstanceProperty>>, StorageOperationStatus> associateComponentInstancePropertiesToComponent(Map<String, List<ComponentInstanceProperty>> instProperties, String componentId) {
992 Either<GraphVertex, TitanOperationStatus> getVertexEither = titanDao.getVertexById(componentId, JsonParseFlagEnum.NoParse);
993 if (getVertexEither.isRight()) {
994 log.debug("Couldn't fetch component with and unique id {}, error: {}", componentId, getVertexEither.right().value());
995 return Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(getVertexEither.right().value()));
999 GraphVertex vertex = getVertexEither.left().value();
1000 Map<String, MapPropertiesDataDefinition> instPropsMap = new HashMap<>();
1001 if (instProperties != null) {
1003 MapPropertiesDataDefinition propertiesMap;
1004 for (Entry<String, List<ComponentInstanceProperty>> entry : instProperties.entrySet()) {
1005 propertiesMap = new MapPropertiesDataDefinition();
1007 propertiesMap.setMapToscaDataDefinition(entry.getValue().stream().map(e -> new PropertyDataDefinition(e)).collect(Collectors.toMap(e -> e.getName(), e -> e)));
1009 instPropsMap.put(entry.getKey(), propertiesMap);
1013 StorageOperationStatus status = topologyTemplateOperation.associateInstPropertiesToComponent(vertex, instPropsMap);
1015 if (StorageOperationStatus.OK == status) {
1016 log.debug("Component created successfully!!!");
1017 return Either.left(instProperties);
1019 return Either.right(status);
1022 public Either<Map<String, List<ComponentInstanceInput>>, StorageOperationStatus> associateComponentInstanceInputsToComponent(Map<String, List<ComponentInstanceInput>> instInputs, String componentId) {
1024 Either<GraphVertex, TitanOperationStatus> getVertexEither = titanDao.getVertexById(componentId, JsonParseFlagEnum.NoParse);
1025 if (getVertexEither.isRight()) {
1026 log.debug("Couldn't fetch component with and unique id {}, error: {}", componentId, getVertexEither.right().value());
1027 return Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(getVertexEither.right().value()));
1030 GraphVertex vertex = getVertexEither.left().value();
1031 Map<String, MapPropertiesDataDefinition> instPropsMap = new HashMap<>();
1032 if (instInputs != null) {
1034 MapPropertiesDataDefinition propertiesMap;
1035 for (Entry<String, List<ComponentInstanceInput>> entry : instInputs.entrySet()) {
1036 propertiesMap = new MapPropertiesDataDefinition();
1038 propertiesMap.setMapToscaDataDefinition(entry.getValue().stream().map(e -> new PropertyDataDefinition(e)).collect(Collectors.toMap(e -> e.getName(), e -> e)));
1040 instPropsMap.put(entry.getKey(), propertiesMap);
1044 StorageOperationStatus status = topologyTemplateOperation.associateInstInputsToComponent(vertex, instPropsMap);
1046 if (StorageOperationStatus.OK == status) {
1047 log.debug("Component created successfully!!!");
1048 return Either.left(instInputs);
1050 return Either.right(status);
1053 public Either<Map<String, List<ComponentInstanceInput>>, StorageOperationStatus> addComponentInstanceInputsToComponent(Component containerComponent, Map<String, List<ComponentInstanceInput>> instProperties) {
1055 StorageOperationStatus status = StorageOperationStatus.OK;
1056 if (instProperties != null) {
1058 for (Entry<String, List<ComponentInstanceInput>> entry : instProperties.entrySet()) {
1059 List<ComponentInstanceInput> props = entry.getValue();
1060 String componentInstanseId = entry.getKey();
1061 if (props != null && !props.isEmpty()) {
1062 for (ComponentInstanceInput property : props) {
1063 List<ComponentInstanceInput> componentInstancesInputs = containerComponent.getComponentInstancesInputs().get(componentInstanseId);
1064 Optional<ComponentInstanceInput> instanceProperty = componentInstancesInputs.stream().filter(p -> p.getName().equals(property.getName())).findAny();
1065 if (instanceProperty.isPresent()) {
1066 status = updateComponentInstanceInput(containerComponent, componentInstanseId, property);
1068 status = addComponentInstanceInput(containerComponent, componentInstanseId, property);
1070 if (status != StorageOperationStatus.OK) {
1071 log.debug("Failed to update instance input {} for instance {} error {} ", property, componentInstanseId, status);
1072 return Either.right(status);
1074 log.trace("instance input {} for instance {} updated", property, componentInstanseId);
1080 return Either.left(instProperties);
1083 public StorageOperationStatus deleteComponentInstanceInputsToComponent(Map<String, List<ComponentInstanceInput>> instProperties, String componentId) {
1085 Either<GraphVertex, TitanOperationStatus> getVertexEither = titanDao.getVertexById(componentId, JsonParseFlagEnum.NoParse);
1086 if (getVertexEither.isRight()) {
1087 log.debug("Couldn't fetch component with and unique id {}, error: {}", componentId, getVertexEither.right().value());
1088 return DaoStatusConverter.convertTitanStatusToStorageStatus(getVertexEither.right().value());
1092 GraphVertex vertex = getVertexEither.left().value();
1093 Map<String, MapPropertiesDataDefinition> instPropsMap = new HashMap<>();
1094 if (instProperties != null) {
1096 MapPropertiesDataDefinition propertiesMap;
1097 for (Entry<String, List<ComponentInstanceInput>> entry : instProperties.entrySet()) {
1098 propertiesMap = new MapPropertiesDataDefinition();
1100 propertiesMap.setMapToscaDataDefinition(entry.getValue().stream().map(e -> new PropertyDataDefinition(e)).collect(Collectors.toMap(e -> e.getName(), e -> e)));
1102 instPropsMap.put(entry.getKey(), propertiesMap);
1106 return topologyTemplateOperation.deleteInstInputsToComponent(vertex, instPropsMap);
1110 public Either<Map<String, List<ComponentInstanceProperty>>, StorageOperationStatus> addComponentInstancePropertiesToComponent(Component containerComponent, Map<String, List<ComponentInstanceProperty>> instProperties, String componentId) {
1112 StorageOperationStatus status = StorageOperationStatus.OK;
1113 if (instProperties != null) {
1115 for (Entry<String, List<ComponentInstanceProperty>> entry : instProperties.entrySet()) {
1116 List<ComponentInstanceProperty> props = entry.getValue();
1117 String componentInstanseId = entry.getKey();
1118 List<ComponentInstanceProperty> instanceProperties = containerComponent.getComponentInstancesProperties().get(componentInstanseId);
1119 if (props != null && !props.isEmpty()) {
1120 for (ComponentInstanceProperty property : props) {
1121 Optional<ComponentInstanceProperty> instanceProperty = instanceProperties.stream().filter(p -> p.getUniqueId().equals(property.getUniqueId())).findAny();
1122 if (instanceProperty.isPresent()) {
1123 status = updateComponentInstanceProperty(containerComponent, componentInstanseId, property);
1125 status = addComponentInstanceProperty(containerComponent, componentInstanseId, property);
1133 return Either.left(instProperties);
1137 public StorageOperationStatus associateDeploymentArtifactsToInstances(Map<String, Map<String, ArtifactDefinition>> instDeploymentArtifacts, String componentId, User user) {
1139 Either<GraphVertex, TitanOperationStatus> getVertexEither = titanDao.getVertexById(componentId, JsonParseFlagEnum.NoParse);
1140 if (getVertexEither.isRight()) {
1141 log.debug("Couldn't fetch component with and unique id {}, error: {}", componentId, getVertexEither.right().value());
1142 return DaoStatusConverter.convertTitanStatusToStorageStatus(getVertexEither.right().value());
1146 GraphVertex vertex = getVertexEither.left().value();
1147 Map<String, MapArtifactDataDefinition> instArtMap = new HashMap<>();
1148 if (instDeploymentArtifacts != null) {
1150 MapArtifactDataDefinition artifactsMap;
1151 for (Entry<String, Map<String, ArtifactDefinition>> entry : instDeploymentArtifacts.entrySet()) {
1152 Map<String, ArtifactDefinition> artList = entry.getValue();
1153 Map<String, ArtifactDataDefinition> artifacts = artList.entrySet().stream().collect(Collectors.toMap(Map.Entry::getKey, e -> new ArtifactDataDefinition(e.getValue())));
1154 artifactsMap = nodeTemplateOperation.prepareInstDeploymentArtifactPerInstance(artifacts, entry.getKey(), user, NodeTemplateOperation.HEAT_VF_ENV_NAME);
1156 instArtMap.put(entry.getKey(), artifactsMap);
1160 return topologyTemplateOperation.associateInstDeploymentArtifactsToComponent(vertex, instArtMap);
1164 public StorageOperationStatus associateArtifactsToInstances(Map<String, Map<String, ArtifactDefinition>> instArtifacts, String componentId, User user) {
1166 Either<GraphVertex, TitanOperationStatus> getVertexEither = titanDao.getVertexById(componentId, JsonParseFlagEnum.NoParse);
1167 if (getVertexEither.isRight()) {
1168 log.debug("Couldn't fetch component with and unique id {}, error: {}", componentId, getVertexEither.right().value());
1169 return DaoStatusConverter.convertTitanStatusToStorageStatus(getVertexEither.right().value());
1173 GraphVertex vertex = getVertexEither.left().value();
1174 Map<String, MapArtifactDataDefinition> instArtMap = new HashMap<>();
1175 if (instArtifacts != null) {
1177 MapArtifactDataDefinition artifactsMap;
1178 for (Entry<String, Map<String, ArtifactDefinition>> entry : instArtifacts.entrySet()) {
1179 Map<String, ArtifactDefinition> artList = entry.getValue();
1180 Map<String, ArtifactDataDefinition> artifacts = artList.entrySet().stream().collect(Collectors.toMap(Map.Entry::getKey, e -> new ArtifactDataDefinition(e.getValue())));
1181 artifactsMap = new MapArtifactDataDefinition(artifacts);
1183 instArtMap.put(entry.getKey(), artifactsMap);
1187 return topologyTemplateOperation.associateInstArtifactsToComponent(vertex, instArtMap);
1191 public StorageOperationStatus associateInstAttributeToComponentToInstances(Map<String, List<PropertyDefinition>> instArttributes, String componentId) {
1193 Either<GraphVertex, TitanOperationStatus> getVertexEither = titanDao.getVertexById(componentId, JsonParseFlagEnum.NoParse);
1194 if (getVertexEither.isRight()) {
1195 log.debug("Couldn't fetch component with and unique id {}, error: {}", componentId, getVertexEither.right().value());
1196 return DaoStatusConverter.convertTitanStatusToStorageStatus(getVertexEither.right().value());
1200 GraphVertex vertex = getVertexEither.left().value();
1201 Map<String, MapPropertiesDataDefinition> instAttr = new HashMap<>();
1202 if (instArttributes != null) {
1204 MapPropertiesDataDefinition attributesMap;
1205 for (Entry<String, List<PropertyDefinition>> entry : instArttributes.entrySet()) {
1206 attributesMap = new MapPropertiesDataDefinition();
1207 attributesMap.setMapToscaDataDefinition(entry.getValue().stream().map(e -> new PropertyDataDefinition(e)).collect(Collectors.toMap(e -> e.getName(), e -> e)));
1208 instAttr.put(entry.getKey(), attributesMap);
1212 return topologyTemplateOperation.associateInstAttributeToComponent(vertex, instAttr);
1216 public StorageOperationStatus associateCalculatedCapReq(Map<ComponentInstance, Map<String, List<CapabilityDefinition>>> instCapabilties, Map<ComponentInstance, Map<String, List<RequirementDefinition>>> instReg, String componentId) {
1217 Either<GraphVertex, TitanOperationStatus> getVertexEither = titanDao.getVertexById(componentId, JsonParseFlagEnum.NoParse);
1218 if (getVertexEither.isRight()) {
1219 log.debug("Couldn't fetch component with and unique id {}, error: {}", componentId, getVertexEither.right().value());
1220 return DaoStatusConverter.convertTitanStatusToStorageStatus(getVertexEither.right().value());
1224 GraphVertex vertex = getVertexEither.left().value();
1226 Map<String, MapListRequirementDataDefinition> calcRequirements = new HashMap<>();
1228 Map<String, MapListCapabiltyDataDefinition> calcCapabilty = new HashMap<>();
1229 Map<String, MapCapabiltyProperty> calculatedCapabilitiesProperties = new HashMap<>();
1231 if (instCapabilties != null) {
1232 for (Entry<ComponentInstance, Map<String, List<CapabilityDefinition>>> entry : instCapabilties.entrySet()) {
1234 Map<String, List<CapabilityDefinition>> caps = entry.getValue();
1235 Map<String, ListCapabilityDataDefinition> mapToscaDataDefinition = new HashMap<>();
1236 for (Entry<String, List<CapabilityDefinition>> instCapability : caps.entrySet()) {
1237 mapToscaDataDefinition.put(instCapability.getKey(), new ListCapabilityDataDefinition(instCapability.getValue().stream().map(iCap -> new CapabilityDataDefinition(iCap)).collect(Collectors.toList())));
1240 ComponentInstanceDataDefinition componentInstance = new ComponentInstanceDataDefinition(entry.getKey());
1241 MapListCapabiltyDataDefinition capMap = nodeTemplateOperation.prepareCalculatedCapabiltyForNodeType(mapToscaDataDefinition, componentInstance);
1243 MapCapabiltyProperty mapCapabiltyProperty = ModelConverter.convertToMapOfMapCapabiltyProperties(caps, componentInstance.getUniqueId(), true);
1245 calcCapabilty.put(entry.getKey().getUniqueId(), capMap);
1246 calculatedCapabilitiesProperties.put(entry.getKey().getUniqueId(), mapCapabiltyProperty);
1250 if (instReg != null) {
1251 for (Entry<ComponentInstance, Map<String, List<RequirementDefinition>>> entry : instReg.entrySet()) {
1253 Map<String, List<RequirementDefinition>> req = entry.getValue();
1254 Map<String, ListRequirementDataDefinition> mapToscaDataDefinition = new HashMap<>();
1255 for (Entry<String, List<RequirementDefinition>> instReq : req.entrySet()) {
1256 mapToscaDataDefinition.put(instReq.getKey(), new ListRequirementDataDefinition(instReq.getValue().stream().map(iCap -> new RequirementDataDefinition(iCap)).collect(Collectors.toList())));
1259 MapListRequirementDataDefinition capMap = nodeTemplateOperation.prepareCalculatedRequirementForNodeType(mapToscaDataDefinition, new ComponentInstanceDataDefinition(entry.getKey()));
1261 calcRequirements.put(entry.getKey().getUniqueId(), capMap);
1265 StorageOperationStatus status = topologyTemplateOperation.associateCalcCapReqToComponent(vertex, calcRequirements, calcCapabilty, calculatedCapabilitiesProperties);
1270 private Either<List<Component>, StorageOperationStatus> getLatestVersionNotAbstractToscaElementsMetadataOnly(boolean isAbstract, Boolean isHighest, ComponentTypeEnum componentTypeEnum, String internalComponentType, VertexTypeEnum vertexType) {
1272 Map<GraphPropertyEnum, Object> hasProps = new EnumMap<>(GraphPropertyEnum.class);
1273 Map<GraphPropertyEnum, Object> hasNotProps = new EnumMap<>(GraphPropertyEnum.class);
1275 fillPropsMap(hasProps, hasNotProps, internalComponentType, componentTypeEnum, isAbstract, vertexType);
1277 Either<List<GraphVertex>, TitanOperationStatus> getRes = titanDao.getByCriteria(vertexType, hasProps, hasNotProps, JsonParseFlagEnum.ParseMetadata);
1278 if (getRes.isRight()) {
1279 if (getRes.right().value().equals(TitanOperationStatus.NOT_FOUND)) {
1280 return Either.left(new ArrayList<>());
1282 return Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(getRes.right().value()));
1285 List<Component> nonAbstractLatestComponents = new ArrayList<>();
1286 ComponentParametersView params = new ComponentParametersView(true);
1287 params.setIgnoreAllVersions(false);
1288 for (GraphVertex vertexComponent : getRes.left().value()) {
1289 Either<ToscaElement, StorageOperationStatus> componentRes = topologyTemplateOperation.getLightComponent(vertexComponent, componentTypeEnum, params);
1290 if (componentRes.isRight()) {
1291 log.debug("Failed to fetch ligth element for {} error {}", vertexComponent.getUniqueId(), componentRes.right().value());
1292 return Either.right(componentRes.right().value());
1294 Component component = ModelConverter.convertFromToscaElement(componentRes.left().value());
1296 nonAbstractLatestComponents.add(component);
1300 return Either.left(nonAbstractLatestComponents);
1304 public Either<ComponentMetadataData, StorageOperationStatus> getLatestComponentMetadataByUuid(String componentUuid, JsonParseFlagEnum parseFlag, Boolean isHighest) {
1306 Either<ComponentMetadataData, StorageOperationStatus> result;
1308 Map<GraphPropertyEnum, Object> hasProperties = new EnumMap<>(GraphPropertyEnum.class);
1310 hasProperties.put(GraphPropertyEnum.UUID, componentUuid);
1311 if (isHighest != null) {
1312 hasProperties.put(GraphPropertyEnum.IS_HIGHEST_VERSION, isHighest.booleanValue());
1315 Map<GraphPropertyEnum, Object> propertiesNotToMatch = new EnumMap<>(GraphPropertyEnum.class);
1316 propertiesNotToMatch.put(GraphPropertyEnum.IS_DELETED, true);
1318 Either<List<GraphVertex>, TitanOperationStatus> getRes = titanDao.getByCriteria(null, hasProperties, propertiesNotToMatch, parseFlag);
1319 if (getRes.isRight()) {
1320 result = Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(getRes.right().value()));
1322 List<ComponentMetadataData> latestVersionList = getRes.left().value().stream().map(ModelConverter::convertToComponentMetadata).collect(Collectors.toList());
1323 ComponentMetadataData latestVersion = latestVersionList.size() == 1 ? latestVersionList.get(0)
1324 : latestVersionList.stream().max((c1, c2) -> Double.compare(Double.parseDouble(c1.getMetadataDataDefinition().getVersion()), Double.parseDouble(c2.getMetadataDataDefinition().getVersion()))).get();
1325 result = Either.left(latestVersion);
1330 public Either<ComponentMetadataData, StorageOperationStatus> getComponentMetadata(String componentId) {
1332 Either<ComponentMetadataData, StorageOperationStatus> result;
1333 Either<GraphVertex, TitanOperationStatus> getRes = titanDao.getVertexById(componentId, JsonParseFlagEnum.ParseMetadata);
1334 if (getRes.isRight()) {
1335 result = Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(getRes.right().value()));
1337 ComponentMetadataData componentMetadata = ModelConverter.convertToComponentMetadata(getRes.left().value());
1338 result = Either.left(componentMetadata);
1343 private Map<String, ComponentMetadataData> findLatestVersion(List<ComponentMetadataData> resourceDataList) {
1344 Map<Pair<String, String>, ComponentMetadataData> latestVersionMap = new HashMap<Pair<String, String>, ComponentMetadataData>();
1345 for (ComponentMetadataData resourceData : resourceDataList) {
1346 ComponentMetadataData latestVersionData = resourceData;
1348 ComponentMetadataDataDefinition metadataDataDefinition = resourceData.getMetadataDataDefinition();
1349 Pair<String, String> pair = createKeyPair(latestVersionData);
1350 if (latestVersionMap.containsKey(pair)) {
1351 latestVersionData = latestVersionMap.get(pair);
1352 String currentVersion = latestVersionData.getMetadataDataDefinition().getVersion();
1353 String newVersion = metadataDataDefinition.getVersion();
1354 if (CommonBeUtils.compareAsdcComponentVersions(newVersion, currentVersion)) {
1355 latestVersionData = resourceData;
1358 if (log.isDebugEnabled())
1359 log.debug("last certified version of resource = {} version is {}", latestVersionData.getMetadataDataDefinition().getName(), latestVersionData.getMetadataDataDefinition().getVersion());
1361 latestVersionMap.put(pair, latestVersionData);
1364 Map<String, ComponentMetadataData> resVersionMap = new HashMap<String, ComponentMetadataData>();
1365 for (ComponentMetadataData resourceData : latestVersionMap.values()) {
1366 ComponentMetadataData latestVersionData = resourceData;
1367 ComponentMetadataDataDefinition metadataDataDefinition = resourceData.getMetadataDataDefinition();
1368 if (resVersionMap.containsKey(metadataDataDefinition.getUUID())) {
1369 latestVersionData = resVersionMap.get(metadataDataDefinition.getUUID());
1370 String currentVersion = latestVersionData.getMetadataDataDefinition().getVersion();
1371 String newVersion = metadataDataDefinition.getVersion();
1372 if (CommonBeUtils.compareAsdcComponentVersions(newVersion, currentVersion)) {
1373 latestVersionData = resourceData;
1376 if (log.isDebugEnabled())
1377 log.debug("last uuid version of resource = {} version is {}", latestVersionData.getMetadataDataDefinition().getName(), latestVersionData.getMetadataDataDefinition().getVersion());
1378 resVersionMap.put(latestVersionData.getMetadataDataDefinition().getUUID(), latestVersionData);
1381 return resVersionMap;
1384 private Pair<String, String> createKeyPair(ComponentMetadataData metadataData) {
1385 Pair<String, String> pair;
1386 NodeTypeEnum label = NodeTypeEnum.getByName(metadataData.getLabel());
1389 pair = new ImmutablePair<>(metadataData.getMetadataDataDefinition().getName(), ((ResourceMetadataDataDefinition) metadataData.getMetadataDataDefinition()).getResourceType().name());
1392 pair = new ImmutablePair<>(metadataData.getMetadataDataDefinition().getName(), metadataData.getLabel());
1399 public Either<List<Component>, StorageOperationStatus> getLatestVersionNotAbstractComponents(boolean isAbstract, Boolean isHighest, ComponentTypeEnum componentTypeEnum, String internalComponentType, List<String> componentUids) {
1401 Either<List<Component>, StorageOperationStatus> result = null;
1402 List<Component> components = new ArrayList<>();
1403 if (componentUids == null) {
1404 Either<List<String>, StorageOperationStatus> componentUidsRes = getComponentUids(isAbstract, isHighest, componentTypeEnum, internalComponentType, componentUids);
1405 if (componentUidsRes.isRight()) {
1406 result = Either.right(componentUidsRes.right().value());
1408 componentUids = componentUidsRes.left().value();
1411 if (!componentUids.isEmpty()) {
1412 for (String componentUid : componentUids) {
1413 ComponentParametersView componentParametersView = buildComponentViewForNotAbstract();
1414 if (internalComponentType != null && "vl".equalsIgnoreCase(internalComponentType)) {
1415 componentParametersView.setIgnoreCapabilities(false);
1416 componentParametersView.setIgnoreRequirements(false);
1418 Either<ToscaElement, StorageOperationStatus> getToscaElementRes = nodeTemplateOperation.getToscaElementOperation(componentTypeEnum).getLightComponent(componentUid, componentTypeEnum, componentParametersView);
1419 if (getToscaElementRes.isRight()) {
1420 if (log.isDebugEnabled())
1421 log.debug("Failed to fetch resource for error is {}", getToscaElementRes.right().value());
1422 result = Either.right(getToscaElementRes.right().value());
1425 Component component = ModelConverter.convertFromToscaElement(getToscaElementRes.left().value());
1426 component.setContactId(null);
1427 component.setCreationDate(null);
1428 component.setCreatorUserId(null);
1429 component.setCreatorFullName(null);
1430 component.setLastUpdateDate(null);
1431 component.setLastUpdaterUserId(null);
1432 component.setLastUpdaterFullName(null);
1433 component.setNormalizedName(null);
1434 components.add(component);
1437 if (result == null) {
1438 result = Either.left(components);
1443 private Either<List<String>, StorageOperationStatus> getComponentUids(boolean isAbstract, Boolean isHighest, ComponentTypeEnum componentTypeEnum, String internalComponentType, List<String> componentUids) {
1445 Either<List<String>, StorageOperationStatus> result = null;
1446 Either<List<Component>, StorageOperationStatus> getToscaElementsRes = getLatestVersionNotAbstractMetadataOnly(isAbstract, isHighest, componentTypeEnum, internalComponentType);
1447 if (getToscaElementsRes.isRight()) {
1448 result = Either.right(getToscaElementsRes.right().value());
1450 List<Component> collection = getToscaElementsRes.left().value();
1451 if (collection == null) {
1452 componentUids = new ArrayList<>();
1454 componentUids = collection.stream().map(p -> p.getUniqueId()).collect(Collectors.toList());
1457 if (result == null) {
1458 result = Either.left(componentUids);
1463 private ComponentParametersView buildComponentViewForNotAbstract() {
1464 ComponentParametersView componentParametersView = new ComponentParametersView();
1465 componentParametersView.disableAll();
1466 componentParametersView.setIgnoreCategories(false);
1467 componentParametersView.setIgnoreAllVersions(false);
1468 return componentParametersView;
1471 public Either<Boolean, StorageOperationStatus> validateComponentNameExists(String name, ResourceTypeEnum resourceType, ComponentTypeEnum componentType) {
1472 Either<Boolean, StorageOperationStatus> result = validateComponentNameUniqueness(name, resourceType, componentType);
1473 if (result.isLeft()) {
1474 result = Either.left(!result.left().value());
1479 public Either<Boolean, StorageOperationStatus> validateComponentNameUniqueness(String name, ResourceTypeEnum resourceType, ComponentTypeEnum componentType) {
1480 VertexTypeEnum vertexType = ModelConverter.isAtomicComponent(resourceType) ? VertexTypeEnum.NODE_TYPE : VertexTypeEnum.TOPOLOGY_TEMPLATE;
1481 String normalizedName = ValidationUtils.normaliseComponentName(name);
1482 Map<GraphPropertyEnum, Object> properties = new EnumMap<>(GraphPropertyEnum.class);
1483 properties.put(GraphPropertyEnum.NORMALIZED_NAME, normalizedName);
1484 properties.put(GraphPropertyEnum.COMPONENT_TYPE, componentType.name());
1486 Either<List<GraphVertex>, TitanOperationStatus> vertexEither = titanDao.getByCriteria(vertexType, properties, JsonParseFlagEnum.NoParse);
1487 if (vertexEither.isRight() && vertexEither.right().value() != TitanOperationStatus.NOT_FOUND) {
1488 log.debug("failed to get vertex from graph with property normalizedName: {}", normalizedName);
1489 return Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(vertexEither.right().value()));
1491 List<GraphVertex> vertexList = vertexEither.isLeft() ? vertexEither.left().value() : null;
1492 if (vertexList != null && !vertexList.isEmpty()) {
1493 return Either.left(false);
1495 return Either.left(true);
1500 private void fillNodeTypePropsMap(Map<GraphPropertyEnum, Object> hasProps, Map<GraphPropertyEnum, Object> hasNotProps, String internalComponentType) {
1501 switch (internalComponentType.toLowerCase()) {
1504 hasNotProps.put(GraphPropertyEnum.RESOURCE_TYPE, ResourceTypeEnum.VFCMT.name());
1508 hasNotProps.put(GraphPropertyEnum.RESOURCE_TYPE, Arrays.asList(ResourceTypeEnum.VFC.name(), ResourceTypeEnum.VFCMT.name()));
1511 hasProps.put(GraphPropertyEnum.RESOURCE_TYPE, ResourceTypeEnum.VL.name());
1519 private void fillTopologyTemplatePropsMap(Map<GraphPropertyEnum, Object> hasProps, Map<GraphPropertyEnum, Object> hasNotProps, ComponentTypeEnum componentTypeEnum, String internalComponentType) {
1520 switch (componentTypeEnum) {
1522 hasProps.put(GraphPropertyEnum.COMPONENT_TYPE, ComponentTypeEnum.RESOURCE.name());
1525 hasProps.put(GraphPropertyEnum.COMPONENT_TYPE, ComponentTypeEnum.SERVICE.name());
1530 switch (internalComponentType.toLowerCase()) {
1533 hasProps.put(GraphPropertyEnum.RESOURCE_TYPE, ResourceTypeEnum.CVFC.name());
1536 hasNotProps.put(GraphPropertyEnum.RESOURCE_TYPE, ResourceTypeEnum.CVFC.name());
1543 private void fillPropsMap(Map<GraphPropertyEnum, Object> hasProps, Map<GraphPropertyEnum, Object> hasNotProps, String internalComponentType, ComponentTypeEnum componentTypeEnum, boolean isAbstract, VertexTypeEnum internalVertexType) {
1544 hasNotProps.put(GraphPropertyEnum.STATE, LifecycleStateEnum.NOT_CERTIFIED_CHECKOUT.name());
1546 hasNotProps.put(GraphPropertyEnum.IS_DELETED, true);
1547 hasProps.put(GraphPropertyEnum.IS_HIGHEST_VERSION, true);
1548 if (VertexTypeEnum.NODE_TYPE == internalVertexType) {
1549 hasProps.put(GraphPropertyEnum.IS_ABSTRACT, isAbstract);
1550 if (internalComponentType != null) {
1551 fillNodeTypePropsMap(hasProps, hasNotProps, internalComponentType);
1554 fillTopologyTemplatePropsMap(hasProps, hasNotProps, componentTypeEnum, internalComponentType);
1558 private List<VertexTypeEnum> getInternalVertexTypes(ComponentTypeEnum componentTypeEnum, String internalComponentType) {
1559 List<VertexTypeEnum> internalVertexTypes = new ArrayList<>();
1560 if (ComponentTypeEnum.RESOURCE == componentTypeEnum) {
1561 internalVertexTypes.add(VertexTypeEnum.NODE_TYPE);
1563 if (ComponentTypeEnum.SERVICE == componentTypeEnum || "service".equalsIgnoreCase(internalComponentType) || "vf".equalsIgnoreCase(internalComponentType)) {
1564 internalVertexTypes.add(VertexTypeEnum.TOPOLOGY_TEMPLATE);
1566 return internalVertexTypes;
1569 public Either<List<Component>, StorageOperationStatus> getLatestVersionNotAbstractMetadataOnly(boolean isAbstract, Boolean isHighest, ComponentTypeEnum componentTypeEnum, String internalComponentType) {
1570 List<VertexTypeEnum> internalVertexTypes = getInternalVertexTypes(componentTypeEnum, internalComponentType);
1571 List<Component> result = new ArrayList<>();
1572 for (VertexTypeEnum vertexType : internalVertexTypes) {
1573 Either<List<Component>, StorageOperationStatus> listByVertexType = getLatestVersionNotAbstractToscaElementsMetadataOnly(isAbstract, isHighest, componentTypeEnum, internalComponentType, vertexType);
1574 if (listByVertexType.isRight()) {
1575 return listByVertexType;
1577 result.addAll(listByVertexType.left().value());
1579 return Either.left(result);
1583 public Either<List<Component>, StorageOperationStatus> getLatestComponentListByUuid(String componentUuid) {
1584 Map<GraphPropertyEnum, Object> propertiesToMatch = new EnumMap<>(GraphPropertyEnum.class);
1585 propertiesToMatch.put(GraphPropertyEnum.IS_HIGHEST_VERSION, true);
1586 Either<List<Component>, StorageOperationStatus> componentListByUuid = getComponentListByUuid(componentUuid, propertiesToMatch);
1587 return componentListByUuid;
1590 public Either<List<Component>, StorageOperationStatus> getComponentListByUuid(String componentUuid, Map<GraphPropertyEnum, Object> additionalPropertiesToMatch) {
1592 Map<GraphPropertyEnum, Object> propertiesToMatch = new EnumMap<>(GraphPropertyEnum.class);
1594 if (additionalPropertiesToMatch != null) {
1595 propertiesToMatch.putAll(additionalPropertiesToMatch);
1598 propertiesToMatch.put(GraphPropertyEnum.UUID, componentUuid);
1600 Map<GraphPropertyEnum, Object> propertiesNotToMatch = new EnumMap<>(GraphPropertyEnum.class);
1601 propertiesNotToMatch.put(GraphPropertyEnum.IS_DELETED, true);
1603 Either<List<GraphVertex>, TitanOperationStatus> vertexEither = titanDao.getByCriteria(null, propertiesToMatch, propertiesNotToMatch, JsonParseFlagEnum.ParseAll);
1605 if (vertexEither.isRight()) {
1606 log.debug("Couldn't fetch metadata for component with type {} and uuid {}, error: {}", componentUuid, vertexEither.right().value());
1607 return Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(vertexEither.right().value()));
1609 List<GraphVertex> vertexList = vertexEither.isLeft() ? vertexEither.left().value() : null;
1611 if (vertexList == null || vertexList.isEmpty()) {
1612 log.debug("Component with uuid {} was not found", componentUuid);
1613 return Either.right(StorageOperationStatus.NOT_FOUND);
1616 ArrayList<Component> latestComponents = new ArrayList<>();
1617 for (GraphVertex vertex : vertexList) {
1618 Either<Component, StorageOperationStatus> toscaElementByOperation = getToscaElementByOperation(vertex);
1620 if(toscaElementByOperation.isRight()){
1621 log.debug("Could not fetch the following Component by UUID {}", vertex.getUniqueId());
1622 return Either.right(toscaElementByOperation.right().value());
1625 latestComponents.add(toscaElementByOperation.left().value());
1628 if(latestComponents.size() > 1) {
1629 for (Component component : latestComponents) {
1630 if(component.isHighestVersion()){
1631 LinkedList<Component> highestComponent = new LinkedList<>();
1632 highestComponent.add(component);
1633 return Either.left(highestComponent);
1638 return Either.left(latestComponents);
1641 public Either<Component, StorageOperationStatus> getLatestComponentByUuid(String componentUuid) {
1643 Either<List<Component>, StorageOperationStatus> latestVersionListEither = getLatestComponentListByUuid(componentUuid);
1645 if (latestVersionListEither.isRight()) {
1646 return Either.right(latestVersionListEither.right().value());
1649 List<Component> latestVersionList = latestVersionListEither.left().value();
1651 if (latestVersionList.isEmpty()) {
1652 return Either.right(StorageOperationStatus.NOT_FOUND);
1654 Component component = latestVersionList.size() == 1 ? latestVersionList.get(0) : latestVersionList.stream().max((c1, c2) -> Double.compare(Double.parseDouble(c1.getVersion()), Double.parseDouble(c2.getVersion()))).get();
1656 return Either.left(component);
1659 public Either<List<Resource>, StorageOperationStatus> getAllCertifiedResources(boolean isAbstract, Boolean isHighest) {
1661 List<Resource> resources = new ArrayList<>();
1662 Map<GraphPropertyEnum, Object> propertiesToMatch = new EnumMap<>(GraphPropertyEnum.class);
1663 Map<GraphPropertyEnum, Object> propertiesNotToMatch = new EnumMap<>(GraphPropertyEnum.class);
1665 propertiesToMatch.put(GraphPropertyEnum.IS_ABSTRACT, isAbstract);
1666 if (isHighest != null) {
1667 propertiesToMatch.put(GraphPropertyEnum.IS_HIGHEST_VERSION, isHighest.booleanValue());
1669 propertiesToMatch.put(GraphPropertyEnum.STATE, LifecycleStateEnum.CERTIFIED.name());
1670 propertiesToMatch.put(GraphPropertyEnum.COMPONENT_TYPE, ComponentTypeEnum.RESOURCE.name());
1671 propertiesNotToMatch.put(GraphPropertyEnum.IS_DELETED, true);
1673 Either<List<GraphVertex>, TitanOperationStatus> getResourcesRes = titanDao.getByCriteria(null, propertiesToMatch, propertiesNotToMatch, JsonParseFlagEnum.ParseAll);
1675 if (getResourcesRes.isRight()) {
1676 log.debug("Failed to fetch all certified resources. Status is {}", getResourcesRes.right().value());
1677 return Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(getResourcesRes.right().value()));
1679 List<GraphVertex> resourceVerticies = getResourcesRes.left().value();
1680 for (GraphVertex resourceV : resourceVerticies) {
1681 Either<Resource, StorageOperationStatus> getResourceRes = getToscaElement(resourceV);
1682 if (getResourceRes.isRight()) {
1683 return Either.right(getResourceRes.right().value());
1685 resources.add(getResourceRes.left().value());
1687 return Either.left(resources);
1690 public <T extends Component> Either<T, StorageOperationStatus> getLatestByNameAndVersion(String name, String version, JsonParseFlagEnum parseFlag) {
1691 Either<T, StorageOperationStatus> result;
1693 Map<GraphPropertyEnum, Object> hasProperties = new EnumMap<>(GraphPropertyEnum.class);
1694 Map<GraphPropertyEnum, Object> hasNotProperties = new EnumMap<>(GraphPropertyEnum.class);
1696 hasProperties.put(GraphPropertyEnum.NAME, name);
1697 hasProperties.put(GraphPropertyEnum.VERSION, version);
1698 hasProperties.put(GraphPropertyEnum.IS_HIGHEST_VERSION, true);
1700 hasNotProperties.put(GraphPropertyEnum.IS_DELETED, true);
1702 Either<List<GraphVertex>, TitanOperationStatus> getResourceRes = titanDao.getByCriteria(null, hasProperties, hasNotProperties, parseFlag);
1703 if (getResourceRes.isRight()) {
1704 TitanOperationStatus status = getResourceRes.right().value();
1705 log.debug("failed to find resource with name {}, version {}. Status is {} ", name, version, status);
1706 result = Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(status));
1709 return getToscaElementByOperation(getResourceRes.left().value().get(0));
1712 public Either<Resource, StorageOperationStatus> getLatestComponentByCsarOrName(ComponentTypeEnum componentType, String csarUUID, String systemName) {
1713 return getLatestComponentByCsarOrName(componentType, csarUUID, systemName, false, JsonParseFlagEnum.ParseAll);
1716 public Either<Resource, StorageOperationStatus> getLatestComponentByCsarOrName(ComponentTypeEnum componentType, String csarUUID, String systemName, boolean allowDeleted, JsonParseFlagEnum parseFlag) {
1717 Map<GraphPropertyEnum, Object> props = new EnumMap<>(GraphPropertyEnum.class);
1718 props.put(GraphPropertyEnum.CSAR_UUID, csarUUID);
1719 props.put(GraphPropertyEnum.IS_HIGHEST_VERSION, true);
1720 if (componentType != null) {
1721 props.put(GraphPropertyEnum.COMPONENT_TYPE, componentType.name());
1723 Map<GraphPropertyEnum, Object> propsHasNot = new EnumMap<>(GraphPropertyEnum.class);
1724 propsHasNot.put(GraphPropertyEnum.IS_DELETED, true);
1726 GraphVertex resourceMetadataData = null;
1727 List<GraphVertex> resourceMetadataDataList = null;
1728 Either<List<GraphVertex>, TitanOperationStatus> byCsar = titanDao.getByCriteria(null, props, propsHasNot, JsonParseFlagEnum.ParseMetadata);
1729 if (byCsar.isRight()) {
1730 if (TitanOperationStatus.NOT_FOUND == byCsar.right().value()) {
1731 // Fix Defect DE256036
1732 if (StringUtils.isEmpty(systemName)) {
1733 return Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(TitanOperationStatus.NOT_FOUND));
1737 props.put(GraphPropertyEnum.IS_HIGHEST_VERSION, true);
1738 props.put(GraphPropertyEnum.SYSTEM_NAME, systemName);
1739 Either<List<GraphVertex>, TitanOperationStatus> bySystemname = titanDao.getByCriteria(null, props, JsonParseFlagEnum.ParseMetadata);
1740 if (bySystemname.isRight()) {
1741 log.debug("getLatestResourceByCsarOrName - Failed to find by system name {} error {} ", systemName, bySystemname.right().value());
1742 return Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(bySystemname.right().value()));
1744 if (bySystemname.left().value().size() > 2) {
1745 log.debug("getLatestResourceByCsarOrName - getByCriteria(by system name) must return only 2 latest version, but was returned - {}", bySystemname.left().value().size());
1746 return Either.right(StorageOperationStatus.GENERAL_ERROR);
1748 resourceMetadataDataList = bySystemname.left().value();
1749 if (resourceMetadataDataList.size() == 1) {
1750 resourceMetadataData = resourceMetadataDataList.get(0);
1752 for (GraphVertex curResource : resourceMetadataDataList) {
1753 if (!((String) curResource.getJsonMetadataField(JsonPresentationFields.LIFECYCLE_STATE)).equals("CERTIFIED")) {
1754 resourceMetadataData = curResource;
1759 if (resourceMetadataData == null) {
1760 log.debug("getLatestResourceByCsarOrName - getByCriteria(by system name) returned 2 latest CERTIFIED versions");
1761 return Either.right(StorageOperationStatus.GENERAL_ERROR);
1763 if (resourceMetadataData.getJsonMetadataField(JsonPresentationFields.CSAR_UUID) != null && !((String) resourceMetadataData.getJsonMetadataField(JsonPresentationFields.CSAR_UUID)).equals(csarUUID)) {
1764 log.debug("getLatestResourceByCsarOrName - same system name {} but different csarUUID. exist {} and new {} ", systemName, resourceMetadataData.getJsonMetadataField(JsonPresentationFields.CSAR_UUID), csarUUID);
1765 // correct error will be returned from create flow. with all
1766 // correct audit records!!!!!
1767 return Either.right(StorageOperationStatus.NOT_FOUND);
1769 Either<Resource, StorageOperationStatus> resource = getToscaElement((String) resourceMetadataData.getUniqueId());
1773 resourceMetadataDataList = byCsar.left().value();
1774 if (resourceMetadataDataList.size() > 2) {
1775 log.debug("getLatestResourceByCsarOrName - getByCriteria(by csar) must return only 2 latest version, but was returned - {}", byCsar.left().value().size());
1776 return Either.right(StorageOperationStatus.GENERAL_ERROR);
1778 if (resourceMetadataDataList.size() == 1) {
1779 resourceMetadataData = resourceMetadataDataList.get(0);
1781 for (GraphVertex curResource : resourceMetadataDataList) {
1782 if (!((String) curResource.getJsonMetadataField(JsonPresentationFields.LIFECYCLE_STATE)).equals("CERTIFIED")) {
1783 resourceMetadataData = curResource;
1788 if (resourceMetadataData == null) {
1789 log.debug("getLatestResourceByCsarOrName - getByCriteria(by csar) returned 2 latest CERTIFIED versions");
1790 return Either.right(StorageOperationStatus.GENERAL_ERROR);
1792 Either<Resource, StorageOperationStatus> resource = getToscaElement((String) resourceMetadataData.getJsonMetadataField(JsonPresentationFields.UNIQUE_ID), parseFlag);
1798 public Either<Boolean, StorageOperationStatus> validateToscaResourceNameExtends(String templateNameCurrent, String templateNameExtends) {
1800 String currentTemplateNameChecked = templateNameExtends;
1802 while (currentTemplateNameChecked != null && !currentTemplateNameChecked.equalsIgnoreCase(templateNameCurrent)) {
1803 Either<Resource, StorageOperationStatus> latestByToscaResourceName = getLatestByToscaResourceName(currentTemplateNameChecked);
1805 if (latestByToscaResourceName.isRight()) {
1806 return latestByToscaResourceName.right().value() == StorageOperationStatus.NOT_FOUND ? Either.left(false) : Either.right(latestByToscaResourceName.right().value());
1809 Resource value = latestByToscaResourceName.left().value();
1811 if (value.getDerivedFrom() != null) {
1812 currentTemplateNameChecked = value.getDerivedFrom().get(0);
1814 currentTemplateNameChecked = null;
1818 return (currentTemplateNameChecked != null && currentTemplateNameChecked.equalsIgnoreCase(templateNameCurrent)) ? Either.left(true) : Either.left(false);
1821 public Either<List<Component>, StorageOperationStatus> fetchMetaDataByResourceType(String resourceType, ComponentParametersView filterBy) {
1822 Map<GraphPropertyEnum, Object> props = new EnumMap<>(GraphPropertyEnum.class);
1823 props.put(GraphPropertyEnum.RESOURCE_TYPE, resourceType);
1824 props.put(GraphPropertyEnum.IS_HIGHEST_VERSION, true);
1825 Either<List<GraphVertex>, TitanOperationStatus> resourcesByTypeEither = titanDao.getByCriteria(null, props, JsonParseFlagEnum.ParseMetadata);
1827 if (resourcesByTypeEither.isRight()) {
1828 return Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(resourcesByTypeEither.right().value()));
1831 List<GraphVertex> vertexList = resourcesByTypeEither.left().value();
1832 List<Component> components = new ArrayList<>();
1834 for (GraphVertex vertex : vertexList) {
1835 components.add(getToscaElementByOperation(vertex, filterBy).left().value());
1838 return Either.left(components);
1841 public void commit() {
1845 public Either<Service, StorageOperationStatus> updateDistributionStatus(Service service, User user, DistributionStatusEnum distributionStatus) {
1846 Either<GraphVertex, StorageOperationStatus> updateDistributionStatus = topologyTemplateOperation.updateDistributionStatus(service.getUniqueId(), user, distributionStatus);
1847 if (updateDistributionStatus.isRight()) {
1848 return Either.right(updateDistributionStatus.right().value());
1850 GraphVertex serviceV = updateDistributionStatus.left().value();
1851 service.setDistributionStatus(distributionStatus);
1852 service.setLastUpdateDate((Long) serviceV.getJsonMetadataField(JsonPresentationFields.LAST_UPDATE_DATE));
1853 return Either.left(service);
1856 public Either<ComponentMetadataData, StorageOperationStatus> updateComponentLastUpdateDateOnGraph(Component component, Long modificationTime) {
1858 Either<ComponentMetadataData, StorageOperationStatus> result = null;
1859 GraphVertex serviceVertex;
1860 Either<GraphVertex, TitanOperationStatus> updateRes = null;
1861 Either<GraphVertex, TitanOperationStatus> getRes = titanDao.getVertexById(component.getUniqueId(), JsonParseFlagEnum.ParseMetadata);
1862 if (getRes.isRight()) {
1863 TitanOperationStatus status = getRes.right().value();
1864 log.error("Failed to fetch component {}. status is {}", component.getUniqueId(), status);
1865 result = Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(status));
1867 if (result == null) {
1868 serviceVertex = getRes.left().value();
1869 long lastUpdateDate = System.currentTimeMillis();
1870 serviceVertex.setJsonMetadataField(JsonPresentationFields.LAST_UPDATE_DATE, lastUpdateDate);
1871 component.setLastUpdateDate(lastUpdateDate);
1872 updateRes = titanDao.updateVertex(serviceVertex);
1873 if (updateRes.isRight()) {
1874 result = Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(updateRes.right().value()));
1877 if (result == null) {
1878 result = Either.left(ModelConverter.convertToComponentMetadata(updateRes.left().value()));
1883 public TitanDao getTitanDao() {
1887 public Either<List<Service>, StorageOperationStatus> getCertifiedServicesWithDistStatus(Set<DistributionStatusEnum> distStatus) {
1888 Map<GraphPropertyEnum, Object> propertiesToMatch = new EnumMap<>(GraphPropertyEnum.class);
1889 propertiesToMatch.put(GraphPropertyEnum.STATE, LifecycleStateEnum.CERTIFIED.name());
1891 return getServicesWithDistStatus(distStatus, propertiesToMatch);
1894 public Either<List<Service>, StorageOperationStatus> getServicesWithDistStatus(Set<DistributionStatusEnum> distStatus, Map<GraphPropertyEnum, Object> additionalPropertiesToMatch) {
1896 List<Service> servicesAll = new ArrayList<>();
1898 Map<GraphPropertyEnum, Object> propertiesToMatch = new EnumMap<>(GraphPropertyEnum.class);
1899 Map<GraphPropertyEnum, Object> propertiesNotToMatch = new EnumMap<>(GraphPropertyEnum.class);
1901 if (additionalPropertiesToMatch != null && !additionalPropertiesToMatch.isEmpty()) {
1902 propertiesToMatch.putAll(additionalPropertiesToMatch);
1905 propertiesToMatch.put(GraphPropertyEnum.COMPONENT_TYPE, ComponentTypeEnum.SERVICE.name());
1907 propertiesNotToMatch.put(GraphPropertyEnum.IS_DELETED, true);
1909 if (distStatus != null && !distStatus.isEmpty()) {
1910 for (DistributionStatusEnum state : distStatus) {
1911 propertiesToMatch.put(GraphPropertyEnum.DISTRIBUTION_STATUS, state.name());
1912 Either<List<Service>, StorageOperationStatus> fetchServicesByCriteria = fetchServicesByCriteria(servicesAll, propertiesToMatch, propertiesNotToMatch);
1913 if (fetchServicesByCriteria.isRight()) {
1914 return fetchServicesByCriteria;
1916 servicesAll = fetchServicesByCriteria.left().value();
1919 return Either.left(servicesAll);
1921 return fetchServicesByCriteria(servicesAll, propertiesToMatch, propertiesNotToMatch);
1925 // private Either<List<Service>, StorageOperationStatus> fetchServicesByCriteria(List<Service> servicesAll, Map<GraphPropertyEnum, Object> propertiesToMatch, Map<GraphPropertyEnum, Object> propertiesNotToMatch) {
1926 // Either<List<GraphVertex>, TitanOperationStatus> getRes = titanDao.getByCriteria(VertexTypeEnum.TOPOLOGY_TEMPLATE, propertiesToMatch, propertiesNotToMatch, JsonParseFlagEnum.ParseAll);
1927 // if (getRes.isRight()) {
1928 // if (getRes.right().value() != TitanOperationStatus.NOT_FOUND) {
1929 // CommonUtility.addRecordToLog(log, LogLevelEnum.DEBUG, "Failed to fetch certified services by match properties {} not match properties {} . Status is {}. ", propertiesToMatch, propertiesNotToMatch, getRes.right().value());
1930 // return Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(getRes.right().value()));
1933 // for (GraphVertex vertex : getRes.left().value()) {
1934 // Either<Component, StorageOperationStatus> getServiceRes = getToscaElementByOperation(vertex);
1935 // if (getServiceRes.isRight()) {
1936 // CommonUtility.addRecordToLog(log, LogLevelEnum.DEBUG, "Failed to fetch certified service {}. Status is {}. ", vertex.getJsonMetadataField(JsonPresentationFields.NAME), getServiceRes.right().value());
1937 // return Either.right(getServiceRes.right().value());
1939 // servicesAll.add((Service) getToscaElementByOperation(vertex).left().value());
1943 // return Either.left(servicesAll);
1946 private Either<List<Service>, StorageOperationStatus> fetchServicesByCriteria(List<Service> servicesAll, Map<GraphPropertyEnum, Object> propertiesToMatch, Map<GraphPropertyEnum, Object> propertiesNotToMatch) {
1947 Either<List<GraphVertex>, TitanOperationStatus> getRes = titanDao.getByCriteria(VertexTypeEnum.TOPOLOGY_TEMPLATE, propertiesToMatch, propertiesNotToMatch, JsonParseFlagEnum.ParseAll);
1948 if (getRes.isRight()) {
1949 if (getRes.right().value() != TitanOperationStatus.NOT_FOUND) {
1950 CommonUtility.addRecordToLog(log, LogLevelEnum.DEBUG, "Failed to fetch certified services by match properties {} not match properties {} . Status is {}. ", propertiesToMatch, propertiesNotToMatch, getRes.right().value());
1951 return Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(getRes.right().value()));
1954 for (GraphVertex vertex : getRes.left().value()) {
1955 // Either<Component, StorageOperationStatus> getServiceRes = getToscaElementByOperation(vertex);
1956 Either<ToscaElement, StorageOperationStatus> getServiceRes = topologyTemplateOperation.getLightComponent(vertex, ComponentTypeEnum.SERVICE, new ComponentParametersView(true));
1958 if (getServiceRes.isRight()) {
1959 CommonUtility.addRecordToLog(log, LogLevelEnum.DEBUG, "Failed to fetch certified service {}. Status is {}. ", vertex.getJsonMetadataField(JsonPresentationFields.NAME), getServiceRes.right().value());
1960 return Either.right(getServiceRes.right().value());
1962 servicesAll.add(ModelConverter.convertFromToscaElement(getServiceRes.left().value()));
1966 return Either.left(servicesAll);
1969 public void rollback() {
1970 titanDao.rollback();
1973 public StorageOperationStatus addDeploymentArtifactsToInstance(String componentId, ComponentInstance componentInstance, Map<String, ArtifactDefinition> finalDeploymentArtifacts) {
1974 Map<String, ArtifactDataDefinition> instDeplArtifacts = finalDeploymentArtifacts.entrySet().stream().collect(Collectors.toMap(Map.Entry::getKey, e -> new ArtifactDataDefinition(e.getValue())));
1976 return nodeTemplateOperation.addDeploymentArtifactsToInstance(componentId, componentInstance.getUniqueId(), instDeplArtifacts);
1979 public StorageOperationStatus addInformationalArtifactsToInstance(String componentId, ComponentInstance componentInstance, Map<String, ArtifactDefinition> artifacts) {
1980 StorageOperationStatus status = StorageOperationStatus.OK;
1981 if(MapUtils.isNotEmpty(artifacts)){
1982 Map<String, ArtifactDataDefinition> instDeplArtifacts = artifacts.entrySet().stream().collect(Collectors.toMap(Map.Entry::getKey, e -> new ArtifactDataDefinition(e.getValue())));
1983 status= nodeTemplateOperation.addInformationalArtifactsToInstance(componentId, componentInstance.getUniqueId(), instDeplArtifacts);
1988 public StorageOperationStatus generateCustomizationUUIDOnInstance(String componentId, String instanceId) {
1989 return nodeTemplateOperation.generateCustomizationUUIDOnInstance(componentId, instanceId);
1992 public StorageOperationStatus generateCustomizationUUIDOnInstanceGroup(String componentId, String instanceId, List<String> groupInstances) {
1993 return nodeTemplateOperation.generateCustomizationUUIDOnInstanceGroup(componentId, instanceId, groupInstances);
1996 public Either<PropertyDefinition, StorageOperationStatus> addPropertyToResource(String propertyName, PropertyDefinition newPropertyDefinition, Resource resource) {
1998 Either<PropertyDefinition, StorageOperationStatus> result = null;
1999 Either<Component, StorageOperationStatus> getUpdatedComponentRes = null;
2000 newPropertyDefinition.setName(propertyName);
2001 newPropertyDefinition.setParentUniqueId(resource.getUniqueId());
2002 StorageOperationStatus status = getToscaElementOperation(resource).addToscaDataToToscaElement(resource.getUniqueId(), EdgeLabelEnum.PROPERTIES, VertexTypeEnum.PROPERTIES, newPropertyDefinition, JsonPresentationFields.NAME);
2003 if (status != StorageOperationStatus.OK) {
2004 CommonUtility.addRecordToLog(log, LogLevelEnum.DEBUG, "Failed to add the property {} to the resource {}. Status is {}. ", propertyName, resource.getName(), status);
2005 result = Either.right(status);
2007 if (result == null) {
2008 ComponentParametersView filter = new ComponentParametersView(true);
2009 filter.setIgnoreProperties(false);
2010 getUpdatedComponentRes = getToscaElement(resource.getUniqueId(), filter);
2011 if (getUpdatedComponentRes.isRight()) {
2012 CommonUtility.addRecordToLog(log, LogLevelEnum.DEBUG, "Failed to get updated resource {}. Status is {}. ", resource.getUniqueId(), getUpdatedComponentRes.right().value());
2013 result = Either.right(status);
2016 if (result == null) {
2017 PropertyDefinition newProperty = null;
2018 List<PropertyDefinition> properties = ((Resource) getUpdatedComponentRes.left().value()).getProperties();
2019 if (CollectionUtils.isNotEmpty(properties)) {
2020 Optional<PropertyDefinition> newPropertyOptional = properties.stream().filter(p -> p.getName().equals(propertyName)).findAny();
2021 if (newPropertyOptional.isPresent()) {
2022 newProperty = newPropertyOptional.get();
2025 if (newProperty == null) {
2026 CommonUtility.addRecordToLog(log, LogLevelEnum.DEBUG, "Failed to find recently added property {} on the resource {}. Status is {}. ", propertyName, resource.getUniqueId(), StorageOperationStatus.NOT_FOUND);
2027 result = Either.right(StorageOperationStatus.NOT_FOUND);
2029 result = Either.left(newProperty);
2035 public StorageOperationStatus deletePropertyOfResource(Resource resource, String propertyName) {
2036 return getToscaElementOperation(resource).deleteToscaDataElement(resource.getUniqueId(), EdgeLabelEnum.PROPERTIES, VertexTypeEnum.PROPERTIES, propertyName, JsonPresentationFields.NAME);
2039 public StorageOperationStatus deleteAttributeOfResource(Component component, String attributeName) {
2040 return getToscaElementOperation(component).deleteToscaDataElement(component.getUniqueId(), EdgeLabelEnum.ATTRIBUTES, VertexTypeEnum.ATTRIBUTES, attributeName, JsonPresentationFields.NAME);
2043 public StorageOperationStatus deleteInputOfResource(Component resource, String inputName) {
2044 return getToscaElementOperation(resource).deleteToscaDataElement(resource.getUniqueId(), EdgeLabelEnum.INPUTS, VertexTypeEnum.INPUTS, inputName, JsonPresentationFields.NAME);
2047 public Either<PropertyDefinition, StorageOperationStatus> updatePropertyOfResource(Resource resource, PropertyDefinition newPropertyDefinition) {
2049 Either<Component, StorageOperationStatus> getUpdatedComponentRes = null;
2050 Either<PropertyDefinition, StorageOperationStatus> result = null;
2051 StorageOperationStatus status = getToscaElementOperation(resource).updateToscaDataOfToscaElement(resource.getUniqueId(), EdgeLabelEnum.PROPERTIES, VertexTypeEnum.PROPERTIES, newPropertyDefinition, JsonPresentationFields.NAME);
2052 if (status != StorageOperationStatus.OK) {
2053 CommonUtility.addRecordToLog(log, LogLevelEnum.DEBUG, "Failed to add the property {} to the resource {}. Status is {}. ", newPropertyDefinition.getName(), resource.getName(), status);
2054 result = Either.right(status);
2056 if (result == null) {
2057 ComponentParametersView filter = new ComponentParametersView(true);
2058 filter.setIgnoreProperties(false);
2059 getUpdatedComponentRes = getToscaElement(resource.getUniqueId(), filter);
2060 if (getUpdatedComponentRes.isRight()) {
2061 CommonUtility.addRecordToLog(log, LogLevelEnum.DEBUG, "Failed to get updated resource {}. Status is {}. ", resource.getUniqueId(), getUpdatedComponentRes.right().value());
2062 result = Either.right(status);
2065 if (result == null) {
2066 Optional<PropertyDefinition> newProperty = ((Resource) getUpdatedComponentRes.left().value()).getProperties().stream().filter(p -> p.getName().equals(newPropertyDefinition.getName())).findAny();
2067 if (newProperty.isPresent()) {
2068 result = Either.left(newProperty.get());
2070 CommonUtility.addRecordToLog(log, LogLevelEnum.DEBUG, "Failed to find recently added property {} on the resource {}. Status is {}. ", newPropertyDefinition.getName(), resource.getUniqueId(), StorageOperationStatus.NOT_FOUND);
2071 result = Either.right(StorageOperationStatus.NOT_FOUND);
2077 public Either<PropertyDefinition, StorageOperationStatus> addAttributeOfResource(Component component, PropertyDefinition newAttributeDef) {
2079 Either<Component, StorageOperationStatus> getUpdatedComponentRes = null;
2080 Either<PropertyDefinition, StorageOperationStatus> result = null;
2081 if (newAttributeDef.getUniqueId() == null || newAttributeDef.getUniqueId().isEmpty()) {
2082 String attUniqueId = UniqueIdBuilder.buildAttributeUid(component.getUniqueId(), newAttributeDef.getName());
2083 newAttributeDef.setUniqueId(attUniqueId);
2086 StorageOperationStatus status = getToscaElementOperation(component).addToscaDataToToscaElement(component.getUniqueId(), EdgeLabelEnum.ATTRIBUTES, VertexTypeEnum.ATTRIBUTES, newAttributeDef, JsonPresentationFields.NAME);
2087 if (status != StorageOperationStatus.OK) {
2088 CommonUtility.addRecordToLog(log, LogLevelEnum.DEBUG, "Failed to add the property {} to the resource {}. Status is {}. ", newAttributeDef.getName(), component.getName(), status);
2089 result = Either.right(status);
2091 if (result == null) {
2092 ComponentParametersView filter = new ComponentParametersView(true);
2093 filter.setIgnoreAttributesFrom(false);
2094 getUpdatedComponentRes = getToscaElement(component.getUniqueId(), filter);
2095 if (getUpdatedComponentRes.isRight()) {
2096 CommonUtility.addRecordToLog(log, LogLevelEnum.DEBUG, "Failed to get updated resource {}. Status is {}. ", component.getUniqueId(), getUpdatedComponentRes.right().value());
2097 result = Either.right(status);
2100 if (result == null) {
2101 Optional<PropertyDefinition> newAttribute = ((Resource) getUpdatedComponentRes.left().value()).getAttributes().stream().filter(p -> p.getName().equals(newAttributeDef.getName())).findAny();
2102 if (newAttribute.isPresent()) {
2103 result = Either.left(newAttribute.get());
2105 CommonUtility.addRecordToLog(log, LogLevelEnum.DEBUG, "Failed to find recently added property {} on the resource {}. Status is {}. ", newAttributeDef.getName(), component.getUniqueId(), StorageOperationStatus.NOT_FOUND);
2106 result = Either.right(StorageOperationStatus.NOT_FOUND);
2112 public Either<PropertyDefinition, StorageOperationStatus> updateAttributeOfResource(Component component, PropertyDefinition newAttributeDef) {
2114 Either<Component, StorageOperationStatus> getUpdatedComponentRes = null;
2115 Either<PropertyDefinition, StorageOperationStatus> result = null;
2116 StorageOperationStatus status = getToscaElementOperation(component).updateToscaDataOfToscaElement(component.getUniqueId(), EdgeLabelEnum.ATTRIBUTES, VertexTypeEnum.ATTRIBUTES, newAttributeDef, JsonPresentationFields.NAME);
2117 if (status != StorageOperationStatus.OK) {
2118 CommonUtility.addRecordToLog(log, LogLevelEnum.DEBUG, "Failed to add the property {} to the resource {}. Status is {}. ", newAttributeDef.getName(), component.getName(), status);
2119 result = Either.right(status);
2121 if (result == null) {
2122 ComponentParametersView filter = new ComponentParametersView(true);
2123 filter.setIgnoreAttributesFrom(false);
2124 getUpdatedComponentRes = getToscaElement(component.getUniqueId(), filter);
2125 if (getUpdatedComponentRes.isRight()) {
2126 CommonUtility.addRecordToLog(log, LogLevelEnum.DEBUG, "Failed to get updated resource {}. Status is {}. ", component.getUniqueId(), getUpdatedComponentRes.right().value());
2127 result = Either.right(status);
2130 if (result == null) {
2131 Optional<PropertyDefinition> newProperty = ((Resource) getUpdatedComponentRes.left().value()).getAttributes().stream().filter(p -> p.getName().equals(newAttributeDef.getName())).findAny();
2132 if (newProperty.isPresent()) {
2133 result = Either.left(newProperty.get());
2135 CommonUtility.addRecordToLog(log, LogLevelEnum.DEBUG, "Failed to find recently added property {} on the resource {}. Status is {}. ", newAttributeDef.getName(), component.getUniqueId(), StorageOperationStatus.NOT_FOUND);
2136 result = Either.right(StorageOperationStatus.NOT_FOUND);
2142 public Either<InputDefinition, StorageOperationStatus> updateInputOfComponent(Component component, InputDefinition newInputDefinition) {
2144 Either<Component, StorageOperationStatus> getUpdatedComponentRes = null;
2145 Either<InputDefinition, StorageOperationStatus> result = null;
2146 StorageOperationStatus status = getToscaElementOperation(component).updateToscaDataOfToscaElement(component.getUniqueId(), EdgeLabelEnum.INPUTS, VertexTypeEnum.INPUTS, newInputDefinition, JsonPresentationFields.NAME);
2147 if (status != StorageOperationStatus.OK) {
2148 CommonUtility.addRecordToLog(log, LogLevelEnum.DEBUG, "Failed to update the input {} to the component {}. Status is {}. ", newInputDefinition.getName(), component.getName(), status);
2149 result = Either.right(status);
2151 if (result == null) {
2152 ComponentParametersView filter = new ComponentParametersView(true);
2153 filter.setIgnoreInputs(false);
2154 getUpdatedComponentRes = getToscaElement(component.getUniqueId(), filter);
2155 if (getUpdatedComponentRes.isRight()) {
2156 CommonUtility.addRecordToLog(log, LogLevelEnum.DEBUG, "Failed to get updated resource {}. Status is {}. ", component.getUniqueId(), getUpdatedComponentRes.right().value());
2157 result = Either.right(status);
2160 if (result == null) {
2161 Optional<InputDefinition> updatedInput = getUpdatedComponentRes.left().value().getInputs().stream().filter(p -> p.getName().equals(newInputDefinition.getName())).findAny();
2162 if (updatedInput.isPresent()) {
2163 result = Either.left(updatedInput.get());
2165 CommonUtility.addRecordToLog(log, LogLevelEnum.DEBUG, "Failed to find recently updated inputs {} on the resource {}. Status is {}. ", newInputDefinition.getName(), component.getUniqueId(), StorageOperationStatus.NOT_FOUND);
2166 result = Either.right(StorageOperationStatus.NOT_FOUND);
2173 * method - ename the group instances after referenced container name renamed
2174 * flow - VF rename -(triggers)-> Group rename
2176 * @param containerComponent - container such as service
2177 * @param componentInstance - context component
2178 * @param componentInstanceId - id
2180 * @return - successfull/failed status
2182 public Either<StorageOperationStatus,StorageOperationStatus> cleanAndAddGroupInstancesToComponentInstance(Component containerComponent, ComponentInstance componentInstance, String componentInstanceId){
2183 String uniqueId = componentInstance.getUniqueId();
2184 StorageOperationStatus status = nodeTemplateOperation.deleteToscaDataDeepElementsBlockToToscaElement( containerComponent.getUniqueId(), EdgeLabelEnum.INST_GROUPS, VertexTypeEnum.INST_GROUPS, uniqueId );
2185 if (status != StorageOperationStatus.OK && status != StorageOperationStatus.NOT_FOUND) {
2186 CommonUtility.addRecordToLog(log, LogLevelEnum.DEBUG, "Failed to delete group instances for container {}. error {] ", componentInstanceId, status);
2187 return Either.right(status);
2189 if(componentInstance.getGroupInstances() != null){
2190 status = addGroupInstancesToComponentInstance( containerComponent , componentInstance, componentInstance.getGroupInstances() );
2191 if (status != StorageOperationStatus.OK && status != StorageOperationStatus.NOT_FOUND) {
2192 CommonUtility.addRecordToLog(log, LogLevelEnum.DEBUG, "Failed to add group instances for container {}. error {] ", componentInstanceId, status);
2193 return Either.right(status);
2196 return Either.left(status);
2199 public StorageOperationStatus addGroupInstancesToComponentInstance(Component containerComponent, ComponentInstance componentInstance, List<GroupDefinition> groups, Map<String, List<ArtifactDefinition>> groupInstancesArtifacts) {
2200 return nodeTemplateOperation.addGroupInstancesToComponentInstance(containerComponent, componentInstance, groups, groupInstancesArtifacts);
2203 public Either<List<GroupDefinition>, StorageOperationStatus> updateGroupsOnComponent(Component component, ComponentTypeEnum componentType, List<GroupDataDefinition> updatedGroups) {
2204 return groupsOperation.updateGroups(component, componentType, updatedGroups);
2207 public Either<List<GroupInstance>, StorageOperationStatus> updateGroupInstancesOnComponent(Component component, ComponentTypeEnum componentType, String instanceId, List<GroupInstance> updatedGroupInstances) {
2208 return groupsOperation.updateGroupInstances(component, componentType, instanceId, updatedGroupInstances);
2211 public StorageOperationStatus addGroupInstancesToComponentInstance(Component containerComponent, ComponentInstance componentInstance, List<GroupInstance> groupInstances) {
2212 return nodeTemplateOperation.addGroupInstancesToComponentInstance(containerComponent, componentInstance, groupInstances);
2215 public StorageOperationStatus addDeploymentArtifactsToComponentInstance(Component containerComponent, ComponentInstance componentInstance, Map<String, ArtifactDefinition> deploymentArtifacts) {
2216 return nodeTemplateOperation.addDeploymentArtifactsToComponentInstance(containerComponent, componentInstance, deploymentArtifacts);
2219 public StorageOperationStatus updateComponentInstanceProperty(Component containerComponent, String componentInstanceId, ComponentInstanceProperty property) {
2220 return nodeTemplateOperation.updateComponentInstanceProperty(containerComponent, componentInstanceId, property);
2223 public StorageOperationStatus addComponentInstanceProperty(Component containerComponent, String componentInstanceId, ComponentInstanceProperty property) {
2224 return nodeTemplateOperation.addComponentInstanceProperty(containerComponent, componentInstanceId, property);
2227 public StorageOperationStatus updateComponentInstanceInput(Component containerComponent, String componentInstanceId, ComponentInstanceInput property) {
2228 return nodeTemplateOperation.updateComponentInstanceInput(containerComponent, componentInstanceId, property);
2231 public StorageOperationStatus addComponentInstanceInput(Component containerComponent, String componentInstanceId, ComponentInstanceInput property) {
2232 return nodeTemplateOperation.addComponentInstanceInput(containerComponent, componentInstanceId, property);
2235 public void setNodeTypeOperation(NodeTypeOperation nodeTypeOperation) {
2236 this.nodeTypeOperation = nodeTypeOperation;
2239 public void setTopologyTemplateOperation(TopologyTemplateOperation topologyTemplateOperation) {
2240 this.topologyTemplateOperation = topologyTemplateOperation;
2243 public StorageOperationStatus deleteComponentInstanceInputsFromTopologyTemplate(Component containerComponent, ComponentTypeEnum componentType, List<InputDefinition> inputsToDelete) {
2244 return topologyTemplateOperation.deleteToscaDataElements(containerComponent.getUniqueId(), EdgeLabelEnum.INPUTS, inputsToDelete.stream().map(i -> i.getName()).collect(Collectors.toList()));
2247 public StorageOperationStatus deleteAllCalculatedCapabilitiesRequirements(String topologyTemplateId) {
2248 StorageOperationStatus status = topologyTemplateOperation.removeToscaData(topologyTemplateId, EdgeLabelEnum.CALCULATED_CAPABILITIES, VertexTypeEnum.CALCULATED_CAPABILITIES);
2249 if(status == StorageOperationStatus.OK){
2250 status = topologyTemplateOperation.removeToscaData(topologyTemplateId, EdgeLabelEnum.CALCULATED_REQUIREMENTS, VertexTypeEnum.CALCULATED_REQUIREMENTS);
2255 public Either<Component, StorageOperationStatus> shouldUpgradeToLatestDerived(Resource clonedResource) {
2256 String componentId = clonedResource.getUniqueId();
2257 Either<GraphVertex, TitanOperationStatus> getVertexEither = titanDao.getVertexById(componentId, JsonParseFlagEnum.NoParse);
2258 if (getVertexEither.isRight()) {
2259 log.debug("Couldn't fetch component with and unique id {}, error: {}", componentId, getVertexEither.right().value());
2260 return Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(getVertexEither.right().value()));
2263 GraphVertex nodeTypeV = getVertexEither.left().value();
2265 ToscaElement toscaElementToUpdate = ModelConverter.convertToToscaElement(clonedResource);
2267 Either<ToscaElement, StorageOperationStatus> shouldUpdateDerivedVersion = nodeTypeOperation.shouldUpdateDerivedVersion(toscaElementToUpdate, nodeTypeV);
2268 if ( shouldUpdateDerivedVersion.isRight() && StorageOperationStatus.OK != shouldUpdateDerivedVersion.right().value() ){
2269 log.debug("Failed to update derived version for node type {} derived {}, error: {}", componentId, clonedResource.getDerivedFrom().get(0), shouldUpdateDerivedVersion.right().value());
2270 return Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(getVertexEither.right().value()));
2272 if ( shouldUpdateDerivedVersion.isLeft() ){
2273 return Either.left(ModelConverter.convertFromToscaElement(shouldUpdateDerivedVersion.left().value()));
2275 return Either.left(clonedResource);