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.jsonjanusgraph.operations;
23 import fj.data.Either;
24 import org.apache.commons.collections.CollectionUtils;
25 import org.apache.commons.collections.MapUtils;
26 import org.apache.commons.lang3.StringUtils;
27 import org.apache.commons.lang3.tuple.ImmutablePair;
28 import org.apache.tinkerpop.gremlin.structure.Direction;
29 import org.apache.tinkerpop.gremlin.structure.Edge;
30 import org.openecomp.sdc.be.config.Configuration;
31 import org.openecomp.sdc.be.config.ConfigurationManager;
32 import org.openecomp.sdc.be.model.jsonjanusgraph.config.ContainerInstanceTypesData;
33 import org.openecomp.sdc.be.dao.janusgraph.JanusGraphOperationStatus;
34 import org.openecomp.sdc.be.dao.jsongraph.GraphVertex;
35 import org.openecomp.sdc.be.dao.jsongraph.HealingJanusGraphDao;
36 import org.openecomp.sdc.be.dao.jsongraph.types.EdgeLabelEnum;
37 import org.openecomp.sdc.be.dao.jsongraph.types.JsonParseFlagEnum;
38 import org.openecomp.sdc.be.dao.jsongraph.types.VertexTypeEnum;
39 import org.openecomp.sdc.be.datatypes.elements.*;
40 import org.openecomp.sdc.be.datatypes.elements.MapInterfaceDataDefinition;
41 import org.openecomp.sdc.be.datatypes.enums.*;
42 import org.openecomp.sdc.be.model.*;
43 import org.openecomp.sdc.be.datatypes.elements.MapCapabilityProperty;
44 import org.openecomp.sdc.be.datatypes.elements.MapListCapabilityDataDefinition;
45 import org.openecomp.sdc.be.model.CatalogUpdateTimestamp;
46 import org.openecomp.sdc.be.model.catalog.CatalogComponent;
47 import org.openecomp.sdc.be.model.jsonjanusgraph.datamodel.TopologyTemplate;
48 import org.openecomp.sdc.be.model.jsonjanusgraph.datamodel.ToscaElement;
49 import org.openecomp.sdc.be.model.jsonjanusgraph.utils.ModelConverter;
50 import org.openecomp.sdc.be.model.operations.StorageException;
51 import org.openecomp.sdc.be.model.operations.api.StorageOperationStatus;
52 import org.openecomp.sdc.be.model.operations.impl.DaoStatusConverter;
53 import org.openecomp.sdc.be.model.operations.impl.UniqueIdBuilder;
54 import org.openecomp.sdc.be.model.utils.GroupUtils;
55 import org.openecomp.sdc.be.resources.data.ComponentMetadataData;
56 import org.openecomp.sdc.common.jsongraph.util.CommonUtility;
57 import org.openecomp.sdc.common.jsongraph.util.CommonUtility.LogLevelEnum;
58 import org.openecomp.sdc.common.log.wrappers.Logger;
59 import org.openecomp.sdc.common.util.ValidationUtils;
60 import org.springframework.beans.factory.annotation.Autowired;
63 import java.util.Map.Entry;
64 import java.util.function.BiPredicate;
65 import java.util.stream.Collectors;
67 import static java.util.Objects.requireNonNull;
68 import static org.apache.commons.collections.CollectionUtils.isEmpty;
69 import static org.apache.commons.collections.CollectionUtils.isNotEmpty;
72 @org.springframework.stereotype.Component("tosca-operation-facade")
73 public class ToscaOperationFacade {
77 private static final String COULDNT_FETCH_A_COMPONENT_WITH_AND_UNIQUE_ID_ERROR = "Couldn't fetch a component with and UniqueId {}, error: {}";
78 private static final String FAILED_TO_FIND_RECENTLY_ADDED_PROPERTY_ON_THE_RESOURCE_STATUS_IS = "Failed to find recently added property {} on the resource {}. Status is {}. ";
79 private static final String FAILED_TO_GET_UPDATED_RESOURCE_STATUS_IS = "Failed to get updated resource {}. Status is {}. ";
80 private static final String FAILED_TO_ADD_THE_PROPERTY_TO_THE_RESOURCE_STATUS_IS = "Failed to add the property {} to the resource {}. Status is {}. ";
81 private static final String SERVICE = "service";
82 private static final String NOT_SUPPORTED_COMPONENT_TYPE = "Not supported component type {}";
83 private static final String COMPONENT_CREATED_SUCCESSFULLY = "Component created successfully!!!";
84 private static final String COULDNT_FETCH_COMPONENT_WITH_AND_UNIQUE_ID_ERROR = "Couldn't fetch component with and unique id {}, error: {}";
86 private NodeTypeOperation nodeTypeOperation;
88 private TopologyTemplateOperation topologyTemplateOperation;
90 private NodeTemplateOperation nodeTemplateOperation;
92 private GroupsOperation groupsOperation;
94 private HealingJanusGraphDao janusGraphDao;
96 private ContainerInstanceTypesData containerInstanceTypesData;
98 private static final Logger log = Logger.getLogger(ToscaOperationFacade.class.getName());
101 // region - ToscaElement - GetById
102 public static final String PROXY_SUFFIX = "_proxy";
104 public <T extends Component> Either<T, StorageOperationStatus> getToscaFullElement(String componentId) {
105 ComponentParametersView filters = new ComponentParametersView();
106 filters.setIgnoreCapabiltyProperties(false);
107 filters.setIgnoreForwardingPath(false);
108 return getToscaElement(componentId, filters);
111 public <T extends Component> Either<T, StorageOperationStatus> getToscaElement(String componentId) {
113 return getToscaElement(componentId, JsonParseFlagEnum.ParseAll);
117 public <T extends Component> Either<T, StorageOperationStatus> getToscaElement(String componentId, ComponentParametersView filters) {
119 Either<GraphVertex, JanusGraphOperationStatus> getVertexEither = janusGraphDao
120 .getVertexById(componentId, filters.detectParseFlag());
121 if (getVertexEither.isRight()) {
122 log.debug(COULDNT_FETCH_COMPONENT_WITH_AND_UNIQUE_ID_ERROR, componentId, getVertexEither.right().value());
123 return Either.right(DaoStatusConverter.convertJanusGraphStatusToStorageStatus(getVertexEither.right().value()));
126 return getToscaElementByOperation(getVertexEither.left().value(), filters);
129 public <T extends Component> Either<T, StorageOperationStatus> getToscaElement(String componentId, JsonParseFlagEnum parseFlag) {
131 Either<GraphVertex, JanusGraphOperationStatus> getVertexEither = janusGraphDao
132 .getVertexById(componentId, parseFlag);
133 if (getVertexEither.isRight()) {
134 log.debug(COULDNT_FETCH_COMPONENT_WITH_AND_UNIQUE_ID_ERROR, componentId, getVertexEither.right().value());
135 return Either.right(DaoStatusConverter.convertJanusGraphStatusToStorageStatus(getVertexEither.right().value()));
138 return getToscaElementByOperation(getVertexEither.left().value());
141 public <T extends Component> Either<T, StorageOperationStatus> getToscaElement(GraphVertex componentVertex) {
142 return getToscaElementByOperation(componentVertex);
145 public Either<Boolean, StorageOperationStatus> validateComponentExists(String componentId) {
147 Either<GraphVertex, JanusGraphOperationStatus> getVertexEither = janusGraphDao
148 .getVertexById(componentId, JsonParseFlagEnum.NoParse);
149 if (getVertexEither.isRight()) {
150 JanusGraphOperationStatus status = getVertexEither.right().value();
151 if (status == JanusGraphOperationStatus.NOT_FOUND) {
152 return Either.left(false);
154 log.debug(COULDNT_FETCH_COMPONENT_WITH_AND_UNIQUE_ID_ERROR, componentId, getVertexEither.right().value());
155 return Either.right(DaoStatusConverter.convertJanusGraphStatusToStorageStatus(getVertexEither.right().value()));
158 return Either.left(true);
161 public <T extends Component> Either<T, StorageOperationStatus> findLastCertifiedToscaElementByUUID(T component) {
162 Map<GraphPropertyEnum, Object> props = new EnumMap<>(GraphPropertyEnum.class);
163 props.put(GraphPropertyEnum.UUID, component.getUUID());
164 props.put(GraphPropertyEnum.STATE, LifecycleStateEnum.CERTIFIED.name());
165 props.put(GraphPropertyEnum.IS_HIGHEST_VERSION, true);
167 Either<List<GraphVertex>, JanusGraphOperationStatus> getVertexEither = janusGraphDao
168 .getByCriteria(ModelConverter.getVertexType(component), props);
169 if (getVertexEither.isRight()) {
170 log.debug(COULDNT_FETCH_COMPONENT_WITH_AND_UNIQUE_ID_ERROR, component.getUniqueId(), getVertexEither.right().value());
171 return Either.right(DaoStatusConverter.convertJanusGraphStatusToStorageStatus(getVertexEither.right().value()));
174 return getToscaElementByOperation(getVertexEither.left().value().get(0));
178 // region - ToscaElement - GetByOperation
179 private <T extends Component> Either<T, StorageOperationStatus> getToscaElementByOperation(GraphVertex componentV) {
180 return getToscaElementByOperation(componentV, new ComponentParametersView());
183 private <T extends Component> Either<T, StorageOperationStatus> getToscaElementByOperation(GraphVertex componentV,
184 ComponentParametersView filters) {
185 if (componentV == null) {
186 log.debug("Unexpected null value for `componentV`");
187 return Either.right(StorageOperationStatus.GENERAL_ERROR);
189 VertexTypeEnum label = componentV.getLabel();
191 ToscaElementOperation toscaOperation = getToscaElementOperation(componentV);
192 if (toscaOperation != null) {
193 log.debug("getToscaElementByOperation: toscaOperation={}", toscaOperation.getClass());
196 Either<ToscaElement, StorageOperationStatus> toscaElement;
197 String componentId = componentV.getUniqueId();
198 if (toscaOperation != null) {
199 log.debug("Need to fetch tosca element for id {}", componentId);
200 toscaElement = toscaOperation.getToscaElement(componentV, filters);
202 log.debug("not supported tosca type {} for id {}", label, componentId);
203 toscaElement = Either.right(StorageOperationStatus.BAD_REQUEST);
205 return toscaElement.left().map(ModelConverter::convertFromToscaElement);
210 private ToscaElementOperation getToscaElementOperation(GraphVertex componentV) {
211 VertexTypeEnum label = componentV.getLabel();
214 return nodeTypeOperation;
215 case TOPOLOGY_TEMPLATE:
216 return topologyTemplateOperation;
222 public <T extends Component> Either<T, StorageOperationStatus> createToscaComponent(T resource) {
223 ToscaElement toscaElement = ModelConverter.convertToToscaElement(resource);
225 ToscaElementOperation toscaElementOperation = getToscaElementOperation(resource);
226 Either<ToscaElement, StorageOperationStatus> createToscaElement = toscaElementOperation.createToscaElement(toscaElement);
227 if (createToscaElement.isLeft()) {
228 log.debug(COMPONENT_CREATED_SUCCESSFULLY);
229 T dataModel = ModelConverter.convertFromToscaElement(createToscaElement.left().value());
230 return Either.left(dataModel);
232 return Either.right(createToscaElement.right().value());
235 // region - ToscaElement Delete
236 public StorageOperationStatus markComponentToDelete(Component componentToDelete) {
238 if ((componentToDelete.getIsDeleted() != null) && componentToDelete.getIsDeleted() && !componentToDelete.isHighestVersion()) {
239 // component already marked for delete
240 return StorageOperationStatus.OK;
243 Either<GraphVertex, JanusGraphOperationStatus> getResponse = janusGraphDao
244 .getVertexById(componentToDelete.getUniqueId(), JsonParseFlagEnum.ParseAll);
245 if (getResponse.isRight()) {
246 log.debug(COULDNT_FETCH_COMPONENT_WITH_AND_UNIQUE_ID_ERROR, componentToDelete.getUniqueId(), getResponse.right().value());
247 return DaoStatusConverter.convertJanusGraphStatusToStorageStatus(getResponse.right().value());
250 GraphVertex componentV = getResponse.left().value();
252 // same operation for node type and topology template operations
253 Either<GraphVertex, StorageOperationStatus> result = nodeTypeOperation.markComponentToDelete(componentV);
254 if (result.isRight()) {
255 return result.right().value();
257 return StorageOperationStatus.OK;
261 public <T extends Component> Either<T, StorageOperationStatus> deleteToscaComponent(String componentId) {
263 Either<GraphVertex, JanusGraphOperationStatus> getVertexEither = janusGraphDao
264 .getVertexById(componentId, JsonParseFlagEnum.ParseAll);
265 if (getVertexEither.isRight()) {
266 log.debug("Couldn't fetch component vertex with and unique id {}, error: {}", componentId, getVertexEither.right().value());
267 return Either.right(DaoStatusConverter.convertJanusGraphStatusToStorageStatus(getVertexEither.right().value()));
270 Either<ToscaElement, StorageOperationStatus> deleteElement = deleteToscaElement(getVertexEither.left().value());
271 if (deleteElement.isRight()) {
272 log.debug("Failed to delete component with and unique id {}, error: {}", componentId, deleteElement.right().value());
273 return Either.right(deleteElement.right().value());
275 T dataModel = ModelConverter.convertFromToscaElement(deleteElement.left().value());
277 return Either.left(dataModel);
280 private Either<ToscaElement, StorageOperationStatus> deleteToscaElement(GraphVertex componentV) {
281 VertexTypeEnum label = componentV.getLabel();
282 Either<ToscaElement, StorageOperationStatus> toscaElement;
283 Object componentId = componentV.getUniqueId();
286 log.debug("Need to fetch node type for id {}", componentId);
287 toscaElement = nodeTypeOperation.deleteToscaElement(componentV);
289 case TOPOLOGY_TEMPLATE:
290 log.debug("Need to fetch topology template for id {}", componentId);
291 toscaElement = topologyTemplateOperation.deleteToscaElement(componentV);
294 log.debug("not supported tosca type {} for id {}", label, componentId);
295 toscaElement = Either.right(StorageOperationStatus.BAD_REQUEST);
302 private ToscaElementOperation getToscaElementOperation(Component component) {
303 return ModelConverter.isAtomicComponent(component) ? nodeTypeOperation : topologyTemplateOperation;
306 public <T extends Component> Either<T, StorageOperationStatus> getLatestByToscaResourceName(String toscaResourceName) {
307 return getLatestByName(GraphPropertyEnum.TOSCA_RESOURCE_NAME, toscaResourceName);
310 public <T extends Component> Either<T, StorageOperationStatus> getFullLatestComponentByToscaResourceName(String toscaResourceName) {
311 ComponentParametersView fetchAllFilter = new ComponentParametersView();
312 fetchAllFilter.setIgnoreForwardingPath(true);
313 fetchAllFilter.setIgnoreCapabiltyProperties(false);
314 return getLatestByName(GraphPropertyEnum.TOSCA_RESOURCE_NAME, toscaResourceName, JsonParseFlagEnum.ParseAll, fetchAllFilter);
317 public <T extends Component> Either<T, StorageOperationStatus> getLatestByName(String resourceName) {
318 return getLatestByName(GraphPropertyEnum.NAME, resourceName);
322 public StorageOperationStatus validateCsarUuidUniqueness(String csarUUID) {
324 Map<GraphPropertyEnum, Object> properties = new EnumMap<>(GraphPropertyEnum.class);
325 properties.put(GraphPropertyEnum.CSAR_UUID, csarUUID);
327 Either<List<GraphVertex>, JanusGraphOperationStatus> resources = janusGraphDao
328 .getByCriteria(null, properties, JsonParseFlagEnum.ParseMetadata);
330 if (resources.isRight()) {
331 if (resources.right().value() == JanusGraphOperationStatus.NOT_FOUND) {
332 return StorageOperationStatus.OK;
334 log.debug("failed to get resources from graph with property name: {}", csarUUID);
335 return DaoStatusConverter.convertJanusGraphStatusToStorageStatus(resources.right().value());
338 return StorageOperationStatus.ENTITY_ALREADY_EXISTS;
342 public <T extends Component> Either<Set<T>, StorageOperationStatus> getFollowed(String userId, Set<LifecycleStateEnum> lifecycleStates, Set<LifecycleStateEnum> lastStateStates, ComponentTypeEnum componentType) {
343 Either<List<ToscaElement>, StorageOperationStatus> followedResources;
344 if (componentType == ComponentTypeEnum.RESOURCE) {
345 followedResources = nodeTypeOperation.getFollowedComponent(userId, lifecycleStates, lastStateStates, componentType);
347 followedResources = topologyTemplateOperation.getFollowedComponent(userId, lifecycleStates, lastStateStates, componentType);
350 Set<T> components = new HashSet<>();
351 if (followedResources.isRight() && followedResources.right().value() != StorageOperationStatus.NOT_FOUND) {
352 return Either.right(followedResources.right().value());
354 if (followedResources.isLeft()) {
355 List<ToscaElement> toscaElements = followedResources.left().value();
356 toscaElements.forEach(te -> {
357 T component = ModelConverter.convertFromToscaElement(te);
358 components.add(component);
361 return Either.left(components);
364 public Either<Resource, StorageOperationStatus> getLatestCertifiedNodeTypeByToscaResourceName(String toscaResourceName) {
366 return getLatestCertifiedByToscaResourceName(toscaResourceName, VertexTypeEnum.NODE_TYPE, JsonParseFlagEnum.ParseMetadata);
369 public Either<Resource, StorageOperationStatus> getLatestCertifiedByToscaResourceName(String toscaResourceName,
370 VertexTypeEnum vertexType, JsonParseFlagEnum parseFlag) {
372 Map<GraphPropertyEnum, Object> props = new EnumMap<>(GraphPropertyEnum.class);
373 props.put(GraphPropertyEnum.TOSCA_RESOURCE_NAME, toscaResourceName);
374 props.put(GraphPropertyEnum.IS_HIGHEST_VERSION, true);
375 props.put(GraphPropertyEnum.STATE, LifecycleStateEnum.CERTIFIED.name());
376 Either<List<GraphVertex>, JanusGraphOperationStatus> getLatestRes = janusGraphDao
377 .getByCriteria(vertexType, props, parseFlag);
382 CommonUtility.addRecordToLog(log, LogLevelEnum.DEBUG, "Failed to fetch {} with name {}. status={} ",
383 vertexType, toscaResourceName, status);
384 return DaoStatusConverter.convertJanusGraphStatusToStorageStatus(status);
389 double version = 0.0;
390 GraphVertex highestResource = null;
391 for (GraphVertex resource : resources) {
392 double resourceVersion = Double
393 .parseDouble((String) resource.getJsonMetadataField(JsonPresentationFields.VERSION));
394 if (resourceVersion > version) {
395 version = resourceVersion;
396 highestResource = resource;
399 if (highestResource != null) {
400 return getToscaFullElement(highestResource.getUniqueId());
402 log.debug("The vertex with the highest version could not be found for {}", toscaResourceName);
403 return Either.right(StorageOperationStatus.GENERAL_ERROR);
409 public Either<Boolean, StorageOperationStatus> validateToscaResourceNameExists(String templateName) {
410 Either<Boolean, StorageOperationStatus> validateUniquenessRes = validateToscaResourceNameUniqueness(templateName);
411 if (validateUniquenessRes.isLeft()) {
412 return Either.left(!validateUniquenessRes.left().value());
414 return validateUniquenessRes;
417 public Either<RequirementCapabilityRelDef, StorageOperationStatus> dissociateResourceInstances(String componentId, RequirementCapabilityRelDef requirementDef) {
418 return nodeTemplateOperation.dissociateResourceInstances(componentId, requirementDef);
422 * Allows to get fulfilled requirement by relation and received predicate
424 public Either<RequirementDataDefinition, StorageOperationStatus> getFulfilledRequirementByRelation(String componentId, String instanceId, RequirementCapabilityRelDef relation, BiPredicate<RelationshipInfo, RequirementDataDefinition> predicate) {
425 return nodeTemplateOperation.getFulfilledRequirementByRelation(componentId, instanceId, relation, predicate);
429 * Allows to get fulfilled capability by relation and received predicate
431 public Either<CapabilityDataDefinition, StorageOperationStatus> getFulfilledCapabilityByRelation(String componentId, String instanceId, RequirementCapabilityRelDef relation, BiPredicate<RelationshipInfo, CapabilityDataDefinition> predicate) {
432 return nodeTemplateOperation.getFulfilledCapabilityByRelation(componentId, instanceId, relation, predicate);
435 public Either<List<RequirementCapabilityRelDef>, StorageOperationStatus> associateResourceInstances(Component component, String componentId, List<RequirementCapabilityRelDef> relations) {
436 Either<List<RequirementCapabilityRelDef>, StorageOperationStatus> reqAndCapListEither = nodeTemplateOperation.associateResourceInstances(component, componentId, relations);
437 if (component != null) {
438 updateInstancesCapAndReqOnComponentFromDB(component);
440 return reqAndCapListEither;
444 protected Either<Boolean, StorageOperationStatus> validateToscaResourceNameUniqueness(String name) {
446 Map<GraphPropertyEnum, Object> properties = new EnumMap<>(GraphPropertyEnum.class);
447 properties.put(GraphPropertyEnum.TOSCA_RESOURCE_NAME, name);
449 Either<List<GraphVertex>, JanusGraphOperationStatus> resources = janusGraphDao
450 .getByCriteria(null, properties, JsonParseFlagEnum.ParseMetadata);
452 if (resources.isRight() && resources.right().value() != JanusGraphOperationStatus.NOT_FOUND) {
453 log.debug("failed to get resources from graph with property name: {}", name);
454 return Either.right(DaoStatusConverter.convertJanusGraphStatusToStorageStatus(resources.right().value()));
456 List<GraphVertex> resourceList = (resources.isLeft() ? resources.left().value() : null);
457 if (isNotEmpty(resourceList)) {
458 if (log.isDebugEnabled()) {
459 StringBuilder builder = new StringBuilder();
460 for (GraphVertex resourceData : resourceList) {
461 builder.append(resourceData.getUniqueId() + "|");
463 log.debug("resources with property name:{} exists in graph. found {}", name, builder);
465 return Either.left(false);
467 log.debug("resources with property name:{} does not exists in graph", name);
468 return Either.left(true);
473 // region - Component Update
475 public Either<Resource, StorageOperationStatus> overrideComponent(Resource newComponent, Resource oldComponent) {
477 copyArtifactsToNewComponent(newComponent, oldComponent);
479 Either<GraphVertex, JanusGraphOperationStatus> componentVEither = janusGraphDao
480 .getVertexById(oldComponent.getUniqueId(), JsonParseFlagEnum.NoParse);
481 if (componentVEither.isRight()) {
482 log.debug("Failed to fetch component {} error {}", oldComponent.getUniqueId(), componentVEither.right().value());
483 return Either.right(DaoStatusConverter.convertJanusGraphStatusToStorageStatus(componentVEither.right().value()));
485 GraphVertex componentv = componentVEither.left().value();
486 Either<GraphVertex, JanusGraphOperationStatus> parentVertexEither = janusGraphDao.getParentVertex(componentv, EdgeLabelEnum.VERSION, JsonParseFlagEnum.NoParse);
487 if (parentVertexEither.isRight() && parentVertexEither.right().value() != JanusGraphOperationStatus.NOT_FOUND) {
488 log.debug("Failed to fetch parent version for component {} error {}", oldComponent.getUniqueId(), parentVertexEither.right().value());
489 return Either.right(DaoStatusConverter.convertJanusGraphStatusToStorageStatus(parentVertexEither.right().value()));
492 Either<ToscaElement, StorageOperationStatus> deleteToscaComponent = deleteToscaElement(componentv);
493 if (deleteToscaComponent.isRight()) {
494 log.debug("Failed to remove old component {} error {}", oldComponent.getUniqueId(), deleteToscaComponent.right().value());
495 return Either.right(deleteToscaComponent.right().value());
497 Either<Resource, StorageOperationStatus> createToscaComponent = createToscaComponent(newComponent);
498 if (createToscaComponent.isRight()) {
499 log.debug("Failed to create tosca element component {} error {}", newComponent.getUniqueId(), createToscaComponent.right().value());
500 return Either.right(createToscaComponent.right().value());
502 Resource newElement = createToscaComponent.left().value();
503 Either<GraphVertex, JanusGraphOperationStatus> newVersionEither = janusGraphDao
504 .getVertexById(newElement.getUniqueId(), JsonParseFlagEnum.NoParse);
505 if (newVersionEither.isRight()) {
506 log.debug("Failed to fetch new tosca element component {} error {}", newComponent.getUniqueId(), newVersionEither.right().value());
507 return Either.right(DaoStatusConverter.convertJanusGraphStatusToStorageStatus(newVersionEither.right().value()));
509 if (parentVertexEither.isLeft()) {
510 GraphVertex previousVersionV = parentVertexEither.left().value();
511 JanusGraphOperationStatus createEdge = janusGraphDao.createEdge(previousVersionV, newVersionEither.left().value(), EdgeLabelEnum.VERSION, null);
512 if (createEdge != JanusGraphOperationStatus.OK) {
513 log.debug("Failed to associate to previous version {} new version {} error {}", previousVersionV.getUniqueId(), newVersionEither.right().value(), createEdge);
514 return Either.right(DaoStatusConverter.convertJanusGraphStatusToStorageStatus(createEdge));
517 return Either.left(newElement);
520 void copyArtifactsToNewComponent(Resource newComponent, Resource oldComponent) {
521 // TODO - check if required
522 Map<String, ArtifactDefinition> toscaArtifacts = oldComponent.getToscaArtifacts();
523 if (toscaArtifacts != null && !toscaArtifacts.isEmpty()) {
524 toscaArtifacts.values().stream().forEach(a -> a.setDuplicated(Boolean.TRUE));
526 newComponent.setToscaArtifacts(toscaArtifacts);
528 Map<String, ArtifactDefinition> artifacts = oldComponent.getArtifacts();
529 if (artifacts != null && !artifacts.isEmpty()) {
530 artifacts.values().stream().forEach(a -> a.setDuplicated(Boolean.TRUE));
532 newComponent.setArtifacts(artifacts);
534 Map<String, ArtifactDefinition> depArtifacts = oldComponent.getDeploymentArtifacts();
535 if (depArtifacts != null && !depArtifacts.isEmpty()) {
536 depArtifacts.values().stream().forEach(a -> a.setDuplicated(Boolean.TRUE));
538 newComponent.setDeploymentArtifacts(depArtifacts);
541 newComponent.setLastUpdateDate(null);
542 newComponent.setHighestVersion(true);
545 public <T extends Component> Either<T, StorageOperationStatus> updateToscaElement(T componentToUpdate) {
546 return updateToscaElement(componentToUpdate, new ComponentParametersView());
549 public <T extends Component> Either<T, StorageOperationStatus> updateToscaElement(T componentToUpdate, ComponentParametersView filterResult) {
550 String componentId = componentToUpdate.getUniqueId();
551 Either<GraphVertex, JanusGraphOperationStatus> getVertexEither = janusGraphDao
552 .getVertexById(componentId, JsonParseFlagEnum.ParseAll);
553 if (getVertexEither.isRight()) {
554 log.debug(COULDNT_FETCH_COMPONENT_WITH_AND_UNIQUE_ID_ERROR, componentId, getVertexEither.right().value());
555 return Either.right(DaoStatusConverter.convertJanusGraphStatusToStorageStatus(getVertexEither.right().value()));
557 GraphVertex elementV = getVertexEither.left().value();
558 ToscaElementOperation toscaElementOperation = getToscaElementOperation(elementV);
560 ToscaElement toscaElementToUpdate = ModelConverter.convertToToscaElement(componentToUpdate);
561 Either<ToscaElement, StorageOperationStatus> updateToscaElement = null;
562 if (toscaElementOperation != null) {
563 updateToscaElement = toscaElementOperation.updateToscaElement(toscaElementToUpdate, elementV, filterResult);
565 log.debug("Null value returned by `getToscaElementOperation` with value {}", elementV);
566 updateToscaElement = Either.right(StorageOperationStatus.GENERAL_ERROR);
569 return updateToscaElement.bimap(
570 ModelConverter::convertFromToscaElement,
572 log.debug("Failed to update tosca element {} error {}", componentId, status);
577 private <T extends Component> Either<T, StorageOperationStatus> getLatestByName(GraphPropertyEnum property, String nodeName, JsonParseFlagEnum parseFlag) {
578 return getLatestByName(property, nodeName, parseFlag, new ComponentParametersView());
581 private <T extends Component> Either<T, StorageOperationStatus> getLatestByName(GraphPropertyEnum property, String nodeName, JsonParseFlagEnum parseFlag, ComponentParametersView filter) {
582 Either<T, StorageOperationStatus> result;
584 Map<GraphPropertyEnum, Object> propertiesToMatch = new EnumMap<>(GraphPropertyEnum.class);
585 Map<GraphPropertyEnum, Object> propertiesNotToMatch = new EnumMap<>(GraphPropertyEnum.class);
587 propertiesToMatch.put(property, nodeName);
588 propertiesToMatch.put(GraphPropertyEnum.IS_HIGHEST_VERSION, true);
590 propertiesNotToMatch.put(GraphPropertyEnum.IS_DELETED, true);
592 Either<List<GraphVertex>, JanusGraphOperationStatus> highestResources = janusGraphDao
593 .getByCriteria(null, propertiesToMatch, propertiesNotToMatch, parseFlag);
594 if (highestResources.isRight()) {
595 JanusGraphOperationStatus status = highestResources.right().value();
596 log.debug("failed to find resource with name {}. status={} ", nodeName, status);
597 result = Either.right(DaoStatusConverter.convertJanusGraphStatusToStorageStatus(status));
601 List<GraphVertex> resources = highestResources.left().value();
602 double version = 0.0;
603 GraphVertex highestResource = null;
604 for (GraphVertex vertex : resources) {
605 Object versionObj = vertex.getMetadataProperty(GraphPropertyEnum.VERSION);
606 double resourceVersion = Double.parseDouble((String) versionObj);
607 if (resourceVersion > version) {
608 version = resourceVersion;
609 highestResource = vertex;
612 return getToscaElementByOperation(highestResource, filter);
616 // region - Component Get By ..
617 private <T extends Component> Either<T, StorageOperationStatus> getLatestByName(GraphPropertyEnum property, String nodeName) {
618 return getLatestByName(property, nodeName, JsonParseFlagEnum.ParseMetadata);
621 public <T extends Component> Either<List<T>, StorageOperationStatus> getBySystemName(ComponentTypeEnum componentType, String systemName) {
623 Either<List<T>, StorageOperationStatus> result = null;
624 Either<T, StorageOperationStatus> getComponentRes;
625 List<T> components = new ArrayList<>();
626 List<GraphVertex> componentVertices;
627 Map<GraphPropertyEnum, Object> propertiesToMatch = new EnumMap<>(GraphPropertyEnum.class);
628 Map<GraphPropertyEnum, Object> propertiesNotToMatch = new EnumMap<>(GraphPropertyEnum.class);
630 propertiesToMatch.put(GraphPropertyEnum.SYSTEM_NAME, systemName);
631 if (componentType != null)
632 propertiesToMatch.put(GraphPropertyEnum.COMPONENT_TYPE, componentType.name());
634 propertiesNotToMatch.put(GraphPropertyEnum.IS_DELETED, true);
636 Either<List<GraphVertex>, JanusGraphOperationStatus> getComponentsRes = janusGraphDao
637 .getByCriteria(null, propertiesToMatch, propertiesNotToMatch, JsonParseFlagEnum.ParseAll);
638 if (getComponentsRes.isRight()) {
639 JanusGraphOperationStatus status = getComponentsRes.right().value();
640 log.debug("Failed to fetch the component with system name {}. Status is {} ", systemName, status);
641 result = Either.right(DaoStatusConverter.convertJanusGraphStatusToStorageStatus(status));
643 if (result == null) {
644 componentVertices = getComponentsRes.left().value();
645 for (GraphVertex componentVertex : componentVertices) {
646 getComponentRes = getToscaElementByOperation(componentVertex);
647 if (getComponentRes.isRight()) {
648 log.debug("Failed to get the component {}. Status is {} ", componentVertex.getJsonMetadataField(JsonPresentationFields.NAME), getComponentRes.right().value());
649 result = Either.right(getComponentRes.right().value());
652 T componentBySystemName = getComponentRes.left().value();
653 log.debug("Found component, id: {}", componentBySystemName.getUniqueId());
654 components.add(componentBySystemName);
657 if (result == null) {
658 result = Either.left(components);
663 public <T extends Component> Either<T, StorageOperationStatus> getComponentByNameAndVersion(ComponentTypeEnum componentType, String name, String version) {
664 return getComponentByNameAndVersion(componentType, name, version, JsonParseFlagEnum.ParseAll);
667 public <T extends Component> Either<T, StorageOperationStatus> getComponentByNameAndVersion(ComponentTypeEnum componentType, String name, String version, JsonParseFlagEnum parseFlag) {
668 Either<T, StorageOperationStatus> result;
670 Map<GraphPropertyEnum, Object> hasProperties = new EnumMap<>(GraphPropertyEnum.class);
671 Map<GraphPropertyEnum, Object> hasNotProperties = new EnumMap<>(GraphPropertyEnum.class);
673 hasProperties.put(GraphPropertyEnum.NAME, name);
674 hasProperties.put(GraphPropertyEnum.VERSION, version);
675 hasNotProperties.put(GraphPropertyEnum.IS_DELETED, true);
676 if (componentType != null) {
677 hasProperties.put(GraphPropertyEnum.COMPONENT_TYPE, componentType.name());
679 Either<List<GraphVertex>, JanusGraphOperationStatus> getResourceRes = janusGraphDao
680 .getByCriteria(null, hasProperties, hasNotProperties, parseFlag);
681 if (getResourceRes.isRight()) {
682 JanusGraphOperationStatus status = getResourceRes.right().value();
683 log.debug("failed to find resource with name {}, version {}. Status is {} ", name, version, status);
684 result = Either.right(DaoStatusConverter.convertJanusGraphStatusToStorageStatus(status));
687 return getToscaElementByOperation(getResourceRes.left().value().get(0));
690 public Either<List<CatalogComponent>, StorageOperationStatus> getCatalogOrArchiveComponents(boolean isCatalog, List<OriginTypeEnum> excludeTypes) {
691 List<ResourceTypeEnum> excludedResourceTypes = Optional.ofNullable(excludeTypes).orElse(Collections.emptyList()).stream().filter(type -> !type.equals(OriginTypeEnum.SERVICE)).map(type -> ResourceTypeEnum.getTypeByName(type.name()))
692 .collect(Collectors.toList());
693 return topologyTemplateOperation.getElementCatalogData(isCatalog, excludedResourceTypes);
697 public <T extends Component> Either<List<T>, StorageOperationStatus> getCatalogComponents(ComponentTypeEnum componentType, List<OriginTypeEnum> excludeTypes, boolean isHighestVersions) {
698 List<T> components = new ArrayList<>();
699 Either<List<ToscaElement>, StorageOperationStatus> catalogDataResult;
700 List<ToscaElement> toscaElements = new ArrayList<>();
701 List<ResourceTypeEnum> excludedResourceTypes = Optional.ofNullable(excludeTypes).orElse(Collections.emptyList()).stream().filter(type -> !type.equals(OriginTypeEnum.SERVICE)).map(type -> ResourceTypeEnum.getTypeByName(type.name()))
702 .collect(Collectors.toList());
704 switch (componentType) {
706 catalogDataResult = nodeTypeOperation.getElementCatalogData(ComponentTypeEnum.RESOURCE, excludedResourceTypes, isHighestVersions);
707 if (catalogDataResult.isRight()) {
708 return Either.right(catalogDataResult.right().value());
710 toscaElements = catalogDataResult.left().value();
713 if (excludeTypes != null && excludeTypes.contains(OriginTypeEnum.SERVICE)) {
716 catalogDataResult = topologyTemplateOperation.getElementCatalogData(ComponentTypeEnum.SERVICE, null, isHighestVersions);
717 if (catalogDataResult.isRight()) {
718 return Either.right(catalogDataResult.right().value());
720 toscaElements = catalogDataResult.left().value();
723 log.debug(NOT_SUPPORTED_COMPONENT_TYPE, componentType);
724 return Either.right(StorageOperationStatus.BAD_REQUEST);
726 toscaElements.forEach(te -> {
727 T component = ModelConverter.convertFromToscaElement(te);
728 components.add(component);
730 return Either.left(components);
733 public Either<List<String>, StorageOperationStatus> deleteMarkedElements(ComponentTypeEnum componentType) {
734 Either<List<GraphVertex>, StorageOperationStatus> allComponentsMarkedForDeletion;
735 switch (componentType) {
737 allComponentsMarkedForDeletion = nodeTypeOperation.getAllComponentsMarkedForDeletion(componentType);
741 allComponentsMarkedForDeletion = topologyTemplateOperation.getAllComponentsMarkedForDeletion(componentType);
744 log.debug(NOT_SUPPORTED_COMPONENT_TYPE, componentType);
745 return Either.right(StorageOperationStatus.BAD_REQUEST);
747 if (allComponentsMarkedForDeletion.isRight()) {
748 return Either.right(allComponentsMarkedForDeletion.right().value());
750 List<GraphVertex> allMarked = allComponentsMarkedForDeletion.left().value();
751 return Either.left(checkIfInUseAndDelete(allMarked));
754 private List<String> checkIfInUseAndDelete(List<GraphVertex> allMarked) {
755 final List<EdgeLabelEnum> forbiddenEdgeLabelEnums = Arrays.asList(EdgeLabelEnum.INSTANCE_OF, EdgeLabelEnum.PROXY_OF, EdgeLabelEnum.ALLOTTED_OF);
756 List<String> deleted = new ArrayList<>();
758 for (GraphVertex elementV : allMarked) {
759 boolean isAllowedToDelete = true;
761 for (EdgeLabelEnum edgeLabelEnum : forbiddenEdgeLabelEnums) {
762 Either<Edge, JanusGraphOperationStatus> belongingEdgeByCriteria = janusGraphDao
763 .getBelongingEdgeByCriteria(elementV, edgeLabelEnum, null);
764 if (belongingEdgeByCriteria.isLeft()) {
765 log.debug("Marked element {} in use. don't delete it", elementV.getUniqueId());
766 isAllowedToDelete = false;
771 if (isAllowedToDelete) {
772 Either<ToscaElement, StorageOperationStatus> deleteToscaElement = deleteToscaElement(elementV);
773 if (deleteToscaElement.isRight()) {
774 log.debug("Failed to delete marked element UniqueID {}, Name {}, error {}", elementV.getUniqueId(), elementV.getMetadataProperties().get(GraphPropertyEnum.NAME), deleteToscaElement.right().value());
777 deleted.add(elementV.getUniqueId());
783 public Either<List<String>, StorageOperationStatus> getAllComponentsMarkedForDeletion(ComponentTypeEnum componentType) {
784 Either<List<GraphVertex>, StorageOperationStatus> allComponentsMarkedForDeletion;
785 switch (componentType) {
787 allComponentsMarkedForDeletion = nodeTypeOperation.getAllComponentsMarkedForDeletion(componentType);
791 allComponentsMarkedForDeletion = topologyTemplateOperation.getAllComponentsMarkedForDeletion(componentType);
794 log.debug(NOT_SUPPORTED_COMPONENT_TYPE, componentType);
795 return Either.right(StorageOperationStatus.BAD_REQUEST);
797 if (allComponentsMarkedForDeletion.isRight()) {
798 return Either.right(allComponentsMarkedForDeletion.right().value());
800 return Either.left(allComponentsMarkedForDeletion.left().value().stream().map(GraphVertex::getUniqueId).collect(Collectors.toList()));
803 // region - Component Update
804 public Either<ImmutablePair<Component, String>, StorageOperationStatus> addComponentInstanceToTopologyTemplate(Component containerComponent, Component origComponent, ComponentInstance componentInstance, boolean allowDeleted, User user) {
806 Either<ImmutablePair<Component, String>, StorageOperationStatus> result = null;
807 Either<ToscaElement, StorageOperationStatus> updateContainerComponentRes = null;
808 if (StringUtils.isEmpty(componentInstance.getIcon())) {
809 componentInstance.setIcon(origComponent.getIcon());
811 String nameToFindForCounter = componentInstance.getOriginType() == OriginTypeEnum.ServiceProxy ? ValidationUtils.normaliseComponentName(componentInstance.getSourceModelName()) + PROXY_SUFFIX : origComponent.getName();
812 String nextComponentInstanceCounter = getNextComponentInstanceCounter(containerComponent, nameToFindForCounter);
813 Either<ImmutablePair<TopologyTemplate, String>, StorageOperationStatus> addResult = nodeTemplateOperation.addComponentInstanceToTopologyTemplate(ModelConverter.convertToToscaElement(containerComponent),
814 ModelConverter.convertToToscaElement(origComponent), nextComponentInstanceCounter, componentInstance, allowDeleted, user);
816 if (addResult.isRight()) {
817 CommonUtility.addRecordToLog(log, LogLevelEnum.DEBUG, "Failed to add the component instance {} to container component {}. ", componentInstance.getName(), containerComponent.getName());
818 result = Either.right(addResult.right().value());
820 if (result == null) {
821 updateContainerComponentRes = topologyTemplateOperation.getToscaElement(containerComponent.getUniqueId());
822 if (updateContainerComponentRes.isRight()) {
823 CommonUtility.addRecordToLog(log, LogLevelEnum.DEBUG, "Failed to fetch updated topology template {} with updated component instance {}. ", containerComponent.getName(), componentInstance.getName());
824 result = Either.right(updateContainerComponentRes.right().value());
827 if (result == null) {
828 Component updatedComponent = ModelConverter.convertFromToscaElement(updateContainerComponentRes.left().value());
829 String createdInstanceId = addResult.left().value().getRight();
830 CommonUtility.addRecordToLog(log, LogLevelEnum.TRACE, "The component instance {} has been added to container component {}. ", createdInstanceId, updatedComponent.getName());
831 result = Either.left(new ImmutablePair<>(updatedComponent, createdInstanceId));
836 public void associateComponentInstancesToComponent(Component containerComponent, Map<ComponentInstance, Resource> resourcesInstancesMap, boolean allowDeleted, boolean isUpdateCsar) {
837 CommonUtility.addRecordToLog(log, LogLevelEnum.DEBUG, "Going to add component instances to component {}", containerComponent.getUniqueId());
839 Either<GraphVertex, JanusGraphOperationStatus> metadataVertex = janusGraphDao
840 .getVertexById(containerComponent.getUniqueId(), JsonParseFlagEnum.ParseAll);
841 if (metadataVertex.isRight()) {
842 JanusGraphOperationStatus status = metadataVertex.right().value();
843 if (status == JanusGraphOperationStatus.NOT_FOUND) {
844 status = JanusGraphOperationStatus.INVALID_ID;
846 throw new StorageException(DaoStatusConverter.convertJanusGraphStatusToStorageStatus(status));
849 Map<String, ComponentInstanceDataDefinition> compnentInstancesMap = nodeTemplateOperation.associateComponentInstancesToComponent(containerComponent, resourcesInstancesMap, metadataVertex.left().value(), allowDeleted, isUpdateCsar);
851 containerComponent.setComponentInstances(ModelConverter.getComponentInstancesFromMapObject(compnentInstancesMap, containerComponent));
855 public Either<ImmutablePair<Component, String>, StorageOperationStatus> updateComponentInstanceMetadataOfTopologyTemplate(Component containerComponent, Component origComponent, ComponentInstance componentInstance) {
857 Either<ImmutablePair<Component, String>, StorageOperationStatus> result = null;
859 CommonUtility.addRecordToLog(log, LogLevelEnum.TRACE, "Going to update the metadata of the component instance {} belonging to container component {}. ", componentInstance.getName(), containerComponent.getName());
860 componentInstance.setIcon(origComponent.getIcon());
861 Either<ImmutablePair<TopologyTemplate, String>, StorageOperationStatus> updateResult = nodeTemplateOperation.updateComponentInstanceMetadataOfTopologyTemplate(ModelConverter.convertToToscaElement(containerComponent),
862 ModelConverter.convertToToscaElement(origComponent), componentInstance);
863 if (updateResult.isRight()) {
864 CommonUtility.addRecordToLog(log, LogLevelEnum.DEBUG, "Failed to update the metadata of the component instance {} belonging to container component {}. ", componentInstance.getName(), containerComponent.getName());
865 result = Either.right(updateResult.right().value());
867 if (result == null) {
868 Component updatedComponent = ModelConverter.convertFromToscaElement(updateResult.left().value().getLeft());
869 String createdInstanceId = updateResult.left().value().getRight();
870 CommonUtility.addRecordToLog(log, LogLevelEnum.TRACE, "The metadata of the component instance {} has been updated to container component {}. ", createdInstanceId, updatedComponent.getName());
871 result = Either.left(new ImmutablePair<>(updatedComponent, createdInstanceId));
876 public Either<Component, StorageOperationStatus> updateComponentInstanceMetadataOfTopologyTemplate(Component containerComponent) {
877 return updateComponentInstanceMetadataOfTopologyTemplate(containerComponent, new ComponentParametersView());
880 public Either<Component, StorageOperationStatus> updateComponentInstanceMetadataOfTopologyTemplate(Component containerComponent, ComponentParametersView filter) {
882 Either<Component, StorageOperationStatus> result = null;
884 CommonUtility.addRecordToLog(log, LogLevelEnum.TRACE, "Going to update the metadata belonging to container component {}. ", containerComponent.getName());
886 Either<TopologyTemplate, StorageOperationStatus> updateResult = nodeTemplateOperation.updateComponentInstanceMetadataOfTopologyTemplate(ModelConverter.convertToToscaElement(containerComponent), filter);
887 if (updateResult.isRight()) {
888 CommonUtility.addRecordToLog(log, LogLevelEnum.DEBUG, "Failed to update the metadata belonging to container component {}. ", containerComponent.getName());
889 result = Either.right(updateResult.right().value());
891 if (result == null) {
892 Component updatedComponent = ModelConverter.convertFromToscaElement(updateResult.left().value());
893 CommonUtility.addRecordToLog(log, LogLevelEnum.TRACE, "The metadata has been updated to container component {}. ", updatedComponent.getName());
894 result = Either.left(updatedComponent);
900 public Either<ImmutablePair<Component, String>, StorageOperationStatus> deleteComponentInstanceFromTopologyTemplate(Component containerComponent, String resourceInstanceId) {
902 Either<ImmutablePair<Component, String>, StorageOperationStatus> result = null;
904 CommonUtility.addRecordToLog(log, LogLevelEnum.TRACE, "Going to delete the component instance {} belonging to container component {}. ", resourceInstanceId, containerComponent.getName());
906 Either<ImmutablePair<TopologyTemplate, String>, StorageOperationStatus> updateResult = nodeTemplateOperation.deleteComponentInstanceFromTopologyTemplate(ModelConverter.convertToToscaElement(containerComponent), resourceInstanceId);
907 if (updateResult.isRight()) {
908 CommonUtility.addRecordToLog(log, LogLevelEnum.DEBUG, "Failed to delete the component instance {} belonging to container component {}. ", resourceInstanceId, containerComponent.getName());
909 result = Either.right(updateResult.right().value());
911 if (result == null) {
912 Component updatedComponent = ModelConverter.convertFromToscaElement(updateResult.left().value().getLeft());
913 String deletedInstanceId = updateResult.left().value().getRight();
914 CommonUtility.addRecordToLog(log, LogLevelEnum.TRACE, "The component instance {} has been deleted from container component {}. ", deletedInstanceId, updatedComponent.getName());
915 result = Either.left(new ImmutablePair<>(updatedComponent, deletedInstanceId));
920 private String getNextComponentInstanceCounter(Component containerComponent, String originResourceName) {
921 Integer nextCounter = 0;
922 if (CollectionUtils.isNotEmpty(containerComponent.getComponentInstances())) {
923 String normalizedName = ValidationUtils.normalizeComponentInstanceName(originResourceName);
924 Integer maxCounter = getMaxCounterFromNamesAndIds(containerComponent, normalizedName);
925 if (maxCounter != null) {
926 nextCounter = maxCounter + 1;
929 return nextCounter.toString();
933 * @return max counter of component instance Id's, null if not found
935 private Integer getMaxCounterFromNamesAndIds(Component containerComponent, String normalizedName) {
936 List<String> countersInNames = containerComponent.getComponentInstances().stream()
937 .filter(ci -> ci.getNormalizedName() != null && ci.getNormalizedName().startsWith(normalizedName))
938 .map(ci -> ci.getNormalizedName().split(normalizedName)[1])
939 .collect(Collectors.toList());
940 List<String> countersInIds = containerComponent.getComponentInstances().stream()
941 .filter(ci -> ci.getUniqueId() != null && ci.getUniqueId().contains(normalizedName))
942 .map(ci -> ci.getUniqueId().split(normalizedName)[1])
943 .collect(Collectors.toList());
944 List<String> namesAndIdsList = new ArrayList<>(countersInNames);
945 namesAndIdsList.addAll(countersInIds);
946 return getMaxInteger(namesAndIdsList);
949 private Integer getMaxInteger(List<String> counters) {
950 Integer maxCounter = 0;
951 Integer currCounter = null;
952 for (String counter : counters) {
954 currCounter = Integer.parseInt(counter);
955 if (maxCounter < currCounter) {
956 maxCounter = currCounter;
958 } catch (NumberFormatException e) {
962 return currCounter == null ? null : maxCounter;
965 public Either<RequirementCapabilityRelDef, StorageOperationStatus> associateResourceInstances(Component component, String componentId, RequirementCapabilityRelDef requirementDef) {
966 return nodeTemplateOperation.associateResourceInstances(component, componentId, requirementDef);
970 public Either<List<InputDefinition>, StorageOperationStatus> createAndAssociateInputs(Map<String, InputDefinition> inputs, String componentId) {
972 Either<GraphVertex, JanusGraphOperationStatus> getVertexEither = janusGraphDao
973 .getVertexById(componentId, JsonParseFlagEnum.NoParse);
974 if (getVertexEither.isRight()) {
975 log.debug(COULDNT_FETCH_COMPONENT_WITH_AND_UNIQUE_ID_ERROR, componentId, getVertexEither.right().value());
976 return Either.right(DaoStatusConverter.convertJanusGraphStatusToStorageStatus(getVertexEither.right().value()));
980 GraphVertex vertex = getVertexEither.left().value();
981 Map<String, PropertyDataDefinition> inputsMap = inputs.entrySet().stream().collect(Collectors.toMap(Map.Entry::getKey, e -> new PropertyDataDefinition(e.getValue())));
983 StorageOperationStatus status = topologyTemplateOperation.associateInputsToComponent(vertex, inputsMap, componentId);
985 if (StorageOperationStatus.OK == status) {
986 log.debug(COMPONENT_CREATED_SUCCESSFULLY);
987 List<InputDefinition> inputsResList = null;
988 if (inputsMap != null && !inputsMap.isEmpty()) {
989 inputsResList = inputsMap.values().stream()
990 .map(InputDefinition::new)
991 .collect(Collectors.toList());
993 return Either.left(inputsResList);
995 return Either.right(status);
999 public Either<List<InputDefinition>, StorageOperationStatus> addInputsToComponent(Map<String, InputDefinition> inputs, String componentId) {
1001 Either<GraphVertex, JanusGraphOperationStatus> getVertexEither = janusGraphDao
1002 .getVertexById(componentId, JsonParseFlagEnum.NoParse);
1003 if (getVertexEither.isRight()) {
1004 log.debug(COULDNT_FETCH_COMPONENT_WITH_AND_UNIQUE_ID_ERROR, componentId, getVertexEither.right().value());
1005 return Either.right(DaoStatusConverter.convertJanusGraphStatusToStorageStatus(getVertexEither.right().value()));
1009 GraphVertex vertex = getVertexEither.left().value();
1010 Map<String, PropertyDefinition> inputsMap = inputs.entrySet().stream().collect(Collectors.toMap(Map.Entry::getKey, e -> new PropertyDefinition(e.getValue())));
1012 StorageOperationStatus status = topologyTemplateOperation.addToscaDataToToscaElement(vertex, EdgeLabelEnum.INPUTS, VertexTypeEnum.INPUTS, inputsMap, JsonPresentationFields.NAME);
1014 if (StorageOperationStatus.OK == status) {
1015 log.debug(COMPONENT_CREATED_SUCCESSFULLY);
1016 List<InputDefinition> inputsResList = null;
1017 if (inputsMap != null && !inputsMap.isEmpty()) {
1018 inputsResList = inputsMap.values().stream().map(InputDefinition::new).collect(Collectors.toList());
1020 return Either.left(inputsResList);
1022 return Either.right(status);
1027 * Add data types into a Component.
1029 * @param dataTypes datatypes to be added. the key should be each name of data type.
1030 * @param componentId unique ID of Component.
1031 * @return list of data types.
1033 public Either<List<DataTypeDefinition>, StorageOperationStatus> addDataTypesToComponent(Map<String, DataTypeDefinition> dataTypes, String componentId) {
1035 log.trace("#addDataTypesToComponent - enter, componentId={}", componentId);
1037 /* get component vertex */
1038 Either<GraphVertex, JanusGraphOperationStatus> getVertexEither = janusGraphDao
1039 .getVertexById(componentId, JsonParseFlagEnum.NoParse);
1040 if (getVertexEither.isRight()) {
1041 /* not found / error */
1042 log.debug(COULDNT_FETCH_COMPONENT_WITH_AND_UNIQUE_ID_ERROR, componentId, getVertexEither.right().value());
1043 return Either.right(DaoStatusConverter.convertJanusGraphStatusToStorageStatus(getVertexEither.right().value()));
1045 GraphVertex vertex = getVertexEither.left().value();
1046 log.trace("#addDataTypesToComponent - get vertex ok");
1048 // convert DataTypeDefinition to DataTypeDataDefinition
1049 Map<String, DataTypeDataDefinition> dataTypeDataMap = dataTypes.entrySet().stream()
1050 .collect(Collectors.toMap(Map.Entry::getKey, e -> convertDataTypeToDataTypeData(e.getValue())));
1052 // add datatype(s) to the Component.
1053 // if child vertex does not exist, it will be created.
1054 StorageOperationStatus status = topologyTemplateOperation.addToscaDataToToscaElement(vertex,
1055 EdgeLabelEnum.DATA_TYPES, VertexTypeEnum.DATA_TYPES, dataTypeDataMap, JsonPresentationFields.NAME);
1057 if (StorageOperationStatus.OK == status) {
1058 log.debug(COMPONENT_CREATED_SUCCESSFULLY);
1059 List<DataTypeDefinition> inputsResList = null;
1060 if (!dataTypes.isEmpty()) {
1061 inputsResList = new ArrayList<>(dataTypes.values());
1063 return Either.left(inputsResList);
1066 log.trace("#addDataTypesToComponent - leave");
1067 return Either.right(status);
1070 private DataTypeDataDefinition convertDataTypeToDataTypeData(DataTypeDefinition dataType) {
1071 DataTypeDataDefinition dataTypeData = new DataTypeDataDefinition(dataType);
1072 if (CollectionUtils.isNotEmpty(dataType.getProperties())) {
1073 List<PropertyDataDefinition> propertyDataList = dataType.getProperties().stream()
1074 .map(PropertyDataDefinition::new).collect(Collectors.toList());
1075 dataTypeData.setPropertiesData(propertyDataList);
1078 // if "derivedFrom" data_type exists, copy the name to "derivedFromName"
1079 if (dataType.getDerivedFrom() != null && StringUtils.isNotEmpty(dataType.getDerivedFrom().getName())) {
1080 // if names are different, log it
1081 if (!StringUtils.equals(dataTypeData.getDerivedFromName(), dataType.getDerivedFrom().getName())) {
1082 log.debug("#convertDataTypeToDataTypeData - derivedFromName(={}) overwritten by derivedFrom.name(={})",
1083 dataType.getDerivedFromName(), dataType.getDerivedFrom().getName());
1085 dataTypeData.setDerivedFromName(dataType.getDerivedFrom().getName());
1088 // supply "name" field to toscaPresentationValue in each datatype object for DAO operations
1089 dataTypeData.setToscaPresentationValue(JsonPresentationFields.NAME, dataType.getName());
1090 return dataTypeData;
1094 public Either<List<InputDefinition>, StorageOperationStatus> getComponentInputs(String componentId) {
1096 Either<GraphVertex, JanusGraphOperationStatus> getVertexEither = janusGraphDao
1097 .getVertexById(componentId, JsonParseFlagEnum.NoParse);
1098 if (getVertexEither.isRight()) {
1099 log.debug("Couldn't fetch component with and unique id {}, error: {}", componentId, getVertexEither.right().value());
1100 return Either.right(DaoStatusConverter.convertJanusGraphStatusToStorageStatus(getVertexEither.right().value()));
1104 Either<ToscaElement, StorageOperationStatus> toscaElement =
1105 topologyTemplateOperation.getToscaElement(componentId);
1106 if(toscaElement.isRight()) {
1107 return Either.right(toscaElement.right().value());
1110 TopologyTemplate topologyTemplate = (TopologyTemplate) toscaElement.left().value();
1112 Map<String, PropertyDataDefinition> inputsMap = topologyTemplate.getInputs();
1114 List<InputDefinition> inputs = new ArrayList<>();
1115 if(MapUtils.isNotEmpty(inputsMap)) {
1117 inputsMap.values().stream().map(p -> new InputDefinition(p)).collect(Collectors.toList());
1120 return Either.left(inputs);
1123 public Either<List<InputDefinition>, StorageOperationStatus> updateInputsToComponent(List<InputDefinition> inputs, String componentId) {
1125 Either<GraphVertex, JanusGraphOperationStatus> getVertexEither = janusGraphDao
1126 .getVertexById(componentId, JsonParseFlagEnum.NoParse);
1127 if (getVertexEither.isRight()) {
1128 log.debug(COULDNT_FETCH_COMPONENT_WITH_AND_UNIQUE_ID_ERROR, componentId, getVertexEither.right().value());
1129 return Either.right(DaoStatusConverter.convertJanusGraphStatusToStorageStatus(getVertexEither.right().value()));
1133 GraphVertex vertex = getVertexEither.left().value();
1134 List<PropertyDataDefinition> inputsAsDataDef = inputs.stream().map(PropertyDataDefinition::new).collect(Collectors.toList());
1136 StorageOperationStatus status = topologyTemplateOperation.updateToscaDataOfToscaElement(vertex, EdgeLabelEnum.INPUTS, VertexTypeEnum.INPUTS, inputsAsDataDef, JsonPresentationFields.NAME);
1138 if (StorageOperationStatus.OK == status) {
1139 log.debug(COMPONENT_CREATED_SUCCESSFULLY);
1140 List<InputDefinition> inputsResList = null;
1141 if (inputsAsDataDef != null && !inputsAsDataDef.isEmpty()) {
1142 inputsResList = inputsAsDataDef.stream().map(InputDefinition::new).collect(Collectors.toList());
1144 return Either.left(inputsResList);
1146 return Either.right(status);
1150 // region - ComponentInstance
1151 public Either<Map<String, List<ComponentInstanceProperty>>, StorageOperationStatus> associateComponentInstancePropertiesToComponent(Map<String, List<ComponentInstanceProperty>> instProperties, String componentId) {
1153 Either<GraphVertex, JanusGraphOperationStatus> getVertexEither = janusGraphDao
1154 .getVertexById(componentId, JsonParseFlagEnum.NoParse);
1155 if (getVertexEither.isRight()) {
1156 log.debug(COULDNT_FETCH_COMPONENT_WITH_AND_UNIQUE_ID_ERROR, componentId, getVertexEither.right().value());
1157 return Either.right(DaoStatusConverter.convertJanusGraphStatusToStorageStatus(getVertexEither.right().value()));
1161 GraphVertex vertex = getVertexEither.left().value();
1162 Map<String, MapPropertiesDataDefinition> instPropsMap = new HashMap<>();
1163 if (instProperties != null) {
1165 MapPropertiesDataDefinition propertiesMap;
1166 for (Entry<String, List<ComponentInstanceProperty>> entry : instProperties.entrySet()) {
1167 propertiesMap = new MapPropertiesDataDefinition();
1169 propertiesMap.setMapToscaDataDefinition(entry.getValue().stream().map(PropertyDataDefinition::new).collect(Collectors.toMap(PropertyDataDefinition::getName, e -> e)));
1171 instPropsMap.put(entry.getKey(), propertiesMap);
1175 StorageOperationStatus status = topologyTemplateOperation.associateInstPropertiesToComponent(vertex, instPropsMap);
1177 if (StorageOperationStatus.OK == status) {
1178 log.debug(COMPONENT_CREATED_SUCCESSFULLY);
1179 return Either.left(instProperties);
1181 return Either.right(status);
1186 * saves the instInputs as the updated instance inputs of the component container in DB
1188 public Either<Map<String, List<ComponentInstanceInput>>, StorageOperationStatus> updateComponentInstanceInputsToComponent(Map<String, List<ComponentInstanceInput>> instInputs, String componentId) {
1189 if (instInputs == null || instInputs.isEmpty()) {
1190 return Either.left(instInputs);
1192 StorageOperationStatus status;
1193 for (Entry<String, List<ComponentInstanceInput>> inputsPerIntance : instInputs.entrySet()) {
1194 List<ComponentInstanceInput> toscaDataListPerInst = inputsPerIntance.getValue();
1195 List<String> pathKeysPerInst = new ArrayList<>();
1196 pathKeysPerInst.add(inputsPerIntance.getKey());
1197 status = topologyTemplateOperation.updateToscaDataDeepElementsOfToscaElement(componentId, EdgeLabelEnum.INST_INPUTS, VertexTypeEnum.INST_INPUTS, toscaDataListPerInst, pathKeysPerInst, JsonPresentationFields.NAME);
1198 if (status != StorageOperationStatus.OK) {
1199 log.debug("Failed to update component instance inputs for instance {} in component {} edge type {} error {}", inputsPerIntance.getKey(), componentId, EdgeLabelEnum.INST_INPUTS, status);
1200 return Either.right(status);
1204 return Either.left(instInputs);
1208 * saves the instProps as the updated instance properties of the component container in DB
1210 public Either<Map<String, List<ComponentInstanceProperty>>, StorageOperationStatus> updateComponentInstancePropsToComponent(Map<String, List<ComponentInstanceProperty>> instProps, String componentId) {
1211 if (instProps == null || instProps.isEmpty()) {
1212 return Either.left(instProps);
1214 StorageOperationStatus status;
1215 for (Entry<String, List<ComponentInstanceProperty>> propsPerIntance : instProps.entrySet()) {
1216 List<ComponentInstanceProperty> toscaDataListPerInst = propsPerIntance.getValue();
1217 List<String> pathKeysPerInst = new ArrayList<>();
1218 pathKeysPerInst.add(propsPerIntance.getKey());
1219 status = topologyTemplateOperation.updateToscaDataDeepElementsOfToscaElement(componentId, EdgeLabelEnum.INST_PROPERTIES, VertexTypeEnum.INST_PROPERTIES, toscaDataListPerInst, pathKeysPerInst, JsonPresentationFields.NAME);
1220 if (status != StorageOperationStatus.OK) {
1221 log.debug("Failed to update component instance inputs for instance {} in component {} edge type {} error {}", propsPerIntance.getKey(), componentId, EdgeLabelEnum.INST_PROPERTIES, status);
1222 return Either.right(status);
1226 return Either.left(instProps);
1229 public Either<Map<String, List<ComponentInstanceInput>>, StorageOperationStatus> associateComponentInstanceInputsToComponent(Map<String, List<ComponentInstanceInput>> instInputs, String componentId) {
1231 Either<GraphVertex, JanusGraphOperationStatus> getVertexEither = janusGraphDao
1232 .getVertexById(componentId, JsonParseFlagEnum.NoParse);
1233 if (getVertexEither.isRight()) {
1234 log.debug(COULDNT_FETCH_COMPONENT_WITH_AND_UNIQUE_ID_ERROR, componentId, getVertexEither.right().value());
1235 return Either.right(DaoStatusConverter.convertJanusGraphStatusToStorageStatus(getVertexEither.right().value()));
1238 GraphVertex vertex = getVertexEither.left().value();
1239 Map<String, MapPropertiesDataDefinition> instPropsMap = new HashMap<>();
1240 if (instInputs != null) {
1242 MapPropertiesDataDefinition propertiesMap;
1243 for (Entry<String, List<ComponentInstanceInput>> entry : instInputs.entrySet()) {
1244 propertiesMap = new MapPropertiesDataDefinition();
1246 propertiesMap.setMapToscaDataDefinition(entry.getValue().stream().map(PropertyDataDefinition::new).collect(Collectors.toMap(PropertyDataDefinition::getName, e -> e)));
1248 instPropsMap.put(entry.getKey(), propertiesMap);
1252 StorageOperationStatus status = topologyTemplateOperation.associateInstInputsToComponent(vertex, instPropsMap);
1254 if (StorageOperationStatus.OK == status) {
1255 log.debug(COMPONENT_CREATED_SUCCESSFULLY);
1256 return Either.left(instInputs);
1258 return Either.right(status);
1262 public Either<Map<String, List<ComponentInstanceInput>>, StorageOperationStatus> addComponentInstanceInputsToComponent(Component containerComponent, Map<String, List<ComponentInstanceInput>> instProperties) {
1263 requireNonNull(instProperties);
1264 StorageOperationStatus status;
1265 for (Entry<String, List<ComponentInstanceInput>> entry : instProperties.entrySet()) {
1266 List<ComponentInstanceInput> props = entry.getValue();
1267 String componentInstanceId = entry.getKey();
1268 if (!isEmpty(props)) {
1269 for (ComponentInstanceInput property : props) {
1270 List<ComponentInstanceInput> componentInstancesInputs = containerComponent.getComponentInstancesInputs().get(componentInstanceId);
1271 Optional<ComponentInstanceInput> instanceProperty = componentInstancesInputs.stream()
1272 .filter(p -> p.getName().equals(property.getName()))
1274 if (instanceProperty.isPresent()) {
1275 status = updateComponentInstanceInput(containerComponent, componentInstanceId, property);
1277 status = addComponentInstanceInput(containerComponent, componentInstanceId, property);
1279 if (status != StorageOperationStatus.OK) {
1280 log.debug("Failed to update instance input {} for instance {} error {} ", property, componentInstanceId, status);
1281 return Either.right(status);
1283 log.trace("instance input {} for instance {} updated", property, componentInstanceId);
1288 return Either.left(instProperties);
1291 public Either<Map<String, List<ComponentInstanceProperty>>, StorageOperationStatus> addComponentInstancePropertiesToComponent(Component containerComponent, Map<String, List<ComponentInstanceProperty>> instProperties) {
1292 requireNonNull(instProperties);
1293 for (Entry<String, List<ComponentInstanceProperty>> entry : instProperties.entrySet()) {
1294 List<ComponentInstanceProperty> props = entry.getValue();
1295 String componentInstanceId = entry.getKey();
1296 List<ComponentInstanceProperty> originalComponentInstProps =
1297 containerComponent.getComponentInstancesProperties().get(componentInstanceId);
1298 Map<String, List<CapabilityDefinition>> containerComponentCapabilities = containerComponent.getCapabilities();
1300 if(isEmpty(props)) {
1303 for (ComponentInstanceProperty property : props) {
1304 StorageOperationStatus status = null;
1305 String propertyParentUniqueId = property.getParentUniqueId();
1306 Optional<CapabilityDefinition>
1307 capPropDefinition = getPropertyCapability(propertyParentUniqueId, containerComponent);
1308 if(capPropDefinition.isPresent() && MapUtils.isNotEmpty(containerComponentCapabilities)) {
1309 status = populateAndUpdateInstanceCapProperty(containerComponent, componentInstanceId,
1310 containerComponentCapabilities, property, capPropDefinition.get());
1312 if(status == null) {
1313 status = updateOrAddComponentInstanceProperty(containerComponent, componentInstanceId,
1314 originalComponentInstProps, property);
1316 if(status != StorageOperationStatus.OK) {
1317 return Either.right(status);
1321 return Either.left(instProperties);
1324 private StorageOperationStatus populateAndUpdateInstanceCapProperty(Component containerComponent, String componentInstanceId,
1325 Map<String, List<CapabilityDefinition>> containerComponentCapabilities,
1326 ComponentInstanceProperty property,
1327 CapabilityDefinition capabilityDefinition) {
1328 List<CapabilityDefinition> capabilityDefinitions = containerComponentCapabilities.get(capabilityDefinition.getType());
1329 if(CollectionUtils.isEmpty(capabilityDefinitions)) {
1332 Optional<CapabilityDefinition> capDefToGetProp = capabilityDefinitions.stream()
1333 .filter(cap -> cap.getUniqueId().equals(capabilityDefinition.getUniqueId()) && cap.getPath().size() == 1).findAny();
1334 if(capDefToGetProp.isPresent()) {
1335 return updateInstanceCapabilityProperty(containerComponent, componentInstanceId, property, capDefToGetProp.get());
1340 private static Optional<CapabilityDefinition> getPropertyCapability(String propertyParentUniqueId,
1341 Component containerComponent) {
1343 Map<String, List<CapabilityDefinition>> componentCapabilities = containerComponent.getCapabilities();
1344 if(MapUtils.isEmpty(componentCapabilities)){
1345 return Optional.empty();
1347 List<CapabilityDefinition> capabilityDefinitionList = componentCapabilities.values()
1348 .stream().flatMap(Collection::stream).collect(Collectors.toList());
1349 if(CollectionUtils.isEmpty(capabilityDefinitionList)){
1350 return Optional.empty();
1352 return capabilityDefinitionList.stream()
1353 .filter(capabilityDefinition -> capabilityDefinition.getUniqueId().equals(propertyParentUniqueId))
1357 private StorageOperationStatus updateOrAddComponentInstanceProperty(Component containerComponent,
1358 String componentInstanceId, List<ComponentInstanceProperty> originalComponentInstProps,
1359 ComponentInstanceProperty property)
1361 StorageOperationStatus status;
1362 // check if the property already exists or not
1363 Optional<ComponentInstanceProperty> instanceProperty = originalComponentInstProps.stream()
1364 .filter(p -> p.getUniqueId().equals(property.getUniqueId())).findAny();
1365 if (instanceProperty.isPresent()) {
1366 status = updateComponentInstanceProperty(containerComponent, componentInstanceId, property);
1368 status = addComponentInstanceProperty(containerComponent, componentInstanceId, property);
1370 if (status != StorageOperationStatus.OK) {
1371 log.debug("Failed to update instance property {} for instance {} error {} ",
1372 property, componentInstanceId, status);
1377 public StorageOperationStatus updateInstanceCapabilityProperty(Component containerComponent, String componentInstanceId,
1378 ComponentInstanceProperty property,
1379 CapabilityDefinition capabilityDefinition) {
1380 Optional<ComponentInstance> fetchedCIOptional = containerComponent.getComponentInstanceById(componentInstanceId);
1381 if(!fetchedCIOptional.isPresent()) {
1382 return StorageOperationStatus.GENERAL_ERROR;
1384 Either<Component, StorageOperationStatus> getComponentRes =
1385 getToscaFullElement(fetchedCIOptional.get().getComponentUid());
1386 if(getComponentRes.isRight()) {
1387 return StorageOperationStatus.GENERAL_ERROR;
1389 Optional<Component> componentOptional = isNodeServiceProxy(getComponentRes.left().value());
1391 if(!componentOptional.isPresent()) {
1392 propOwner = componentInstanceId;
1394 propOwner = fetchedCIOptional.get().getSourceModelUid();
1396 StorageOperationStatus status;
1397 StringBuilder sb = new StringBuilder(componentInstanceId);
1398 sb.append(ModelConverter.CAP_PROP_DELIM).append(propOwner).append(ModelConverter.CAP_PROP_DELIM)
1399 .append(capabilityDefinition.getType()).append(ModelConverter.CAP_PROP_DELIM).append(capabilityDefinition.getName());
1400 String capKey = sb.toString();
1401 status = updateComponentInstanceCapabiltyProperty(containerComponent, componentInstanceId, capKey, property);
1402 if (status != StorageOperationStatus.OK) {
1403 log.debug("Failed to update instance capability property {} for instance {} error {} ", property,
1404 componentInstanceId, status);
1407 return StorageOperationStatus.OK;
1410 private Optional<Component> isNodeServiceProxy(Component component) {
1411 if (component.getComponentType().equals(ComponentTypeEnum.SERVICE)) {
1412 return Optional.empty();
1414 Resource resource = (Resource) component;
1415 ResourceTypeEnum resType = resource.getResourceType();
1416 if(resType.equals(ResourceTypeEnum.ServiceProxy)) {
1417 return Optional.of(component);
1419 return Optional.empty();
1422 public StorageOperationStatus associateDeploymentArtifactsToInstances(Map<String, Map<String, ArtifactDefinition>> instDeploymentArtifacts, Component component, User user) {
1424 Either<GraphVertex, JanusGraphOperationStatus> getVertexEither = janusGraphDao.getVertexById(component.getUniqueId(), JsonParseFlagEnum.NoParse);
1425 if (getVertexEither.isRight()) {
1426 log.debug(COULDNT_FETCH_COMPONENT_WITH_AND_UNIQUE_ID_ERROR, component.getUniqueId(), getVertexEither.right().value());
1427 return DaoStatusConverter.convertJanusGraphStatusToStorageStatus(getVertexEither.right().value());
1431 GraphVertex vertex = getVertexEither.left().value();
1432 Map<String, MapArtifactDataDefinition> instArtMap = new HashMap<>();
1433 if (instDeploymentArtifacts != null) {
1435 MapArtifactDataDefinition artifactsMap;
1436 for (Entry<String, Map<String, ArtifactDefinition>> entry : instDeploymentArtifacts.entrySet()) {
1437 Map<String, ArtifactDefinition> artList = entry.getValue();
1438 Map<String, ArtifactDataDefinition> artifacts = artList.entrySet().stream().collect(Collectors.toMap(Map.Entry::getKey, e -> new ArtifactDataDefinition(e.getValue())));
1439 artifactsMap = nodeTemplateOperation.prepareInstDeploymentArtifactPerInstance(artifacts, entry.getKey(), user, NodeTemplateOperation.HEAT_VF_ENV_NAME);
1441 instArtMap.put(entry.getKey(), artifactsMap);
1444 ModelConverter.setComponentInstancesDeploymentArtifactsToComponent(instArtMap, component);
1445 return topologyTemplateOperation.associateInstDeploymentArtifactsToComponent(vertex, instArtMap);
1448 public StorageOperationStatus associateArtifactsToInstances(Map<String, Map<String, ArtifactDefinition>> instArtifacts, Component component) {
1450 Either<GraphVertex, JanusGraphOperationStatus> getVertexEither = janusGraphDao.getVertexById(component.getUniqueId(), JsonParseFlagEnum.NoParse);
1451 if (getVertexEither.isRight()) {
1452 log.debug(COULDNT_FETCH_COMPONENT_WITH_AND_UNIQUE_ID_ERROR, component.getUniqueId(), getVertexEither.right().value());
1453 return DaoStatusConverter.convertJanusGraphStatusToStorageStatus(getVertexEither.right().value());
1457 GraphVertex vertex = getVertexEither.left().value();
1458 Map<String, MapArtifactDataDefinition> instArtMap = new HashMap<>();
1459 if (instArtifacts != null) {
1461 MapArtifactDataDefinition artifactsMap;
1462 for (Entry<String, Map<String, ArtifactDefinition>> entry : instArtifacts.entrySet()) {
1463 Map<String, ArtifactDefinition> artList = entry.getValue();
1464 Map<String, ArtifactDataDefinition> artifacts = artList.entrySet().stream().collect(Collectors.toMap(Map.Entry::getKey, e -> new ArtifactDataDefinition(e.getValue())));
1465 artifactsMap = new MapArtifactDataDefinition(artifacts);
1467 instArtMap.put(entry.getKey(), artifactsMap);
1470 ModelConverter.setComponentInstancesInformationalArtifactsToComponent(instArtMap, component);
1471 return topologyTemplateOperation.associateInstArtifactsToComponent(vertex, instArtMap);
1475 public StorageOperationStatus associateInstAttributeToComponentToInstances(Map<String, List<AttributeDataDefinition>> instArttributes, Component component) {
1477 Either<GraphVertex, JanusGraphOperationStatus> getVertexEither = janusGraphDao.getVertexById(component.getUniqueId(), JsonParseFlagEnum.NoParse);
1478 if (getVertexEither.isRight()) {
1479 log.debug(COULDNT_FETCH_COMPONENT_WITH_AND_UNIQUE_ID_ERROR, component.getUniqueId(), getVertexEither.right().value());
1480 return DaoStatusConverter.convertJanusGraphStatusToStorageStatus(getVertexEither.right().value());
1484 GraphVertex vertex = getVertexEither.left().value();
1485 Map<String, MapAttributesDataDefinition> instAttr = new HashMap<>();
1486 if (instArttributes != null) {
1488 MapAttributesDataDefinition attributesMap;
1489 for (Entry<String, List<AttributeDataDefinition>> entry : instArttributes.entrySet()) {
1490 final List<AttributeDataDefinition> value = entry.getValue();
1491 attributesMap = new MapAttributesDataDefinition();
1492 attributesMap.setMapToscaDataDefinition(value.stream().map(AttributeDataDefinition::new).collect(Collectors.toMap(AttributeDataDefinition::getName, e -> e)));
1493 instAttr.put(entry.getKey(), attributesMap);
1496 setComponentInstanceAttributesOnComponent(component, instAttr);
1497 return topologyTemplateOperation.associateInstAttributeToComponent(vertex, instAttr);
1501 private void setComponentInstanceAttributesOnComponent(Component resource, Map<String, MapAttributesDataDefinition> instAttr) {
1502 Map<String, List<ComponentInstanceAttribute>> componentInstancesAttributes = resource.getComponentInstancesAttributes();
1503 if (componentInstancesAttributes == null)
1504 componentInstancesAttributes = new HashMap<>();
1505 componentInstancesAttributes.putAll(ModelConverter.getComponentInstancesAttributes(instAttr));
1506 resource.setComponentInstancesAttributes(componentInstancesAttributes);
1509 public StorageOperationStatus associateOrAddCalculatedCapReq(Map<ComponentInstance, Map<String, List<CapabilityDefinition>>> instCapabilties, Map<ComponentInstance, Map<String, List<RequirementDefinition>>> instReg, Component component) {
1510 Either<GraphVertex, JanusGraphOperationStatus> getVertexEither = janusGraphDao.getVertexById(component.getUniqueId(), JsonParseFlagEnum.NoParse);
1511 if (getVertexEither.isRight()) {
1512 log.debug(COULDNT_FETCH_COMPONENT_WITH_AND_UNIQUE_ID_ERROR, component.getUniqueId(), getVertexEither.right().value());
1513 return DaoStatusConverter.convertJanusGraphStatusToStorageStatus(getVertexEither.right().value());
1517 GraphVertex vertex = getVertexEither.left().value();
1519 Map<String, MapListRequirementDataDefinition> calcRequirements = new HashMap<>();
1521 Map<String, MapListCapabilityDataDefinition> calcCapabilty = new HashMap<>();
1522 Map<String, MapCapabilityProperty> calculatedCapabilitiesProperties = new HashMap<>();
1523 if (instCapabilties != null) {
1524 for (Entry<ComponentInstance, Map<String, List<CapabilityDefinition>>> entry : instCapabilties.entrySet()) {
1526 Map<String, List<CapabilityDefinition>> caps = entry.getValue();
1527 Map<String, ListCapabilityDataDefinition> mapToscaDataDefinition = new HashMap<>();
1528 for (Entry<String, List<CapabilityDefinition>> instCapability : caps.entrySet()) {
1529 mapToscaDataDefinition.put(instCapability.getKey(), new ListCapabilityDataDefinition(instCapability.getValue().stream().map(CapabilityDataDefinition::new).collect(Collectors.toList())));
1532 ComponentInstanceDataDefinition componentInstance = new ComponentInstanceDataDefinition(entry.getKey());
1533 MapListCapabilityDataDefinition capMap = nodeTemplateOperation.prepareCalculatedCapabiltyForNodeType(mapToscaDataDefinition, componentInstance);
1535 MapCapabilityProperty mapCapabilityProperty = ModelConverter.convertToMapOfMapCapabiltyProperties(caps, componentInstance.getUniqueId(), true);
1537 calcCapabilty.put(entry.getKey().getUniqueId(), capMap);
1538 calculatedCapabilitiesProperties.put(entry.getKey().getUniqueId(), mapCapabilityProperty);
1542 if (instReg != null) {
1543 for (Entry<ComponentInstance, Map<String, List<RequirementDefinition>>> entry : instReg.entrySet()) {
1545 Map<String, List<RequirementDefinition>> req = entry.getValue();
1546 Map<String, ListRequirementDataDefinition> mapToscaDataDefinition = new HashMap<>();
1547 for (Entry<String, List<RequirementDefinition>> instReq : req.entrySet()) {
1548 mapToscaDataDefinition.put(instReq.getKey(), new ListRequirementDataDefinition(instReq.getValue().stream().map(RequirementDataDefinition::new).collect(Collectors.toList())));
1551 MapListRequirementDataDefinition reqMap = nodeTemplateOperation.prepareCalculatedRequirementForNodeType(mapToscaDataDefinition, new ComponentInstanceDataDefinition(entry.getKey()));
1553 String componentInstanceId = entry.getKey().getUniqueId();
1554 calcRequirements.put(componentInstanceId, reqMap);
1558 StorageOperationStatus storageOperationStatus = topologyTemplateOperation.associateOrAddCalcCapReqToComponent(vertex, calcRequirements, calcCapabilty, calculatedCapabilitiesProperties);
1559 updateInstancesCapAndReqOnComponentFromDB(component);
1560 return storageOperationStatus;
1563 private void updateInstancesCapAndReqOnComponentFromDB(Component component) {
1564 ComponentParametersView componentParametersView = new ComponentParametersView(true);
1565 componentParametersView.setIgnoreCapabilities(false);
1566 componentParametersView.setIgnoreRequirements(false);
1567 componentParametersView.setIgnoreCapabiltyProperties(false);
1568 componentParametersView.setIgnoreComponentInstances(false);
1569 Either<Component, StorageOperationStatus> componentEither = getToscaElement(component.getUniqueId(), componentParametersView);
1570 if (componentEither.isRight()) {
1571 throw new StorageException(StorageOperationStatus.NOT_FOUND);
1573 Component updatedComponent = componentEither.left().value();
1574 component.setCapabilities(updatedComponent.getCapabilities());
1575 component.setRequirements(updatedComponent.getRequirements());
1576 component.setComponentInstances(updatedComponent.getComponentInstances());
1579 private Either<List<Service>, StorageOperationStatus> getLatestVersionNonCheckoutServicesMetadataOnly(Map<GraphPropertyEnum, Object> hasProps, Map<GraphPropertyEnum, Object> hasNotProps) {
1580 List<Service> services = new ArrayList<>();
1581 List<LifecycleStateEnum> states = new ArrayList<>();
1583 hasProps.put(GraphPropertyEnum.COMPONENT_TYPE, ComponentTypeEnum.SERVICE.name());
1584 hasProps.put(GraphPropertyEnum.IS_HIGHEST_VERSION, true);
1587 states.add(LifecycleStateEnum.NOT_CERTIFIED_CHECKOUT);
1588 hasNotProps.put(GraphPropertyEnum.STATE, states);
1589 hasNotProps.put(GraphPropertyEnum.IS_DELETED, true);
1590 hasNotProps.put(GraphPropertyEnum.IS_ARCHIVED, true);
1591 return fetchServicesByCriteria(services, hasProps, hasNotProps);
1594 private Either<List<Component>, StorageOperationStatus> getLatestVersionNotAbstractToscaElementsMetadataOnly(boolean isAbstract, ComponentTypeEnum componentTypeEnum, String internalComponentType, VertexTypeEnum vertexType) {
1595 List<Service> services = null;
1596 Map<GraphPropertyEnum, Object> hasProps = new EnumMap<>(GraphPropertyEnum.class);
1597 Map<GraphPropertyEnum, Object> hasNotProps = new EnumMap<>(GraphPropertyEnum.class);
1598 fillPropsMap(hasProps, hasNotProps, internalComponentType, componentTypeEnum, isAbstract, vertexType);
1599 Either<List<GraphVertex>, JanusGraphOperationStatus> getRes = janusGraphDao
1600 .getByCriteria(vertexType, hasProps, hasNotProps, JsonParseFlagEnum.ParseMetadata);
1601 if (getRes.isRight()) {
1602 if (getRes.right().value().equals(JanusGraphOperationStatus.NOT_FOUND)) {
1603 return Either.left(new ArrayList<>());
1605 return Either.right(DaoStatusConverter.convertJanusGraphStatusToStorageStatus(getRes.right().value()));
1608 // region -> Fetch non checked-out services
1609 if (internalComponentType != null && internalComponentType.toLowerCase().trim().equals(SERVICE) && VertexTypeEnum.NODE_TYPE == vertexType) {
1610 Either<List<Service>, StorageOperationStatus> result = getLatestVersionNonCheckoutServicesMetadataOnly(new EnumMap<>(GraphPropertyEnum.class), new EnumMap<>(GraphPropertyEnum.class));
1611 if (result.isRight()) {
1612 log.debug("Failed to fetch services for");
1613 return Either.right(result.right().value());
1615 services = result.left().value();
1616 if (log.isTraceEnabled() && isEmpty(services))
1617 log.trace("No relevant services available");
1620 List<Component> nonAbstractLatestComponents = new ArrayList<>();
1621 ComponentParametersView params = new ComponentParametersView(true);
1622 params.setIgnoreAllVersions(false);
1623 for (GraphVertex vertexComponent : getRes.left().value()) {
1624 Either<ToscaElement, StorageOperationStatus> componentRes = topologyTemplateOperation.getLightComponent(vertexComponent, componentTypeEnum, params);
1625 if (componentRes.isRight()) {
1626 log.debug("Failed to fetch light element for {} error {}", vertexComponent.getUniqueId(), componentRes.right().value());
1627 return Either.right(componentRes.right().value());
1629 Component component = ModelConverter.convertFromToscaElement(componentRes.left().value());
1630 nonAbstractLatestComponents.add(component);
1633 if (CollectionUtils.isNotEmpty(services)) {
1634 nonAbstractLatestComponents.addAll(services);
1636 return Either.left(nonAbstractLatestComponents);
1639 public Either<ComponentMetadataData, StorageOperationStatus> getLatestComponentMetadataByUuid(String componentUuid, JsonParseFlagEnum parseFlag, Boolean isHighest) {
1641 Either<ComponentMetadataData, StorageOperationStatus> result;
1642 Map<GraphPropertyEnum, Object> hasProperties = new EnumMap<>(GraphPropertyEnum.class);
1643 hasProperties.put(GraphPropertyEnum.UUID, componentUuid);
1644 if (isHighest != null) {
1645 hasProperties.put(GraphPropertyEnum.IS_HIGHEST_VERSION, isHighest);
1647 Map<GraphPropertyEnum, Object> propertiesNotToMatch = new EnumMap<>(GraphPropertyEnum.class);
1648 propertiesNotToMatch.put(GraphPropertyEnum.IS_DELETED, true);
1649 propertiesNotToMatch.put(GraphPropertyEnum.IS_ARCHIVED, true); //US382674, US382683
1651 Either<List<GraphVertex>, JanusGraphOperationStatus> getRes = janusGraphDao
1652 .getByCriteria(null, hasProperties, propertiesNotToMatch, parseFlag);
1653 if (getRes.isRight()) {
1654 result = Either.right(DaoStatusConverter.convertJanusGraphStatusToStorageStatus(getRes.right().value()));
1656 List<ComponentMetadataData> latestVersionList = getRes.left().value().stream().map(ModelConverter::convertToComponentMetadata).collect(Collectors.toList());
1657 ComponentMetadataData latestVersion = latestVersionList.size() == 1 ? latestVersionList.get(0)
1658 : latestVersionList.stream().max((c1, c2) -> Double.compare(Double.parseDouble(c1.getMetadataDataDefinition().getVersion()), Double.parseDouble(c2.getMetadataDataDefinition().getVersion()))).get();
1659 result = Either.left(latestVersion);
1664 public Either<ComponentMetadataData, StorageOperationStatus> getComponentMetadata(String componentId) {
1665 Either<ComponentMetadataData, StorageOperationStatus> result;
1666 Either<GraphVertex, JanusGraphOperationStatus> getRes = janusGraphDao
1667 .getVertexById(componentId, JsonParseFlagEnum.ParseMetadata);
1668 if (getRes.isRight()) {
1669 result = Either.right(DaoStatusConverter.convertJanusGraphStatusToStorageStatus(getRes.right().value()));
1671 ComponentMetadataData componentMetadata = ModelConverter.convertToComponentMetadata(getRes.left().value());
1672 result = Either.left(componentMetadata);
1677 public Either<List<Component>, StorageOperationStatus> getLatestVersionNotAbstractComponents(boolean isAbstract, ComponentTypeEnum componentTypeEnum,
1678 String internalComponentType, List<String> componentUids) {
1680 List<Component> components = new ArrayList<>();
1681 if (componentUids == null) {
1682 Either<List<String>, StorageOperationStatus> componentUidsRes = getComponentUids(isAbstract, componentTypeEnum, internalComponentType);
1683 if (componentUidsRes.isRight()) {
1684 return Either.right(componentUidsRes.right().value());
1686 componentUids = componentUidsRes.left().value();
1688 if (!isEmpty(componentUids)) {
1689 for (String componentUid : componentUids) {
1690 ComponentParametersView componentParametersView = buildComponentViewForNotAbstract();
1691 if ("vl".equalsIgnoreCase(internalComponentType)) {
1692 componentParametersView.setIgnoreCapabilities(false);
1693 componentParametersView.setIgnoreRequirements(false);
1695 Either<ToscaElement, StorageOperationStatus> getToscaElementRes = nodeTemplateOperation.getToscaElementOperation(componentTypeEnum).getLightComponent(componentUid, componentTypeEnum, componentParametersView);
1696 if (getToscaElementRes.isRight()) {
1697 log.debug("Failed to fetch resource for error is {}", getToscaElementRes.right().value());
1698 return Either.right(getToscaElementRes.right().value());
1700 Component component = ModelConverter.convertFromToscaElement(getToscaElementRes.left().value());
1701 nullifySomeComponentProperties(component);
1702 components.add(component);
1705 return Either.left(components);
1708 public void nullifySomeComponentProperties(Component component) {
1709 component.setContactId(null);
1710 component.setCreationDate(null);
1711 component.setCreatorUserId(null);
1712 component.setCreatorFullName(null);
1713 component.setLastUpdateDate(null);
1714 component.setLastUpdaterUserId(null);
1715 component.setLastUpdaterFullName(null);
1716 component.setNormalizedName(null);
1719 private Either<List<String>, StorageOperationStatus> getComponentUids(boolean isAbstract, ComponentTypeEnum componentTypeEnum, String internalComponentType) {
1721 Either<List<Component>, StorageOperationStatus> getToscaElementsRes = getLatestVersionNotAbstractMetadataOnly(isAbstract, componentTypeEnum, internalComponentType);
1722 if (getToscaElementsRes.isRight()) {
1723 return Either.right(getToscaElementsRes.right().value());
1725 List<Component> collection = getToscaElementsRes.left().value();
1726 List<String> componentUids;
1727 if (collection == null) {
1728 componentUids = new ArrayList<>();
1730 componentUids = collection.stream()
1731 .map(Component::getUniqueId)
1732 .collect(Collectors.toList());
1734 return Either.left(componentUids);
1737 private ComponentParametersView buildComponentViewForNotAbstract() {
1738 ComponentParametersView componentParametersView = new ComponentParametersView();
1739 componentParametersView.disableAll();
1740 componentParametersView.setIgnoreCategories(false);
1741 componentParametersView.setIgnoreAllVersions(false);
1742 return componentParametersView;
1745 public Either<Boolean, StorageOperationStatus> validateComponentNameExists(String name, ResourceTypeEnum resourceType, ComponentTypeEnum componentType) {
1746 Either<Boolean, StorageOperationStatus> result = validateComponentNameUniqueness(name, resourceType, componentType);
1747 if (result.isLeft()) {
1748 result = Either.left(!result.left().value());
1753 public Either<Boolean, StorageOperationStatus> validateComponentNameUniqueness(String name, ResourceTypeEnum resourceType, ComponentTypeEnum componentType) {
1754 VertexTypeEnum vertexType = ModelConverter.isAtomicComponent(resourceType) ? VertexTypeEnum.NODE_TYPE : VertexTypeEnum.TOPOLOGY_TEMPLATE;
1755 String normalizedName = ValidationUtils.normaliseComponentName(name);
1756 Map<GraphPropertyEnum, Object> properties = new EnumMap<>(GraphPropertyEnum.class);
1757 properties.put(GraphPropertyEnum.NORMALIZED_NAME, normalizedName);
1758 properties.put(GraphPropertyEnum.COMPONENT_TYPE, componentType.name());
1760 Either<List<GraphVertex>, JanusGraphOperationStatus> vertexEither = janusGraphDao
1761 .getByCriteria(vertexType, properties, JsonParseFlagEnum.NoParse);
1762 if (vertexEither.isRight() && vertexEither.right().value() != JanusGraphOperationStatus.NOT_FOUND) {
1763 log.debug("failed to get vertex from graph with property normalizedName: {}", normalizedName);
1764 return Either.right(DaoStatusConverter.convertJanusGraphStatusToStorageStatus(vertexEither.right().value()));
1766 List<GraphVertex> vertexList = vertexEither.isLeft() ? vertexEither.left().value() : null;
1767 if (vertexList != null && !vertexList.isEmpty()) {
1768 return Either.left(false);
1770 return Either.left(true);
1774 private void fillNodeTypePropsMap(final Map<GraphPropertyEnum, Object> hasProps,
1775 final Map<GraphPropertyEnum, Object> hasNotProps,
1776 final String internalComponentType) {
1777 final Configuration configuration = ConfigurationManager.getConfigurationManager().getConfiguration();
1778 final List<String> allowedTypes;
1780 if (ComponentTypeEnum.SERVICE.getValue().equalsIgnoreCase(internalComponentType)) {
1781 allowedTypes = containerInstanceTypesData.getComponentAllowedList(ComponentTypeEnum.SERVICE, null);
1783 final ResourceTypeEnum resourceType = ResourceTypeEnum.getTypeIgnoreCase(internalComponentType);
1784 allowedTypes = containerInstanceTypesData.getComponentAllowedList(ComponentTypeEnum.RESOURCE, resourceType);
1786 final List<String> allResourceTypes = configuration.getResourceTypes();
1787 if (allowedTypes == null) {
1788 hasNotProps.put(GraphPropertyEnum.RESOURCE_TYPE, allResourceTypes);
1792 if (ResourceTypeEnum.VL.getValue().equalsIgnoreCase(internalComponentType)) {
1793 hasProps.put(GraphPropertyEnum.RESOURCE_TYPE, allowedTypes);
1795 final List<String> notAllowedTypes = allResourceTypes.stream().filter(s -> !allowedTypes.contains(s))
1796 .collect(Collectors.toList());
1797 hasNotProps.put(GraphPropertyEnum.RESOURCE_TYPE, notAllowedTypes);
1801 private void fillTopologyTemplatePropsMap(Map<GraphPropertyEnum, Object> hasProps, Map<GraphPropertyEnum, Object> hasNotProps, ComponentTypeEnum componentTypeEnum) {
1802 switch (componentTypeEnum) {
1804 hasProps.put(GraphPropertyEnum.COMPONENT_TYPE, ComponentTypeEnum.RESOURCE.name());
1807 hasProps.put(GraphPropertyEnum.COMPONENT_TYPE, ComponentTypeEnum.SERVICE.name());
1812 hasNotProps.put(GraphPropertyEnum.RESOURCE_TYPE, ResourceTypeEnum.CVFC.name());
1815 private void fillPropsMap(Map<GraphPropertyEnum, Object> hasProps, Map<GraphPropertyEnum, Object> hasNotProps, String internalComponentType, ComponentTypeEnum componentTypeEnum, boolean isAbstract, VertexTypeEnum internalVertexType) {
1816 hasNotProps.put(GraphPropertyEnum.STATE, LifecycleStateEnum.NOT_CERTIFIED_CHECKOUT.name());
1818 hasNotProps.put(GraphPropertyEnum.IS_DELETED, true);
1819 hasNotProps.put(GraphPropertyEnum.IS_ARCHIVED, true);
1820 hasProps.put(GraphPropertyEnum.IS_HIGHEST_VERSION, true);
1821 if (VertexTypeEnum.NODE_TYPE == internalVertexType) {
1822 hasProps.put(GraphPropertyEnum.IS_ABSTRACT, isAbstract);
1823 if (internalComponentType != null) {
1824 fillNodeTypePropsMap(hasProps, hasNotProps, internalComponentType);
1827 fillTopologyTemplatePropsMap(hasProps, hasNotProps, componentTypeEnum);
1831 private List<VertexTypeEnum> getInternalVertexTypes(ComponentTypeEnum componentTypeEnum, String internalComponentType) {
1832 List<VertexTypeEnum> internalVertexTypes = new ArrayList<>();
1833 if (ComponentTypeEnum.RESOURCE == componentTypeEnum) {
1834 internalVertexTypes.add(VertexTypeEnum.NODE_TYPE);
1836 if (ComponentTypeEnum.SERVICE == componentTypeEnum || SERVICE.equalsIgnoreCase(internalComponentType)) {
1837 internalVertexTypes.add(VertexTypeEnum.TOPOLOGY_TEMPLATE);
1839 return internalVertexTypes;
1842 public Either<List<Component>, StorageOperationStatus> getLatestVersionNotAbstractMetadataOnly(boolean isAbstract, ComponentTypeEnum componentTypeEnum, String internalComponentType) {
1843 List<VertexTypeEnum> internalVertexTypes = getInternalVertexTypes(componentTypeEnum, internalComponentType);
1844 List<Component> result = new ArrayList<>();
1845 for (VertexTypeEnum vertexType : internalVertexTypes) {
1846 Either<List<Component>, StorageOperationStatus> listByVertexType = getLatestVersionNotAbstractToscaElementsMetadataOnly(isAbstract, componentTypeEnum, internalComponentType, vertexType);
1847 if (listByVertexType.isRight()) {
1848 return listByVertexType;
1850 result.addAll(listByVertexType.left().value());
1852 return Either.left(result);
1856 private Either<List<Component>, StorageOperationStatus> getLatestComponentListByUuid(String componentUuid, Map<GraphPropertyEnum, Object> additionalPropertiesToMatch) {
1857 Map<GraphPropertyEnum, Object> propertiesToMatch = new EnumMap<>(GraphPropertyEnum.class);
1858 if (additionalPropertiesToMatch != null) {
1859 propertiesToMatch.putAll(additionalPropertiesToMatch);
1861 propertiesToMatch.put(GraphPropertyEnum.IS_HIGHEST_VERSION, true);
1862 return getComponentListByUuid(componentUuid, propertiesToMatch);
1865 public Either<Component, StorageOperationStatus> getComponentByUuidAndVersion(String componentUuid, String version) {
1866 Map<GraphPropertyEnum, Object> propertiesToMatch = new EnumMap<>(GraphPropertyEnum.class);
1868 propertiesToMatch.put(GraphPropertyEnum.UUID, componentUuid);
1869 propertiesToMatch.put(GraphPropertyEnum.VERSION, version);
1871 Map<GraphPropertyEnum, Object> propertiesNotToMatch = new EnumMap<>(GraphPropertyEnum.class);
1872 propertiesNotToMatch.put(GraphPropertyEnum.IS_DELETED, true);
1873 Either<List<GraphVertex>, JanusGraphOperationStatus> vertexEither = janusGraphDao
1874 .getByCriteria(null, propertiesToMatch, propertiesNotToMatch, JsonParseFlagEnum.ParseAll);
1875 if (vertexEither.isRight()) {
1876 return Either.right(DaoStatusConverter.convertJanusGraphStatusToStorageStatus(vertexEither.right().value()));
1879 List<GraphVertex> vertexList = vertexEither.isLeft() ? vertexEither.left().value() : null;
1880 if (vertexList == null || vertexList.isEmpty() || vertexList.size() > 1) {
1881 return Either.right(StorageOperationStatus.NOT_FOUND);
1884 return getToscaElementByOperation(vertexList.get(0));
1887 public Either<List<Component>, StorageOperationStatus> getComponentListByUuid(String componentUuid, Map<GraphPropertyEnum, Object> additionalPropertiesToMatch) {
1889 Map<GraphPropertyEnum, Object> propertiesToMatch = new EnumMap<>(GraphPropertyEnum.class);
1891 if (additionalPropertiesToMatch != null) {
1892 propertiesToMatch.putAll(additionalPropertiesToMatch);
1895 propertiesToMatch.put(GraphPropertyEnum.UUID, componentUuid);
1897 Map<GraphPropertyEnum, Object> propertiesNotToMatch = new EnumMap<>(GraphPropertyEnum.class);
1898 propertiesNotToMatch.put(GraphPropertyEnum.IS_DELETED, true);
1899 propertiesNotToMatch.put(GraphPropertyEnum.IS_ARCHIVED, true); //US382674, US382683
1901 Either<List<GraphVertex>, JanusGraphOperationStatus> vertexEither = janusGraphDao
1902 .getByCriteria(null, propertiesToMatch, propertiesNotToMatch, JsonParseFlagEnum.ParseAll);
1904 if (vertexEither.isRight()) {
1905 log.debug("Couldn't fetch metadata for component with uuid {}, error: {}", componentUuid, vertexEither.right().value());
1906 return Either.right(DaoStatusConverter.convertJanusGraphStatusToStorageStatus(vertexEither.right().value()));
1908 List<GraphVertex> vertexList = vertexEither.isLeft() ? vertexEither.left().value() : null;
1910 if (vertexList == null || vertexList.isEmpty()) {
1911 log.debug("Component with uuid {} was not found", componentUuid);
1912 return Either.right(StorageOperationStatus.NOT_FOUND);
1915 ArrayList<Component> latestComponents = new ArrayList<>();
1916 for (GraphVertex vertex : vertexList) {
1917 Either<Component, StorageOperationStatus> toscaElementByOperation = getToscaElementByOperation(vertex);
1919 if (toscaElementByOperation.isRight()) {
1920 log.debug("Could not fetch the following Component by UUID {}", vertex.getUniqueId());
1921 return Either.right(toscaElementByOperation.right().value());
1924 latestComponents.add(toscaElementByOperation.left().value());
1927 if (latestComponents.size() > 1) {
1928 for (Component component : latestComponents) {
1929 if (component.isHighestVersion()) {
1930 LinkedList<Component> highestComponent = new LinkedList<>();
1931 highestComponent.add(component);
1932 return Either.left(highestComponent);
1937 return Either.left(latestComponents);
1940 public Either<Component, StorageOperationStatus> getLatestServiceByUuid(String serviceUuid) {
1941 Map<GraphPropertyEnum, Object> propertiesToMatch = new EnumMap<>(GraphPropertyEnum.class);
1942 propertiesToMatch.put(GraphPropertyEnum.COMPONENT_TYPE, ComponentTypeEnum.SERVICE.name());
1943 return getLatestComponentByUuid(serviceUuid, propertiesToMatch);
1946 public Either<Component, StorageOperationStatus> getLatestComponentByUuid(String componentUuid) {
1947 return getLatestComponentByUuid(componentUuid, null);
1950 public Either<Component, StorageOperationStatus> getLatestComponentByUuid(String componentUuid, Map<GraphPropertyEnum, Object> propertiesToMatch) {
1952 Either<List<Component>, StorageOperationStatus> latestVersionListEither = getLatestComponentListByUuid(componentUuid, propertiesToMatch);
1954 if (latestVersionListEither.isRight()) {
1955 return Either.right(latestVersionListEither.right().value());
1958 List<Component> latestVersionList = latestVersionListEither.left().value();
1960 if (latestVersionList.isEmpty()) {
1961 return Either.right(StorageOperationStatus.NOT_FOUND);
1963 Component component = latestVersionList.size() == 1 ? latestVersionList.get(0) : latestVersionList.stream().max((c1, c2) -> Double.compare(Double.parseDouble(c1.getVersion()), Double.parseDouble(c2.getVersion()))).get();
1965 return Either.left(component);
1968 public Either<List<Resource>, StorageOperationStatus> getAllCertifiedResources(boolean isAbstract, Boolean isHighest) {
1970 List<Resource> resources = new ArrayList<>();
1971 Map<GraphPropertyEnum, Object> propertiesToMatch = new EnumMap<>(GraphPropertyEnum.class);
1972 Map<GraphPropertyEnum, Object> propertiesNotToMatch = new EnumMap<>(GraphPropertyEnum.class);
1974 propertiesToMatch.put(GraphPropertyEnum.IS_ABSTRACT, isAbstract);
1975 if (isHighest != null) {
1976 propertiesToMatch.put(GraphPropertyEnum.IS_HIGHEST_VERSION, isHighest);
1978 propertiesToMatch.put(GraphPropertyEnum.STATE, LifecycleStateEnum.CERTIFIED.name());
1979 propertiesToMatch.put(GraphPropertyEnum.COMPONENT_TYPE, ComponentTypeEnum.RESOURCE.name());
1980 propertiesNotToMatch.put(GraphPropertyEnum.IS_DELETED, true);
1982 Either<List<GraphVertex>, JanusGraphOperationStatus> getResourcesRes = janusGraphDao
1983 .getByCriteria(null, propertiesToMatch, propertiesNotToMatch, JsonParseFlagEnum.ParseAll);
1985 if (getResourcesRes.isRight()) {
1986 log.debug("Failed to fetch all certified resources. Status is {}", getResourcesRes.right().value());
1987 return Either.right(DaoStatusConverter.convertJanusGraphStatusToStorageStatus(getResourcesRes.right().value()));
1989 List<GraphVertex> resourceVerticies = getResourcesRes.left().value();
1990 for (GraphVertex resourceV : resourceVerticies) {
1991 Either<Resource, StorageOperationStatus> getResourceRes = getToscaElement(resourceV);
1992 if (getResourceRes.isRight()) {
1993 return Either.right(getResourceRes.right().value());
1995 resources.add(getResourceRes.left().value());
1997 return Either.left(resources);
2000 public <T extends Component> Either<T, StorageOperationStatus> getLatestByNameAndVersion(String name, String version, JsonParseFlagEnum parseFlag) {
2001 Either<T, StorageOperationStatus> result;
2003 Map<GraphPropertyEnum, Object> hasProperties = new EnumMap<>(GraphPropertyEnum.class);
2004 Map<GraphPropertyEnum, Object> hasNotProperties = new EnumMap<>(GraphPropertyEnum.class);
2006 hasProperties.put(GraphPropertyEnum.NAME, name);
2007 hasProperties.put(GraphPropertyEnum.VERSION, version);
2008 hasProperties.put(GraphPropertyEnum.IS_HIGHEST_VERSION, true);
2010 hasNotProperties.put(GraphPropertyEnum.IS_DELETED, true);
2012 Either<List<GraphVertex>, JanusGraphOperationStatus> getResourceRes = janusGraphDao
2013 .getByCriteria(null, hasProperties, hasNotProperties, parseFlag);
2014 if (getResourceRes.isRight()) {
2015 JanusGraphOperationStatus status = getResourceRes.right().value();
2016 log.debug("failed to find resource with name {}, version {}. Status is {} ", name, version, status);
2017 result = Either.right(DaoStatusConverter.convertJanusGraphStatusToStorageStatus(status));
2020 return getToscaElementByOperation(getResourceRes.left().value().get(0));
2023 public Either<Resource, StorageOperationStatus> getLatestComponentByCsarOrName(ComponentTypeEnum componentType, String csarUUID, String systemName) {
2024 return getLatestComponentByCsarOrName(componentType, csarUUID, systemName, JsonParseFlagEnum.ParseAll);
2027 public Either<Resource, StorageOperationStatus> getLatestComponentByCsarOrName(ComponentTypeEnum componentType, String csarUUID, String systemName, JsonParseFlagEnum parseFlag) {
2028 Map<GraphPropertyEnum, Object> props = new EnumMap<>(GraphPropertyEnum.class);
2029 Map<GraphPropertyEnum, Object> propsHasNot = new EnumMap<>(GraphPropertyEnum.class);
2030 props.put(GraphPropertyEnum.CSAR_UUID, csarUUID);
2031 props.put(GraphPropertyEnum.IS_HIGHEST_VERSION, true);
2032 if (componentType != null) {
2033 props.put(GraphPropertyEnum.COMPONENT_TYPE, componentType.name());
2035 propsHasNot.put(GraphPropertyEnum.IS_DELETED, true);
2037 GraphVertex resourceMetadataData = null;
2038 List<GraphVertex> resourceMetadataDataList = null;
2039 Either<List<GraphVertex>, JanusGraphOperationStatus> byCsar = janusGraphDao
2040 .getByCriteria(null, props, propsHasNot, JsonParseFlagEnum.ParseMetadata);
2041 if (byCsar.isRight()) {
2042 if (JanusGraphOperationStatus.NOT_FOUND == byCsar.right().value()) {
2043 // Fix Defect DE256036
2044 if (StringUtils.isEmpty(systemName)) {
2045 return Either.right(DaoStatusConverter.convertJanusGraphStatusToStorageStatus(
2046 JanusGraphOperationStatus.NOT_FOUND));
2050 props.put(GraphPropertyEnum.IS_HIGHEST_VERSION, true);
2051 props.put(GraphPropertyEnum.SYSTEM_NAME, systemName);
2052 Either<List<GraphVertex>, JanusGraphOperationStatus> bySystemname = janusGraphDao
2053 .getByCriteria(null, props, JsonParseFlagEnum.ParseMetadata);
2054 if (bySystemname.isRight()) {
2055 log.debug("getLatestResourceByCsarOrName - Failed to find by system name {} error {} ", systemName, bySystemname.right().value());
2056 return Either.right(DaoStatusConverter.convertJanusGraphStatusToStorageStatus(bySystemname.right().value()));
2058 if (bySystemname.left().value().size() > 2) {
2059 log.debug("getLatestResourceByCsarOrName - getByCriteria(by system name) must return only 2 latest version, but was returned - {}", bySystemname.left().value().size());
2060 return Either.right(StorageOperationStatus.GENERAL_ERROR);
2062 resourceMetadataDataList = bySystemname.left().value();
2063 if (resourceMetadataDataList.size() == 1) {
2064 resourceMetadataData = resourceMetadataDataList.get(0);
2066 for (GraphVertex curResource : resourceMetadataDataList) {
2067 if (!((String) curResource.getJsonMetadataField(JsonPresentationFields.LIFECYCLE_STATE)).equals("CERTIFIED")) {
2068 resourceMetadataData = curResource;
2073 if (resourceMetadataData == null) {
2074 log.debug("getLatestResourceByCsarOrName - getByCriteria(by system name) returned 2 latest CERTIFIED versions");
2075 return Either.right(StorageOperationStatus.GENERAL_ERROR);
2077 if (resourceMetadataData.getJsonMetadataField(JsonPresentationFields.CSAR_UUID) != null && !((String) resourceMetadataData.getJsonMetadataField(JsonPresentationFields.CSAR_UUID)).equals(csarUUID)) {
2078 log.debug("getLatestResourceByCsarOrName - same system name {} but different csarUUID. exist {} and new {} ", systemName, resourceMetadataData.getJsonMetadataField(JsonPresentationFields.CSAR_UUID), csarUUID);
2079 // correct error will be returned from create flow. with all
2080 // correct audit records!!!!!
2081 return Either.right(StorageOperationStatus.NOT_FOUND);
2083 return getToscaElement((String) resourceMetadataData.getUniqueId());
2086 resourceMetadataDataList = byCsar.left().value();
2087 if (resourceMetadataDataList.size() > 2) {
2088 log.debug("getLatestResourceByCsarOrName - getByCriteria(by csar) must return only 2 latest version, but was returned - {}", byCsar.left().value().size());
2089 return Either.right(StorageOperationStatus.GENERAL_ERROR);
2091 if (resourceMetadataDataList.size() == 1) {
2092 resourceMetadataData = resourceMetadataDataList.get(0);
2094 for (GraphVertex curResource : resourceMetadataDataList) {
2095 if (!((String) curResource.getJsonMetadataField(JsonPresentationFields.LIFECYCLE_STATE)).equals("CERTIFIED")) {
2096 resourceMetadataData = curResource;
2101 if (resourceMetadataData == null) {
2102 log.debug("getLatestResourceByCsarOrName - getByCriteria(by csar) returned 2 latest CERTIFIED versions");
2103 return Either.right(StorageOperationStatus.GENERAL_ERROR);
2105 return getToscaElement((String) resourceMetadataData.getJsonMetadataField(JsonPresentationFields.UNIQUE_ID), parseFlag);
2110 public Either<Boolean, StorageOperationStatus> validateToscaResourceNameExtends(String templateNameCurrent, String templateNameExtends) {
2112 String currentTemplateNameChecked = templateNameExtends;
2114 while (currentTemplateNameChecked != null && !currentTemplateNameChecked.equalsIgnoreCase(templateNameCurrent)) {
2115 Either<Resource, StorageOperationStatus> latestByToscaResourceName = getLatestByToscaResourceName(currentTemplateNameChecked);
2117 if (latestByToscaResourceName.isRight()) {
2118 return latestByToscaResourceName.right().value() == StorageOperationStatus.NOT_FOUND ? Either.left(false) : Either.right(latestByToscaResourceName.right().value());
2121 Resource value = latestByToscaResourceName.left().value();
2123 if (value.getDerivedFrom() != null) {
2124 currentTemplateNameChecked = value.getDerivedFrom().get(0);
2126 currentTemplateNameChecked = null;
2130 return (currentTemplateNameChecked != null && currentTemplateNameChecked.equalsIgnoreCase(templateNameCurrent)) ? Either.left(true) : Either.left(false);
2133 public Either<List<Component>, StorageOperationStatus> fetchMetaDataByResourceType(String resourceType, ComponentParametersView filterBy) {
2134 Map<GraphPropertyEnum, Object> props = new EnumMap<>(GraphPropertyEnum.class);
2135 props.put(GraphPropertyEnum.RESOURCE_TYPE, resourceType);
2136 props.put(GraphPropertyEnum.IS_HIGHEST_VERSION, true);
2137 Map<GraphPropertyEnum, Object> propsHasNotToMatch = new EnumMap<>(GraphPropertyEnum.class);
2138 propsHasNotToMatch.put(GraphPropertyEnum.IS_DELETED, true);
2139 Either<List<GraphVertex>, JanusGraphOperationStatus> resourcesByTypeEither = janusGraphDao
2140 .getByCriteria(null, props, propsHasNotToMatch, JsonParseFlagEnum.ParseMetadata);
2142 if (resourcesByTypeEither.isRight()) {
2143 return Either.right(DaoStatusConverter.convertJanusGraphStatusToStorageStatus(resourcesByTypeEither.right().value()));
2146 List<GraphVertex> vertexList = resourcesByTypeEither.left().value();
2147 List<Component> components = new ArrayList<>();
2149 for (GraphVertex vertex : vertexList) {
2150 components.add(getToscaElementByOperation(vertex, filterBy).left().value());
2153 return Either.left(components);
2156 public void commit() {
2157 janusGraphDao.commit();
2160 public Either<Service, StorageOperationStatus> updateDistributionStatus(Service service, User user, DistributionStatusEnum distributionStatus) {
2161 Either<GraphVertex, StorageOperationStatus> updateDistributionStatus = topologyTemplateOperation.updateDistributionStatus(service.getUniqueId(), user, distributionStatus);
2162 if (updateDistributionStatus.isRight()) {
2163 return Either.right(updateDistributionStatus.right().value());
2165 GraphVertex serviceV = updateDistributionStatus.left().value();
2166 service.setDistributionStatus(distributionStatus);
2167 service.setLastUpdateDate((Long) serviceV.getJsonMetadataField(JsonPresentationFields.LAST_UPDATE_DATE));
2168 return Either.left(service);
2171 public Either<ComponentMetadataData, StorageOperationStatus> updateComponentLastUpdateDateOnGraph(Component component) {
2173 Either<ComponentMetadataData, StorageOperationStatus> result = null;
2174 GraphVertex serviceVertex;
2175 Either<GraphVertex, JanusGraphOperationStatus> updateRes = null;
2176 Either<GraphVertex, JanusGraphOperationStatus> getRes = janusGraphDao
2177 .getVertexById(component.getUniqueId(), JsonParseFlagEnum.ParseMetadata);
2178 if (getRes.isRight()) {
2179 JanusGraphOperationStatus status = getRes.right().value();
2180 log.error("Failed to fetch component {}. status is {}", component.getUniqueId(), status);
2181 result = Either.right(DaoStatusConverter.convertJanusGraphStatusToStorageStatus(status));
2183 if (result == null) {
2184 serviceVertex = getRes.left().value();
2185 long lastUpdateDate = System.currentTimeMillis();
2186 serviceVertex.setJsonMetadataField(JsonPresentationFields.LAST_UPDATE_DATE, lastUpdateDate);
2187 component.setLastUpdateDate(lastUpdateDate);
2188 updateRes = janusGraphDao.updateVertex(serviceVertex);
2189 if (updateRes.isRight()) {
2190 result = Either.right(DaoStatusConverter.convertJanusGraphStatusToStorageStatus(updateRes.right().value()));
2193 if (result == null) {
2194 result = Either.left(ModelConverter.convertToComponentMetadata(updateRes.left().value()));
2199 public HealingJanusGraphDao getJanusGraphDao() {
2200 return janusGraphDao;
2203 public Either<List<Service>, StorageOperationStatus> getCertifiedServicesWithDistStatus(Set<DistributionStatusEnum> distStatus) {
2204 Map<GraphPropertyEnum, Object> propertiesToMatch = new EnumMap<>(GraphPropertyEnum.class);
2205 propertiesToMatch.put(GraphPropertyEnum.STATE, LifecycleStateEnum.CERTIFIED.name());
2207 return getServicesWithDistStatus(distStatus, propertiesToMatch);
2210 public Either<List<Service>, StorageOperationStatus> getServicesWithDistStatus(Set<DistributionStatusEnum> distStatus, Map<GraphPropertyEnum, Object> additionalPropertiesToMatch) {
2212 List<Service> servicesAll = new ArrayList<>();
2214 Map<GraphPropertyEnum, Object> propertiesToMatch = new EnumMap<>(GraphPropertyEnum.class);
2215 Map<GraphPropertyEnum, Object> propertiesNotToMatch = new EnumMap<>(GraphPropertyEnum.class);
2217 if (additionalPropertiesToMatch != null && !additionalPropertiesToMatch.isEmpty()) {
2218 propertiesToMatch.putAll(additionalPropertiesToMatch);
2221 propertiesToMatch.put(GraphPropertyEnum.COMPONENT_TYPE, ComponentTypeEnum.SERVICE.name());
2223 propertiesNotToMatch.put(GraphPropertyEnum.IS_DELETED, true);
2225 if (distStatus != null && !distStatus.isEmpty()) {
2226 for (DistributionStatusEnum state : distStatus) {
2227 propertiesToMatch.put(GraphPropertyEnum.DISTRIBUTION_STATUS, state.name());
2228 Either<List<Service>, StorageOperationStatus> fetchServicesByCriteria = fetchServicesByCriteria(servicesAll, propertiesToMatch, propertiesNotToMatch);
2229 if (fetchServicesByCriteria.isRight()) {
2230 return fetchServicesByCriteria;
2232 servicesAll = fetchServicesByCriteria.left().value();
2235 return Either.left(servicesAll);
2237 return fetchServicesByCriteria(servicesAll, propertiesToMatch, propertiesNotToMatch);
2241 private Either<List<Service>, StorageOperationStatus> fetchServicesByCriteria(List<Service> servicesAll, Map<GraphPropertyEnum, Object> propertiesToMatch, Map<GraphPropertyEnum, Object> propertiesNotToMatch) {
2242 Either<List<GraphVertex>, JanusGraphOperationStatus> getRes = janusGraphDao
2243 .getByCriteria(VertexTypeEnum.TOPOLOGY_TEMPLATE, propertiesToMatch, propertiesNotToMatch, JsonParseFlagEnum.ParseAll);
2244 if (getRes.isRight()) {
2245 if (getRes.right().value() != JanusGraphOperationStatus.NOT_FOUND) {
2246 CommonUtility.addRecordToLog(log, LogLevelEnum.DEBUG, "Failed to fetch certified services by match properties {} not match properties {} . Status is {}. ", propertiesToMatch, propertiesNotToMatch, getRes.right().value());
2247 return Either.right(DaoStatusConverter.convertJanusGraphStatusToStorageStatus(getRes.right().value()));
2250 for (GraphVertex vertex : getRes.left().value()) {
2251 Either<ToscaElement, StorageOperationStatus> getServiceRes = topologyTemplateOperation.getLightComponent(vertex, ComponentTypeEnum.SERVICE, new ComponentParametersView(true));
2253 if (getServiceRes.isRight()) {
2254 CommonUtility.addRecordToLog(log, LogLevelEnum.DEBUG, "Failed to fetch certified service {}. Status is {}. ", vertex.getJsonMetadataField(JsonPresentationFields.NAME), getServiceRes.right().value());
2255 return Either.right(getServiceRes.right().value());
2257 servicesAll.add(ModelConverter.convertFromToscaElement(getServiceRes.left().value()));
2261 return Either.left(servicesAll);
2264 public void rollback() {
2265 janusGraphDao.rollback();
2268 public StorageOperationStatus addDeploymentArtifactsToInstance(String componentId, ComponentInstance componentInstance, Map<String, ArtifactDefinition> finalDeploymentArtifacts) {
2269 Map<String, ArtifactDataDefinition> instDeplArtifacts = finalDeploymentArtifacts.entrySet().stream().collect(Collectors.toMap(Map.Entry::getKey, e -> new ArtifactDataDefinition(e.getValue())));
2271 return nodeTemplateOperation.addDeploymentArtifactsToInstance(componentId, componentInstance.getUniqueId(), instDeplArtifacts);
2274 public StorageOperationStatus addInformationalArtifactsToInstance(String componentId, ComponentInstance componentInstance, Map<String, ArtifactDefinition> artifacts) {
2275 StorageOperationStatus status = StorageOperationStatus.OK;
2276 if (MapUtils.isNotEmpty(artifacts)) {
2277 Map<String, ArtifactDataDefinition> instDeplArtifacts = artifacts.entrySet().stream().collect(Collectors.toMap(Map.Entry::getKey, e -> new ArtifactDataDefinition(e.getValue())));
2278 status = nodeTemplateOperation.addInformationalArtifactsToInstance(componentId, componentInstance.getUniqueId(), instDeplArtifacts);
2283 public StorageOperationStatus generateCustomizationUUIDOnInstance(String componentId, String instanceId) {
2284 return nodeTemplateOperation.generateCustomizationUUIDOnInstance(componentId, instanceId);
2287 public StorageOperationStatus generateCustomizationUUIDOnInstanceGroup(String componentId, String instanceId, List<String> groupInstances) {
2288 return nodeTemplateOperation.generateCustomizationUUIDOnInstanceGroup(componentId, instanceId, groupInstances);
2291 public Either<PropertyDefinition, StorageOperationStatus> addPropertyToComponent(String propertyName,
2292 PropertyDefinition newPropertyDefinition,
2293 Component component) {
2294 newPropertyDefinition.setName(propertyName);
2296 StorageOperationStatus status = getToscaElementOperation(component)
2297 .addToscaDataToToscaElement(component.getUniqueId(), EdgeLabelEnum.PROPERTIES, VertexTypeEnum.PROPERTIES, newPropertyDefinition, JsonPresentationFields.NAME);
2298 if (status != StorageOperationStatus.OK) {
2299 CommonUtility.addRecordToLog(log, LogLevelEnum.DEBUG, "Failed to add the property {} to the component {}. Status is {}. ", propertyName, component.getName(), status);
2300 return Either.right(status);
2303 ComponentParametersView filter = new ComponentParametersView(true);
2304 filter.setIgnoreProperties(false);
2305 filter.setIgnoreInputs(false);
2306 Either<Component, StorageOperationStatus> getUpdatedComponentRes = getToscaElement(component.getUniqueId(), filter);
2307 if (getUpdatedComponentRes.isRight()) {
2308 CommonUtility.addRecordToLog(log, LogLevelEnum.DEBUG, "Failed to get updated component {}. Status is {}. ", component.getUniqueId(), getUpdatedComponentRes.right().value());
2309 return Either.right(status);
2312 PropertyDefinition newProperty = null;
2313 List<PropertyDefinition> properties =
2314 (getUpdatedComponentRes.left().value()).getProperties();
2315 if (CollectionUtils.isNotEmpty(properties)) {
2316 Optional<PropertyDefinition> propertyOptional = properties.stream().filter(
2317 propertyEntry -> propertyEntry.getName().equals(propertyName)).findAny();
2318 if (propertyOptional.isPresent()) {
2319 newProperty = propertyOptional.get();
2322 if (newProperty == null) {
2323 CommonUtility.addRecordToLog(log, LogLevelEnum.DEBUG, "Failed to find recently added property {} on the component {}. Status is {}. ", propertyName, component.getUniqueId(), StorageOperationStatus.NOT_FOUND);
2324 return Either.right(StorageOperationStatus.NOT_FOUND);
2327 return Either.left(newProperty);
2330 public StorageOperationStatus deletePropertyOfComponent(Component component, String propertyName) {
2331 return getToscaElementOperation(component).deleteToscaDataElement(component.getUniqueId(), EdgeLabelEnum.PROPERTIES, VertexTypeEnum.PROPERTIES, propertyName, JsonPresentationFields.NAME);
2334 public StorageOperationStatus deleteAttributeOfResource(Component component, String attributeName) {
2335 return getToscaElementOperation(component).deleteToscaDataElement(component.getUniqueId(), EdgeLabelEnum.ATTRIBUTES, VertexTypeEnum.ATTRIBUTES, attributeName, JsonPresentationFields.NAME);
2338 public StorageOperationStatus deleteInputOfResource(Component resource, String inputName) {
2339 return getToscaElementOperation(resource).deleteToscaDataElement(resource.getUniqueId(), EdgeLabelEnum.INPUTS, VertexTypeEnum.INPUTS, inputName, JsonPresentationFields.NAME);
2343 * Deletes a data type from a component.
2344 * @param component the container which has the data type
2345 * @param dataTypeName the data type name to be deleted
2346 * @return Operation result.
2348 public StorageOperationStatus deleteDataTypeOfComponent(Component component, String dataTypeName) {
2349 return getToscaElementOperation(component).deleteToscaDataElement(component.getUniqueId(), EdgeLabelEnum.DATA_TYPES, VertexTypeEnum.DATA_TYPES, dataTypeName, JsonPresentationFields.NAME);
2352 public Either<PropertyDefinition, StorageOperationStatus> updatePropertyOfComponent(Component component,
2353 PropertyDefinition newPropertyDefinition) {
2355 Either<Component, StorageOperationStatus> getUpdatedComponentRes = null;
2356 Either<PropertyDefinition, StorageOperationStatus> result = null;
2357 StorageOperationStatus status = getToscaElementOperation(component).updateToscaDataOfToscaElement(component.getUniqueId(), EdgeLabelEnum.PROPERTIES, VertexTypeEnum.PROPERTIES, newPropertyDefinition, JsonPresentationFields.NAME);
2358 if (status != StorageOperationStatus.OK) {
2359 CommonUtility.addRecordToLog(log, LogLevelEnum.DEBUG, "Failed to add the property {} to the resource {}. Status is {}. ", newPropertyDefinition.getName(), component.getName(), status);
2360 result = Either.right(status);
2362 if (result == null) {
2363 ComponentParametersView filter = new ComponentParametersView(true);
2364 filter.setIgnoreProperties(false);
2365 getUpdatedComponentRes = getToscaElement(component.getUniqueId(), filter);
2366 if (getUpdatedComponentRes.isRight()) {
2367 CommonUtility.addRecordToLog(log, LogLevelEnum.DEBUG, "Failed to get updated resource {}. Status is {}. ", component.getUniqueId(), getUpdatedComponentRes.right().value());
2368 result = Either.right(status);
2371 if (result == null) {
2372 Optional<PropertyDefinition> newProperty = (getUpdatedComponentRes.left().value())
2373 .getProperties().stream().filter(p -> p.getName().equals(newPropertyDefinition.getName())).findAny();
2374 if (newProperty.isPresent()) {
2375 result = Either.left(newProperty.get());
2377 CommonUtility.addRecordToLog(log, LogLevelEnum.DEBUG, "Failed to find recently added property {} on the resource {}. Status is {}. ", newPropertyDefinition.getName(), component.getUniqueId(), StorageOperationStatus.NOT_FOUND);
2378 result = Either.right(StorageOperationStatus.NOT_FOUND);
2385 public Either<AttributeDataDefinition, StorageOperationStatus> addAttributeOfResource(Component component, AttributeDataDefinition newAttributeDef) {
2387 Either<Component, StorageOperationStatus> getUpdatedComponentRes = null;
2388 Either<AttributeDataDefinition, StorageOperationStatus> result = null;
2389 if (newAttributeDef.getUniqueId() == null || newAttributeDef.getUniqueId().isEmpty()) {
2390 String attUniqueId = UniqueIdBuilder.buildAttributeUid(component.getUniqueId(), newAttributeDef.getName());
2391 newAttributeDef.setUniqueId(attUniqueId);
2394 StorageOperationStatus status = getToscaElementOperation(component).addToscaDataToToscaElement(component.getUniqueId(), EdgeLabelEnum.ATTRIBUTES, VertexTypeEnum.ATTRIBUTES, newAttributeDef, JsonPresentationFields.NAME);
2395 if (status != StorageOperationStatus.OK) {
2396 CommonUtility.addRecordToLog(log, LogLevelEnum.DEBUG, FAILED_TO_ADD_THE_PROPERTY_TO_THE_RESOURCE_STATUS_IS, newAttributeDef.getName(), component.getName(), status);
2397 result = Either.right(status);
2399 if (result == null) {
2400 ComponentParametersView filter = new ComponentParametersView(true);
2401 filter.setIgnoreAttributesFrom(false);
2402 getUpdatedComponentRes = getToscaElement(component.getUniqueId(), filter);
2403 if (getUpdatedComponentRes.isRight()) {
2404 CommonUtility.addRecordToLog(log, LogLevelEnum.DEBUG, FAILED_TO_GET_UPDATED_RESOURCE_STATUS_IS, component.getUniqueId(), getUpdatedComponentRes.right().value());
2405 result = Either.right(status);
2408 if (result == null) {
2409 Optional<AttributeDataDefinition> newAttribute = ((Resource) getUpdatedComponentRes.left().value()).getAttributes().stream().filter(p -> p.getName().equals(newAttributeDef.getName())).findAny();
2410 if (newAttribute.isPresent()) {
2411 result = Either.left(newAttribute.get());
2413 CommonUtility.addRecordToLog(log, LogLevelEnum.DEBUG, FAILED_TO_FIND_RECENTLY_ADDED_PROPERTY_ON_THE_RESOURCE_STATUS_IS, newAttributeDef.getName(), component.getUniqueId(), StorageOperationStatus.NOT_FOUND);
2414 result = Either.right(StorageOperationStatus.NOT_FOUND);
2420 public Either<AttributeDataDefinition, StorageOperationStatus> updateAttributeOfResource(Component component, AttributeDataDefinition newAttributeDef) {
2422 Either<Component, StorageOperationStatus> getUpdatedComponentRes = null;
2423 Either<AttributeDataDefinition, StorageOperationStatus> result = null;
2424 StorageOperationStatus status = getToscaElementOperation(component).updateToscaDataOfToscaElement(component.getUniqueId(), EdgeLabelEnum.ATTRIBUTES, VertexTypeEnum.ATTRIBUTES, newAttributeDef, JsonPresentationFields.NAME);
2425 if (status != StorageOperationStatus.OK) {
2426 CommonUtility.addRecordToLog(log, LogLevelEnum.DEBUG, FAILED_TO_ADD_THE_PROPERTY_TO_THE_RESOURCE_STATUS_IS, newAttributeDef.getName(), component.getName(), status);
2427 result = Either.right(status);
2429 if (result == null) {
2430 ComponentParametersView filter = new ComponentParametersView(true);
2431 filter.setIgnoreAttributesFrom(false);
2432 getUpdatedComponentRes = getToscaElement(component.getUniqueId(), filter);
2433 if (getUpdatedComponentRes.isRight()) {
2434 CommonUtility.addRecordToLog(log, LogLevelEnum.DEBUG, FAILED_TO_GET_UPDATED_RESOURCE_STATUS_IS, component.getUniqueId(), getUpdatedComponentRes.right().value());
2435 result = Either.right(status);
2438 if (result == null) {
2439 Optional<AttributeDataDefinition> newProperty = ((Resource) getUpdatedComponentRes.left().value()).getAttributes().stream().filter(p -> p.getName().equals(newAttributeDef.getName())).findAny();
2440 if (newProperty.isPresent()) {
2441 result = Either.left(newProperty.get());
2443 CommonUtility.addRecordToLog(log, LogLevelEnum.DEBUG, FAILED_TO_FIND_RECENTLY_ADDED_PROPERTY_ON_THE_RESOURCE_STATUS_IS, newAttributeDef.getName(), component.getUniqueId(), StorageOperationStatus.NOT_FOUND);
2444 result = Either.right(StorageOperationStatus.NOT_FOUND);
2450 public Either<InputDefinition, StorageOperationStatus> updateInputOfComponent(Component component, InputDefinition newInputDefinition) {
2452 Either<Component, StorageOperationStatus> getUpdatedComponentRes = null;
2453 Either<InputDefinition, StorageOperationStatus> result = null;
2454 StorageOperationStatus status = getToscaElementOperation(component).updateToscaDataOfToscaElement(component.getUniqueId(), EdgeLabelEnum.INPUTS, VertexTypeEnum.INPUTS, newInputDefinition, JsonPresentationFields.NAME);
2455 if (status != StorageOperationStatus.OK) {
2456 CommonUtility.addRecordToLog(log, LogLevelEnum.DEBUG, "Failed to update the input {} to the component {}. Status is {}. ", newInputDefinition.getName(), component.getName(), status);
2457 result = Either.right(status);
2459 if (result == null) {
2460 ComponentParametersView filter = new ComponentParametersView(true);
2461 filter.setIgnoreInputs(false);
2462 getUpdatedComponentRes = getToscaElement(component.getUniqueId(), filter);
2463 if (getUpdatedComponentRes.isRight()) {
2464 CommonUtility.addRecordToLog(log, LogLevelEnum.DEBUG, FAILED_TO_GET_UPDATED_RESOURCE_STATUS_IS, component.getUniqueId(), getUpdatedComponentRes.right().value());
2465 result = Either.right(status);
2468 if (result == null) {
2469 Optional<InputDefinition> updatedInput = getUpdatedComponentRes.left().value().getInputs().stream().filter(p -> p.getName().equals(newInputDefinition.getName())).findAny();
2470 if (updatedInput.isPresent()) {
2471 result = Either.left(updatedInput.get());
2473 CommonUtility.addRecordToLog(log, LogLevelEnum.DEBUG, "Failed to find recently updated inputs {} on the resource {}. Status is {}. ", newInputDefinition.getName(), component.getUniqueId(), StorageOperationStatus.NOT_FOUND);
2474 result = Either.right(StorageOperationStatus.NOT_FOUND);
2481 * method - ename the group instances after referenced container name renamed flow - VF rename -(triggers)-> Group rename
2483 * @param containerComponent - container such as service
2484 * @param componentInstance - context component
2485 * @param componentInstanceId - id
2486 * @return - successfull/failed status
2488 public Either<StorageOperationStatus, StorageOperationStatus> cleanAndAddGroupInstancesToComponentInstance(Component containerComponent, ComponentInstance componentInstance, String componentInstanceId) {
2489 String uniqueId = componentInstance.getUniqueId();
2490 StorageOperationStatus status = nodeTemplateOperation.deleteToscaDataDeepElementsBlockOfToscaElement(containerComponent.getUniqueId(), EdgeLabelEnum.INST_GROUPS, VertexTypeEnum.INST_GROUPS, uniqueId);
2491 if (status != StorageOperationStatus.OK && status != StorageOperationStatus.NOT_FOUND) {
2492 CommonUtility.addRecordToLog(log, LogLevelEnum.DEBUG, "Failed to delete group instances for container {}. error {] ", componentInstanceId, status);
2493 return Either.right(status);
2495 if (componentInstance.getGroupInstances() != null) {
2496 status = addGroupInstancesToComponentInstance(containerComponent, componentInstance, componentInstance.getGroupInstances());
2497 if (status != StorageOperationStatus.OK && status != StorageOperationStatus.NOT_FOUND) {
2498 CommonUtility.addRecordToLog(log, LogLevelEnum.DEBUG, "Failed to add group instances for container {}. error {] ", componentInstanceId, status);
2499 return Either.right(status);
2502 return Either.left(status);
2505 public StorageOperationStatus addGroupInstancesToComponentInstance(Component containerComponent, ComponentInstance componentInstance, List<GroupDefinition> groups, Map<String, List<ArtifactDefinition>> groupInstancesArtifacts) {
2506 return nodeTemplateOperation.addGroupInstancesToComponentInstance(containerComponent, componentInstance, groups, groupInstancesArtifacts);
2509 public Either<List<GroupDefinition>, StorageOperationStatus> updateGroupsOnComponent(Component component, List<GroupDataDefinition> updatedGroups) {
2510 return groupsOperation.updateGroups(component, updatedGroups, PromoteVersionEnum.MINOR);
2513 public Either<List<GroupInstance>, StorageOperationStatus> updateGroupInstancesOnComponent(Component component, String instanceId, List<GroupInstance> updatedGroupInstances) {
2514 return groupsOperation.updateGroupInstances(component, instanceId, updatedGroupInstances);
2517 public StorageOperationStatus addGroupInstancesToComponentInstance(Component containerComponent, ComponentInstance componentInstance, List<GroupInstance> groupInstances) {
2518 return nodeTemplateOperation.addGroupInstancesToComponentInstance(containerComponent, componentInstance, groupInstances);
2521 public StorageOperationStatus addDeploymentArtifactsToComponentInstance(Component containerComponent, ComponentInstance componentInstance, Map<String, ArtifactDefinition> deploymentArtifacts) {
2522 return nodeTemplateOperation.addDeploymentArtifactsToComponentInstance(containerComponent, componentInstance, deploymentArtifacts);
2525 public StorageOperationStatus updateComponentInstanceProperty(Component containerComponent, String componentInstanceId, ComponentInstanceProperty property) {
2526 return nodeTemplateOperation.updateComponentInstanceProperty(containerComponent, componentInstanceId, property);
2529 public StorageOperationStatus updateComponentInstanceProperties(Component containerComponent, String componentInstanceId, List<ComponentInstanceProperty> properties) {
2530 return nodeTemplateOperation.updateComponentInstanceProperties(containerComponent, componentInstanceId, properties);
2534 public StorageOperationStatus addComponentInstanceProperty(Component containerComponent, String componentInstanceId, ComponentInstanceProperty property) {
2535 return nodeTemplateOperation.addComponentInstanceProperty(containerComponent, componentInstanceId, property);
2538 public StorageOperationStatus updateComponentInstanceAttribute(Component containerComponent, String componentInstanceId, ComponentInstanceAttribute property){
2539 return nodeTemplateOperation.updateComponentInstanceAttribute(containerComponent, componentInstanceId, property);
2542 public StorageOperationStatus addComponentInstanceAttribute(Component containerComponent, String componentInstanceId, ComponentInstanceAttribute attribute){
2543 return nodeTemplateOperation.addComponentInstanceAttribute(containerComponent, componentInstanceId, attribute);
2546 public StorageOperationStatus updateComponentInstanceInput(Component containerComponent, String componentInstanceId, ComponentInstanceInput property) {
2547 return nodeTemplateOperation.updateComponentInstanceInput(containerComponent, componentInstanceId, property);
2550 public StorageOperationStatus updateComponentInstanceInputs(Component containerComponent, String componentInstanceId, List<ComponentInstanceInput> instanceInputs) {
2551 return nodeTemplateOperation.updateComponentInstanceInputs(containerComponent, componentInstanceId, instanceInputs);
2554 public StorageOperationStatus addComponentInstanceInput(Component containerComponent, String componentInstanceId, ComponentInstanceInput property) {
2555 return nodeTemplateOperation.addComponentInstanceInput(containerComponent, componentInstanceId, property);
2558 public void setNodeTypeOperation(NodeTypeOperation nodeTypeOperation) {
2559 this.nodeTypeOperation = nodeTypeOperation;
2562 public void setTopologyTemplateOperation(TopologyTemplateOperation topologyTemplateOperation) {
2563 this.topologyTemplateOperation = topologyTemplateOperation;
2566 public StorageOperationStatus deleteComponentInstanceInputsFromTopologyTemplate(Component containerComponent, List<InputDefinition> inputsToDelete) {
2567 return topologyTemplateOperation.deleteToscaDataElements(containerComponent.getUniqueId(), EdgeLabelEnum.INPUTS, inputsToDelete.stream().map(PropertyDataDefinition::getName).collect(Collectors.toList()));
2570 public StorageOperationStatus updateComponentInstanceCapabiltyProperty(Component containerComponent, String componentInstanceUniqueId, String capabilityPropertyKey, ComponentInstanceProperty property) {
2571 return nodeTemplateOperation.updateComponentInstanceCapabilityProperty(containerComponent, componentInstanceUniqueId, capabilityPropertyKey, property);
2574 public StorageOperationStatus updateComponentInstanceCapabilityProperties(Component containerComponent, String componentInstanceUniqueId) {
2575 return convertComponentInstanceProperties(containerComponent, componentInstanceUniqueId)
2576 .map(instanceCapProps -> topologyTemplateOperation.updateComponentInstanceCapabilityProperties(containerComponent, componentInstanceUniqueId, instanceCapProps))
2577 .orElse(StorageOperationStatus.NOT_FOUND);
2580 public StorageOperationStatus updateComponentInstanceInterfaces(Component containerComponent, String componentInstanceUniqueId) {
2581 MapInterfaceDataDefinition mapInterfaceDataDefinition =
2582 convertComponentInstanceInterfaces(containerComponent, componentInstanceUniqueId);
2583 return topologyTemplateOperation
2584 .updateComponentInstanceInterfaces(containerComponent, componentInstanceUniqueId, mapInterfaceDataDefinition);
2587 public StorageOperationStatus updateComponentCalculatedCapabilitiesProperties(Component containerComponent) {
2588 Map<String, MapCapabilityProperty> mapCapabiltyPropertyMap =
2589 convertComponentCapabilitiesProperties(containerComponent);
2590 return nodeTemplateOperation.overrideComponentCapabilitiesProperties(containerComponent, mapCapabiltyPropertyMap);
2593 public StorageOperationStatus deleteAllCalculatedCapabilitiesRequirements(String topologyTemplateId) {
2594 StorageOperationStatus status = topologyTemplateOperation.removeToscaData(topologyTemplateId, EdgeLabelEnum.CALCULATED_CAPABILITIES, VertexTypeEnum.CALCULATED_CAPABILITIES);
2595 if (status == StorageOperationStatus.OK) {
2596 status = topologyTemplateOperation.removeToscaData(topologyTemplateId, EdgeLabelEnum.CALCULATED_REQUIREMENTS, VertexTypeEnum.CALCULATED_REQUIREMENTS);
2598 if (status == StorageOperationStatus.OK) {
2599 status = topologyTemplateOperation.removeToscaData(topologyTemplateId, EdgeLabelEnum.CALCULATED_CAP_PROPERTIES, VertexTypeEnum.CALCULATED_CAP_PROPERTIES);
2604 public Either<Component, StorageOperationStatus> shouldUpgradeToLatestDerived(Resource clonedResource) {
2605 String componentId = clonedResource.getUniqueId();
2606 Either<GraphVertex, JanusGraphOperationStatus> getVertexEither = janusGraphDao
2607 .getVertexById(componentId, JsonParseFlagEnum.NoParse);
2608 if (getVertexEither.isRight()) {
2609 log.debug(COULDNT_FETCH_COMPONENT_WITH_AND_UNIQUE_ID_ERROR, componentId, getVertexEither.right().value());
2610 return Either.right(DaoStatusConverter.convertJanusGraphStatusToStorageStatus(getVertexEither.right().value()));
2613 GraphVertex nodeTypeV = getVertexEither.left().value();
2615 ToscaElement toscaElementToUpdate = ModelConverter.convertToToscaElement(clonedResource);
2617 Either<ToscaElement, StorageOperationStatus> shouldUpdateDerivedVersion = nodeTypeOperation.shouldUpdateDerivedVersion(toscaElementToUpdate, nodeTypeV);
2618 if (shouldUpdateDerivedVersion.isRight() && StorageOperationStatus.OK != shouldUpdateDerivedVersion.right().value()) {
2619 log.debug("Failed to update derived version for node type {} derived {}, error: {}", componentId, clonedResource.getDerivedFrom().get(0), shouldUpdateDerivedVersion.right().value());
2620 return Either.right(shouldUpdateDerivedVersion.right().value());
2622 if (shouldUpdateDerivedVersion.isLeft()) {
2623 return Either.left(ModelConverter.convertFromToscaElement(shouldUpdateDerivedVersion.left().value()));
2625 return Either.left(clonedResource);
2629 * Returns list of ComponentInstanceProperty belonging to component instance capability specified by name, type and ownerId
2631 public Either<List<ComponentInstanceProperty>, StorageOperationStatus> getComponentInstanceCapabilityProperties(String componentId, String instanceId, String capabilityName, String capabilityType, String ownerId) {
2632 return topologyTemplateOperation.getComponentInstanceCapabilityProperties(componentId, instanceId, capabilityName, capabilityType, ownerId);
2635 private MapInterfaceDataDefinition convertComponentInstanceInterfaces(Component currComponent,
2636 String componentInstanceId) {
2637 MapInterfaceDataDefinition mapInterfaceDataDefinition = new MapInterfaceDataDefinition();
2638 List<ComponentInstanceInterface> componentInterface = currComponent.getComponentInstancesInterfaces().get(componentInstanceId);
2640 if(CollectionUtils.isNotEmpty(componentInterface)) {
2641 componentInterface.stream().forEach(interfaceDef -> mapInterfaceDataDefinition.put
2642 (interfaceDef.getUniqueId(), interfaceDef));
2645 return mapInterfaceDataDefinition;
2648 private Map<String, MapCapabilityProperty> convertComponentCapabilitiesProperties(Component currComponent) {
2649 Map<String, MapCapabilityProperty> map = ModelConverter.extractCapabilityPropertiesFromGroups(currComponent.getGroups(), true);
2650 map.putAll(ModelConverter.extractCapabilityProperteisFromInstances(currComponent.getComponentInstances(), true));
2654 private Optional<MapCapabilityProperty> convertComponentInstanceProperties(Component component, String instanceId) {
2655 return component.fetchInstanceById(instanceId)
2656 .map(ci -> ModelConverter.convertToMapOfMapCapabilityProperties(ci.getCapabilities(), instanceId, ci.getOriginType().isAtomicType()));
2659 public Either<PolicyDefinition, StorageOperationStatus> associatePolicyToComponent(String componentId, PolicyDefinition policyDefinition, int counter) {
2660 Either<PolicyDefinition, StorageOperationStatus> result = null;
2661 Either<GraphVertex, JanusGraphOperationStatus> getVertexEither;
2662 getVertexEither = janusGraphDao.getVertexById(componentId, JsonParseFlagEnum.ParseMetadata);
2663 if (getVertexEither.isRight()) {
2664 log.error(COULDNT_FETCH_A_COMPONENT_WITH_AND_UNIQUE_ID_ERROR, componentId, getVertexEither.right().value());
2665 result = Either.right(DaoStatusConverter.convertJanusGraphStatusToStorageStatus(getVertexEither.right().value()));
2667 if (getVertexEither.left().value().getLabel() != VertexTypeEnum.TOPOLOGY_TEMPLATE) {
2668 log.error("Policy association to component of Tosca type {} is not allowed. ", getVertexEither.left().value().getLabel());
2669 result = Either.right(StorageOperationStatus.BAD_REQUEST);
2672 if (result == null) {
2673 StorageOperationStatus status = topologyTemplateOperation.addPolicyToToscaElement(getVertexEither.left().value(), policyDefinition, counter);
2674 if (status != StorageOperationStatus.OK) {
2675 return Either.right(status);
2678 if (result == null) {
2679 result = Either.left(policyDefinition);
2684 public StorageOperationStatus associatePoliciesToComponent(String componentId, List<PolicyDefinition> policies) {
2685 log.debug("#associatePoliciesToComponent - associating policies for component {}.", componentId);
2686 return janusGraphDao.getVertexById(componentId, JsonParseFlagEnum.ParseMetadata)
2687 .either(containerVertex -> topologyTemplateOperation.addPoliciesToToscaElement(containerVertex, policies),
2688 DaoStatusConverter::convertJanusGraphStatusToStorageStatus);
2691 public Either<PolicyDefinition, StorageOperationStatus> updatePolicyOfComponent(String componentId, PolicyDefinition policyDefinition, PromoteVersionEnum promoteVersionEnum) {
2692 Either<PolicyDefinition, StorageOperationStatus> result = null;
2693 Either<GraphVertex, JanusGraphOperationStatus> getVertexEither;
2694 getVertexEither = janusGraphDao.getVertexById(componentId, JsonParseFlagEnum.NoParse);
2695 if (getVertexEither.isRight()) {
2696 log.error(COULDNT_FETCH_A_COMPONENT_WITH_AND_UNIQUE_ID_ERROR, componentId, getVertexEither.right().value());
2697 result = Either.right(DaoStatusConverter.convertJanusGraphStatusToStorageStatus(getVertexEither.right().value()));
2699 if (result == null) {
2700 policyDefinition.setVersion(GroupUtils.updateVersion(promoteVersionEnum, policyDefinition.getVersion()));
2701 StorageOperationStatus status = topologyTemplateOperation.updatePolicyOfToscaElement(getVertexEither.left().value(), policyDefinition);
2702 if (status != StorageOperationStatus.OK) {
2703 return Either.right(status);
2706 if (result == null) {
2707 result = Either.left(policyDefinition);
2712 public StorageOperationStatus updatePoliciesOfComponent(String componentId, List<PolicyDefinition> policyDefinition) {
2713 log.debug("#updatePoliciesOfComponent - updating policies for component {}", componentId);
2714 return janusGraphDao.getVertexById(componentId, JsonParseFlagEnum.NoParse)
2716 .map(DaoStatusConverter::convertJanusGraphStatusToStorageStatus)
2717 .either(containerVertex -> topologyTemplateOperation.updatePoliciesOfToscaElement(containerVertex, policyDefinition),
2721 public StorageOperationStatus removePolicyFromComponent(String componentId, String policyId) {
2722 StorageOperationStatus status = null;
2723 Either<GraphVertex, JanusGraphOperationStatus> getVertexEither = janusGraphDao
2724 .getVertexById(componentId, JsonParseFlagEnum.NoParse);
2725 if (getVertexEither.isRight()) {
2726 log.error(COULDNT_FETCH_A_COMPONENT_WITH_AND_UNIQUE_ID_ERROR, componentId, getVertexEither.right().value());
2727 status = DaoStatusConverter.convertJanusGraphStatusToStorageStatus(getVertexEither.right().value());
2729 if (status == null) {
2730 status = topologyTemplateOperation.removePolicyFromToscaElement(getVertexEither.left().value(), policyId);
2735 public boolean canAddGroups(String componentId) {
2736 GraphVertex vertex = janusGraphDao.getVertexById(componentId)
2738 .on(this::onJanusGraphError);
2739 return topologyTemplateOperation.hasEdgeOfType(vertex, EdgeLabelEnum.GROUPS);
2742 GraphVertex onJanusGraphError(JanusGraphOperationStatus toe) {
2743 throw new StorageException(
2744 DaoStatusConverter.convertJanusGraphStatusToStorageStatus(toe));
2747 public CatalogUpdateTimestamp updateCatalogTimes() {
2748 long now = System.currentTimeMillis();
2750 GraphVertex catalogRoot = janusGraphDao.getVertexByLabel(VertexTypeEnum.CATALOG_ROOT)
2752 .on(this::onJanusGraphError);
2754 Long currentTime = (Long) catalogRoot.getMetadataProperty(GraphPropertyEnum.CURRENT_CATALOG_UPDATE_TIME);
2755 catalogRoot.addMetadataProperty(GraphPropertyEnum.PREV_CATALOG_UPDATE_TIME, currentTime);
2756 catalogRoot.addMetadataProperty(GraphPropertyEnum.CURRENT_CATALOG_UPDATE_TIME, now);
2758 janusGraphDao.updateVertex(catalogRoot).left().on(this::onJanusGraphError);
2760 return new CatalogUpdateTimestamp(currentTime, now);
2763 public CatalogUpdateTimestamp getCatalogTimes() {
2766 GraphVertex catalogRoot = janusGraphDao.getVertexByLabel(VertexTypeEnum.CATALOG_ROOT)
2768 .on(this::onJanusGraphError);
2770 Long currentTime = (Long) catalogRoot.getMetadataProperty(GraphPropertyEnum.CURRENT_CATALOG_UPDATE_TIME);
2771 Long prevTime = (Long) catalogRoot.getMetadataProperty(GraphPropertyEnum.PREV_CATALOG_UPDATE_TIME);
2773 return new CatalogUpdateTimestamp(prevTime == null ? 0 : prevTime.longValue(), currentTime == null ? 0 : currentTime.longValue());
2776 public void updateNamesOfCalculatedCapabilitiesRequirements(String componentId) {
2777 topologyTemplateOperation
2778 .updateNamesOfCalculatedCapabilitiesRequirements(componentId, getTopologyTemplate(componentId));
2781 public void revertNamesOfCalculatedCapabilitiesRequirements(String componentId) {
2782 topologyTemplateOperation
2783 .revertNamesOfCalculatedCapabilitiesRequirements(componentId, getTopologyTemplate(componentId));
2786 private TopologyTemplate getTopologyTemplate(String componentId) {
2787 return (TopologyTemplate) topologyTemplateOperation
2788 .getToscaElement(componentId, getFilterComponentWithCapProperties())
2790 .on(this::throwStorageException);
2793 private ComponentParametersView getFilterComponentWithCapProperties() {
2794 ComponentParametersView filter = new ComponentParametersView();
2795 filter.setIgnoreCapabiltyProperties(false);
2799 private ToscaElement throwStorageException(StorageOperationStatus status) {
2800 throw new StorageException(status);
2803 public Either<Boolean, StorageOperationStatus> isComponentInUse(String componentId) {
2804 final List<EdgeLabelEnum> forbiddenEdgeLabelEnums = Arrays.asList(EdgeLabelEnum.INSTANCE_OF, EdgeLabelEnum.PROXY_OF, EdgeLabelEnum.ALLOTTED_OF);
2805 Either<GraphVertex, JanusGraphOperationStatus> vertexById = janusGraphDao.getVertexById(componentId);
2806 if (vertexById.isLeft()) {
2807 for (EdgeLabelEnum edgeLabelEnum : forbiddenEdgeLabelEnums) {
2808 Iterator<Edge> edgeItr = vertexById.left().value().getVertex().edges(Direction.IN, edgeLabelEnum.name());
2809 if(edgeItr != null && edgeItr.hasNext()){
2810 return Either.left(true);
2814 return Either.left(false);
2817 public Either<List<Component>, StorageOperationStatus> getComponentListByInvariantUuid
2818 (String componentInvariantUuid, Map<GraphPropertyEnum, Object> additionalPropertiesToMatch) {
2820 Map<GraphPropertyEnum, Object> propertiesToMatch = new EnumMap<>(GraphPropertyEnum.class);
2821 if (MapUtils.isNotEmpty(additionalPropertiesToMatch)) {
2822 propertiesToMatch.putAll(additionalPropertiesToMatch);
2824 propertiesToMatch.put(GraphPropertyEnum.INVARIANT_UUID, componentInvariantUuid);
2826 Either<List<GraphVertex>, JanusGraphOperationStatus> vertexEither = janusGraphDao
2827 .getByCriteria(null, propertiesToMatch, JsonParseFlagEnum.ParseMetadata);
2829 if (vertexEither.isRight()) {
2830 log.debug("Couldn't fetch metadata for component with type {} and invariantUUId {}, error: {}", componentInvariantUuid, vertexEither.right().value());
2831 return Either.right(DaoStatusConverter.convertJanusGraphStatusToStorageStatus(vertexEither.right().value()));
2833 List<GraphVertex> vertexList = vertexEither.isLeft() ? vertexEither.left().value() : null;
2835 if (vertexList == null || vertexList.isEmpty()) {
2836 log.debug("Component with invariantUUId {} was not found", componentInvariantUuid);
2837 return Either.right(StorageOperationStatus.NOT_FOUND);
2840 ArrayList<Component> components = new ArrayList<>();
2841 for (GraphVertex vertex : vertexList) {
2842 Either<Component, StorageOperationStatus> toscaElementByOperation = getToscaElementByOperation(vertex);
2843 if (toscaElementByOperation.isRight()) {
2844 log.debug("Could not fetch the following Component by Invariant UUID {}", vertex.getUniqueId());
2845 return Either.right(toscaElementByOperation.right().value());
2847 components.add(toscaElementByOperation.left().value());
2850 return Either.left(components);
2853 public Either<List<Component>, StorageOperationStatus> getParentComponents(String componentId) {
2854 List<Component> parentComponents = new ArrayList<>();
2855 final List<EdgeLabelEnum> relationEdgeLabelEnums = Arrays.asList(EdgeLabelEnum.INSTANCE_OF, EdgeLabelEnum.PROXY_OF);
2856 Either<GraphVertex, JanusGraphOperationStatus> vertexById = janusGraphDao.getVertexById(componentId);
2857 if (vertexById.isLeft()) {
2858 for (EdgeLabelEnum edgeLabelEnum : relationEdgeLabelEnums) {
2859 Either<GraphVertex, JanusGraphOperationStatus> parentVertexEither = janusGraphDao
2860 .getParentVertex(vertexById.left().value(), edgeLabelEnum, JsonParseFlagEnum.ParseJson);
2861 if(parentVertexEither.isLeft()){
2862 Either<Component, StorageOperationStatus> componentEither = getToscaElement(parentVertexEither.left().value().getUniqueId());
2863 if(componentEither.isLeft()){
2864 parentComponents.add(componentEither.left().value());
2869 return Either.left(parentComponents);
2871 public void updateCapReqPropertiesOwnerId(String componentId) {
2872 topologyTemplateOperation
2873 .updateCapReqPropertiesOwnerId(componentId, getTopologyTemplate(componentId));