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=========================================================
20 package org.openecomp.sdc.be.model.jsonjanusgraph.operations;
22 import com.vdurmont.semver4j.Semver;
23 import com.vdurmont.semver4j.Semver.SemverType;
24 import fj.data.Either;
25 import org.apache.commons.collections.CollectionUtils;
26 import org.apache.commons.collections.MapUtils;
27 import org.apache.commons.lang3.StringUtils;
28 import org.apache.commons.lang3.tuple.ImmutablePair;
29 import org.apache.tinkerpop.gremlin.structure.Direction;
30 import org.apache.tinkerpop.gremlin.structure.Edge;
31 import org.janusgraph.graphdb.query.JanusGraphPredicate;
32 import org.openecomp.sdc.be.config.Configuration;
33 import org.openecomp.sdc.be.config.ConfigurationManager;
34 import org.openecomp.sdc.be.dao.api.exception.JanusGraphException;
35 import org.openecomp.sdc.be.dao.janusgraph.HealingJanusGraphDao;
36 import org.openecomp.sdc.be.dao.janusgraph.JanusGraphOperationStatus;
37 import org.openecomp.sdc.be.dao.jsongraph.GraphVertex;
38 import org.openecomp.sdc.be.dao.jsongraph.types.EdgeLabelEnum;
39 import org.openecomp.sdc.be.dao.jsongraph.types.JsonParseFlagEnum;
40 import org.openecomp.sdc.be.dao.jsongraph.types.VertexTypeEnum;
41 import org.openecomp.sdc.be.datatypes.elements.ArtifactDataDefinition;
42 import org.openecomp.sdc.be.datatypes.elements.AttributeDataDefinition;
43 import org.openecomp.sdc.be.datatypes.elements.CapabilityDataDefinition;
44 import org.openecomp.sdc.be.datatypes.elements.ComponentInstanceDataDefinition;
45 import org.openecomp.sdc.be.datatypes.elements.DataTypeDataDefinition;
46 import org.openecomp.sdc.be.datatypes.elements.GroupDataDefinition;
47 import org.openecomp.sdc.be.datatypes.elements.InterfaceDataDefinition;
48 import org.openecomp.sdc.be.datatypes.elements.ListCapabilityDataDefinition;
49 import org.openecomp.sdc.be.datatypes.elements.ListRequirementDataDefinition;
50 import org.openecomp.sdc.be.datatypes.elements.MapArtifactDataDefinition;
51 import org.openecomp.sdc.be.datatypes.elements.MapAttributesDataDefinition;
52 import org.openecomp.sdc.be.datatypes.elements.MapCapabilityProperty;
53 import org.openecomp.sdc.be.datatypes.elements.MapInterfaceDataDefinition;
54 import org.openecomp.sdc.be.datatypes.elements.MapListCapabilityDataDefinition;
55 import org.openecomp.sdc.be.datatypes.elements.MapListRequirementDataDefinition;
56 import org.openecomp.sdc.be.datatypes.elements.MapPropertiesDataDefinition;
57 import org.openecomp.sdc.be.datatypes.elements.PropertyDataDefinition;
58 import org.openecomp.sdc.be.datatypes.elements.RequirementDataDefinition;
59 import org.openecomp.sdc.be.datatypes.enums.ComponentTypeEnum;
60 import org.openecomp.sdc.be.datatypes.enums.GraphPropertyEnum;
61 import org.openecomp.sdc.be.datatypes.enums.JsonPresentationFields;
62 import org.openecomp.sdc.be.datatypes.enums.NodeTypeEnum;
63 import org.openecomp.sdc.be.datatypes.enums.OriginTypeEnum;
64 import org.openecomp.sdc.be.datatypes.enums.PromoteVersionEnum;
65 import org.openecomp.sdc.be.datatypes.enums.ResourceTypeEnum;
66 import org.openecomp.sdc.be.model.ArtifactDefinition;
67 import org.openecomp.sdc.be.model.AttributeDefinition;
68 import org.openecomp.sdc.be.model.CapabilityDefinition;
69 import org.openecomp.sdc.be.model.CatalogUpdateTimestamp;
70 import org.openecomp.sdc.be.model.Component;
71 import org.openecomp.sdc.be.model.ComponentInstance;
72 import org.openecomp.sdc.be.model.ComponentInstanceAttribute;
73 import org.openecomp.sdc.be.model.ComponentInstanceInput;
74 import org.openecomp.sdc.be.model.ComponentInstanceInterface;
75 import org.openecomp.sdc.be.model.ComponentInstanceOutput;
76 import org.openecomp.sdc.be.model.ComponentInstanceProperty;
77 import org.openecomp.sdc.be.model.ComponentParametersView;
78 import org.openecomp.sdc.be.model.DataTypeDefinition;
79 import org.openecomp.sdc.be.model.DistributionStatusEnum;
80 import org.openecomp.sdc.be.model.GroupDefinition;
81 import org.openecomp.sdc.be.model.GroupInstance;
82 import org.openecomp.sdc.be.model.InputDefinition;
83 import org.openecomp.sdc.be.model.InterfaceDefinition;
84 import org.openecomp.sdc.be.model.LifecycleStateEnum;
85 import org.openecomp.sdc.be.model.OutputDefinition;
86 import org.openecomp.sdc.be.model.PolicyDefinition;
87 import org.openecomp.sdc.be.model.PropertyDefinition;
88 import org.openecomp.sdc.be.model.RelationshipInfo;
89 import org.openecomp.sdc.be.model.RequirementCapabilityRelDef;
90 import org.openecomp.sdc.be.model.RequirementDefinition;
91 import org.openecomp.sdc.be.model.Resource;
92 import org.openecomp.sdc.be.model.Service;
93 import org.openecomp.sdc.be.model.User;
94 import org.openecomp.sdc.be.model.catalog.CatalogComponent;
95 import org.openecomp.sdc.be.model.jsonjanusgraph.config.ContainerInstanceTypesData;
96 import org.openecomp.sdc.be.model.jsonjanusgraph.datamodel.TopologyTemplate;
97 import org.openecomp.sdc.be.model.jsonjanusgraph.datamodel.ToscaElement;
98 import org.openecomp.sdc.be.model.jsonjanusgraph.operations.exception.ToscaOperationExceptionSupplier;
99 import org.openecomp.sdc.be.model.jsonjanusgraph.utils.ModelConverter;
100 import org.openecomp.sdc.be.model.operations.StorageException;
101 import org.openecomp.sdc.be.model.operations.api.IGraphLockOperation;
102 import org.openecomp.sdc.be.model.operations.api.StorageOperationStatus;
103 import org.openecomp.sdc.be.model.operations.impl.DaoStatusConverter;
104 import org.openecomp.sdc.be.model.operations.impl.UniqueIdBuilder;
105 import org.openecomp.sdc.be.model.utils.GroupUtils;
106 import org.openecomp.sdc.be.resources.data.ComponentMetadataData;
107 import org.openecomp.sdc.common.jsongraph.util.CommonUtility;
108 import org.openecomp.sdc.common.jsongraph.util.CommonUtility.LogLevelEnum;
109 import org.openecomp.sdc.common.log.enums.EcompLoggerErrorCode;
110 import org.openecomp.sdc.common.log.wrappers.Logger;
111 import org.openecomp.sdc.common.util.ValidationUtils;
112 import org.springframework.beans.factory.annotation.Autowired;
114 import java.util.ArrayList;
115 import java.util.Arrays;
116 import java.util.Collection;
117 import java.util.Collections;
118 import java.util.Comparator;
119 import java.util.EnumMap;
120 import java.util.HashMap;
121 import java.util.HashSet;
122 import java.util.Iterator;
123 import java.util.LinkedList;
124 import java.util.List;
125 import java.util.Map;
126 import java.util.Map.Entry;
127 import java.util.Objects;
128 import java.util.Optional;
129 import java.util.Set;
130 import java.util.TreeSet;
131 import java.util.function.BiPredicate;
132 import java.util.stream.Collectors;
134 import static java.util.Objects.requireNonNull;
135 import static org.apache.commons.collections.CollectionUtils.isEmpty;
136 import static org.apache.commons.collections.CollectionUtils.isNotEmpty;
137 import static org.janusgraph.core.attribute.Text.REGEX;
139 @org.springframework.stereotype.Component("tosca-operation-facade")
140 public class ToscaOperationFacade {
142 // region - ToscaElement - GetById
143 public static final String PROXY_SUFFIX = "_proxy";
145 private static final String COULDNT_FETCH_A_COMPONENT_WITH_AND_UNIQUE_ID_ERROR = "Couldn't fetch a component with and UniqueId {}, error: {}";
146 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 {}. ";
147 private static final String FAILED_TO_GET_UPDATED_RESOURCE_STATUS_IS = "Failed to get updated resource {}. Status is {}. ";
148 private static final String FAILED_TO_ADD_THE_PROPERTY_TO_THE_RESOURCE_STATUS_IS = "Failed to add the property {} to the resource {}. Status is {}. ";
149 private static final String SERVICE = "service";
150 private static final String VF = "VF";
151 private static final String NOT_SUPPORTED_COMPONENT_TYPE = "Not supported component type {}";
152 private static final String COMPONENT_CREATED_SUCCESSFULLY = "Component created successfully!!!";
153 private static final String INPUTS_ASSOCIATED_TO_COMPONENT_SUCCESSFULLY = "Inputs associated to component successfully!";
154 private static final String OUTPUTS_ASSOCIATED_TO_COMPONENT_SUCCESSFULLY = "Outputs associated to component successfully!";
155 private static final String COULDNT_FETCH_COMPONENT_WITH_AND_UNIQUE_ID_ERROR = "Couldn't fetch component with and unique id {}, error: {}";
156 private static final Logger log = Logger.getLogger(ToscaOperationFacade.class.getName());
158 private IGraphLockOperation graphLockOperation;
160 private NodeTypeOperation nodeTypeOperation;
162 private TopologyTemplateOperation topologyTemplateOperation;
164 private NodeTemplateOperation nodeTemplateOperation;
166 private GroupsOperation groupsOperation;
168 private HealingJanusGraphDao janusGraphDao;
171 private ContainerInstanceTypesData containerInstanceTypesData;
173 private static Optional<CapabilityDefinition> getPropertyCapability(String propertyParentUniqueId, Component containerComponent) {
174 Map<String, List<CapabilityDefinition>> componentCapabilities = containerComponent.getCapabilities();
175 if (MapUtils.isEmpty(componentCapabilities)) {
176 return Optional.empty();
178 List<CapabilityDefinition> capabilityDefinitionList = componentCapabilities.values().stream().flatMap(Collection::stream)
179 .collect(Collectors.toList());
180 if (CollectionUtils.isEmpty(capabilityDefinitionList)) {
181 return Optional.empty();
183 return capabilityDefinitionList.stream().filter(capabilityDefinition -> capabilityDefinition.getUniqueId().equals(propertyParentUniqueId))
187 public <T extends Component> Either<T, StorageOperationStatus> getToscaFullElement(String componentId) {
188 ComponentParametersView filters = new ComponentParametersView();
189 filters.setIgnoreCapabiltyProperties(false);
190 filters.setIgnoreServicePath(false);
191 return getToscaElement(componentId, filters);
194 public <T extends Component> Either<T, StorageOperationStatus> getToscaElement(String componentId) {
195 return getToscaElement(componentId, JsonParseFlagEnum.ParseAll);
198 public <T extends Component> Either<T, StorageOperationStatus> getToscaElement(String componentId, ComponentParametersView filters) {
199 Either<GraphVertex, JanusGraphOperationStatus> getVertexEither = janusGraphDao.getVertexById(componentId, filters.detectParseFlag());
200 if (getVertexEither.isRight()) {
201 log.debug(COULDNT_FETCH_COMPONENT_WITH_AND_UNIQUE_ID_ERROR, componentId, getVertexEither.right().value());
202 return Either.right(DaoStatusConverter.convertJanusGraphStatusToStorageStatus(getVertexEither.right().value()));
204 return getToscaElementByOperation(getVertexEither.left().value(), filters);
207 public <T extends Component> Either<T, StorageOperationStatus> getToscaElement(String componentId, JsonParseFlagEnum parseFlag) {
208 Either<GraphVertex, JanusGraphOperationStatus> getVertexEither = janusGraphDao.getVertexById(componentId, parseFlag);
209 if (getVertexEither.isRight()) {
210 log.debug(COULDNT_FETCH_COMPONENT_WITH_AND_UNIQUE_ID_ERROR, componentId, getVertexEither.right().value());
211 return Either.right(DaoStatusConverter.convertJanusGraphStatusToStorageStatus(getVertexEither.right().value()));
213 return getToscaElementByOperation(getVertexEither.left().value());
216 public <T extends Component> Either<T, StorageOperationStatus> getToscaElement(GraphVertex componentVertex) {
217 return getToscaElementByOperation(componentVertex);
220 public Either<Boolean, StorageOperationStatus> validateComponentExists(String componentId) {
221 Either<GraphVertex, JanusGraphOperationStatus> getVertexEither = janusGraphDao.getVertexById(componentId, JsonParseFlagEnum.NoParse);
222 if (getVertexEither.isRight()) {
223 JanusGraphOperationStatus status = getVertexEither.right().value();
224 if (status == JanusGraphOperationStatus.NOT_FOUND) {
225 return Either.left(false);
227 log.debug(COULDNT_FETCH_COMPONENT_WITH_AND_UNIQUE_ID_ERROR, componentId, getVertexEither.right().value());
228 return Either.right(DaoStatusConverter.convertJanusGraphStatusToStorageStatus(getVertexEither.right().value()));
231 return Either.left(true);
235 public <T extends Component> Either<T, StorageOperationStatus> findLastCertifiedToscaElementByUUID(T component) {
236 Map<GraphPropertyEnum, Object> props = new EnumMap<>(GraphPropertyEnum.class);
237 props.put(GraphPropertyEnum.UUID, component.getUUID());
238 props.put(GraphPropertyEnum.STATE, LifecycleStateEnum.CERTIFIED.name());
239 props.put(GraphPropertyEnum.IS_HIGHEST_VERSION, true);
240 Either<List<GraphVertex>, JanusGraphOperationStatus> getVertexEither = janusGraphDao
241 .getByCriteria(ModelConverter.getVertexType(component), props);
242 if (getVertexEither.isRight()) {
243 log.debug(COULDNT_FETCH_COMPONENT_WITH_AND_UNIQUE_ID_ERROR, component.getUniqueId(), getVertexEither.right().value());
244 return Either.right(DaoStatusConverter.convertJanusGraphStatusToStorageStatus(getVertexEither.right().value()));
246 return getToscaElementByOperation(getVertexEither.left().value().get(0));
249 // region - ToscaElement - GetByOperation
250 private <T extends Component> Either<T, StorageOperationStatus> getToscaElementByOperation(GraphVertex componentV) {
251 return getToscaElementByOperation(componentV, new ComponentParametersView());
254 private <T extends Component> Either<T, StorageOperationStatus> getToscaElementByOperation(GraphVertex componentV,
255 ComponentParametersView filters) {
256 if (componentV == null) {
257 log.debug("Unexpected null value for `componentV`");
258 return Either.right(StorageOperationStatus.GENERAL_ERROR);
260 VertexTypeEnum label = componentV.getLabel();
261 ToscaElementOperation toscaOperation = getToscaElementOperation(componentV);
262 if (toscaOperation != null) {
263 log.debug("getToscaElementByOperation: toscaOperation={}", toscaOperation.getClass());
265 Either<ToscaElement, StorageOperationStatus> toscaElement;
266 String componentId = componentV.getUniqueId();
267 if (toscaOperation != null) {
268 log.debug("Need to fetch tosca element for id {}", componentId);
269 toscaElement = toscaOperation.getToscaElement(componentV, filters);
271 log.debug("not supported tosca type {} for id {}", label, componentId);
272 toscaElement = Either.right(StorageOperationStatus.BAD_REQUEST);
274 return toscaElement.left().map(ModelConverter::convertFromToscaElement);
279 private ToscaElementOperation getToscaElementOperation(GraphVertex componentV) {
280 VertexTypeEnum label = componentV.getLabel();
283 return nodeTypeOperation;
284 case TOPOLOGY_TEMPLATE:
285 return topologyTemplateOperation;
291 public <T extends Component> Either<T, StorageOperationStatus> createToscaComponent(T resource) {
292 ToscaElement toscaElement = ModelConverter.convertToToscaElement(resource);
293 ToscaElementOperation toscaElementOperation = getToscaElementOperation(resource);
294 Either<ToscaElement, StorageOperationStatus> createToscaElement = toscaElementOperation.createToscaElement(toscaElement);
295 if (createToscaElement.isLeft()) {
296 log.debug(COMPONENT_CREATED_SUCCESSFULLY);
297 T dataModel = ModelConverter.convertFromToscaElement(createToscaElement.left().value());
298 return Either.left(dataModel);
300 return Either.right(createToscaElement.right().value());
303 // region - ToscaElement Delete
304 public StorageOperationStatus markComponentToDelete(Component componentToDelete) {
305 if (Boolean.TRUE.equals(componentToDelete.getIsDeleted()) && Boolean.FALSE.equals(componentToDelete.isHighestVersion())) {
306 // component already marked for delete
307 return StorageOperationStatus.OK;
309 Either<GraphVertex, JanusGraphOperationStatus> getResponse = janusGraphDao
310 .getVertexById(componentToDelete.getUniqueId(), JsonParseFlagEnum.ParseAll);
311 if (getResponse.isRight()) {
312 log.debug(COULDNT_FETCH_COMPONENT_WITH_AND_UNIQUE_ID_ERROR, componentToDelete.getUniqueId(), getResponse.right().value());
313 return DaoStatusConverter.convertJanusGraphStatusToStorageStatus(getResponse.right().value());
315 GraphVertex componentV = getResponse.left().value();
316 // same operation for node type and topology template operations
317 Either<GraphVertex, StorageOperationStatus> result = nodeTypeOperation.markComponentToDelete(componentV);
318 if (result.isRight()) {
319 return result.right().value();
321 return StorageOperationStatus.OK;
325 public <T extends Component> Either<T, StorageOperationStatus> deleteToscaComponent(String componentId) {
326 Either<GraphVertex, JanusGraphOperationStatus> getVertexEither = janusGraphDao.getVertexById(componentId, JsonParseFlagEnum.ParseAll);
327 if (getVertexEither.isRight()) {
328 log.debug("Couldn't fetch component vertex with and unique id {}, error: {}", componentId, getVertexEither.right().value());
329 return Either.right(DaoStatusConverter.convertJanusGraphStatusToStorageStatus(getVertexEither.right().value()));
331 Either<ToscaElement, StorageOperationStatus> deleteElement = deleteToscaElement(getVertexEither.left().value());
332 if (deleteElement.isRight()) {
333 log.debug("Failed to delete component with and unique id {}, error: {}", componentId, deleteElement.right().value());
334 return Either.right(deleteElement.right().value());
336 T dataModel = ModelConverter.convertFromToscaElement(deleteElement.left().value());
337 return Either.left(dataModel);
340 private Either<ToscaElement, StorageOperationStatus> deleteToscaElement(GraphVertex componentV) {
341 VertexTypeEnum label = componentV.getLabel();
342 Either<ToscaElement, StorageOperationStatus> toscaElement;
343 Object componentId = componentV.getUniqueId();
346 log.debug("Need to fetch node type for id {}", componentId);
347 toscaElement = nodeTypeOperation.deleteToscaElement(componentV);
349 case TOPOLOGY_TEMPLATE:
350 log.debug("Need to fetch topology template for id {}", componentId);
351 toscaElement = topologyTemplateOperation.deleteToscaElement(componentV);
354 log.debug("not supported tosca type {} for id {}", label, componentId);
355 toscaElement = Either.right(StorageOperationStatus.BAD_REQUEST);
362 private ToscaElementOperation getToscaElementOperation(Component component) {
363 return ModelConverter.isAtomicComponent(component) ? nodeTypeOperation : topologyTemplateOperation;
366 public <T extends Component> Either<T, StorageOperationStatus> getLatestByToscaResourceNameAndModel(final String toscaResourceName,
367 final String model) {
368 return getLatestByNameAndModel(toscaResourceName, JsonParseFlagEnum.ParseMetadata, new ComponentParametersView(), model);
371 private <T extends Component> Either<T, StorageOperationStatus> getLatestByNameAndModel(final String nodeName,
372 final JsonParseFlagEnum parseFlag,
373 final ComponentParametersView filter,
374 final String model) {
375 Either<T, StorageOperationStatus> result;
376 final Map<GraphPropertyEnum, Object> propertiesToMatch = new EnumMap<>(GraphPropertyEnum.class);
377 final Map<GraphPropertyEnum, Object> propertiesNotToMatch = new EnumMap<>(GraphPropertyEnum.class);
378 propertiesToMatch.put(GraphPropertyEnum.TOSCA_RESOURCE_NAME, nodeName);
379 propertiesToMatch.put(GraphPropertyEnum.IS_HIGHEST_VERSION, true);
380 propertiesNotToMatch.put(GraphPropertyEnum.IS_DELETED, true);
381 final Either<List<GraphVertex>, JanusGraphOperationStatus> highestResources = janusGraphDao
382 .getByCriteria(null, propertiesToMatch, propertiesNotToMatch, parseFlag, model);
383 if (highestResources.isRight()) {
384 final JanusGraphOperationStatus status = highestResources.right().value();
385 log.debug("failed to find resource with name {}. status={} ", nodeName, status);
386 result = Either.right(DaoStatusConverter.convertJanusGraphStatusToStorageStatus(status));
389 final List<GraphVertex> resources = highestResources.left().value();
390 double version = 0.0;
391 GraphVertex highestResource = null;
392 for (final GraphVertex vertex : resources) {
393 final Object versionObj = vertex.getMetadataProperty(GraphPropertyEnum.VERSION);
394 double resourceVersion = Double.parseDouble((String) versionObj);
395 if (resourceVersion > version) {
396 version = resourceVersion;
397 highestResource = vertex;
400 return getToscaElementByOperation(highestResource, filter);
403 public <T extends Component> Either<T, StorageOperationStatus> getLatestByToscaResourceName(String toscaResourceName, String modelName) {
404 return getLatestByName(GraphPropertyEnum.TOSCA_RESOURCE_NAME, toscaResourceName, modelName);
407 public <T extends Component> Either<T, StorageOperationStatus> getFullLatestComponentByToscaResourceName(String toscaResourceName) {
408 ComponentParametersView fetchAllFilter = new ComponentParametersView();
409 fetchAllFilter.setIgnoreServicePath(true);
410 fetchAllFilter.setIgnoreCapabiltyProperties(false);
411 return getLatestByName(GraphPropertyEnum.TOSCA_RESOURCE_NAME, toscaResourceName, JsonParseFlagEnum.ParseAll, fetchAllFilter, null);
414 public <T extends Component> Either<T, StorageOperationStatus> getLatestByName(String resourceName, String modelName) {
415 return getLatestByName(GraphPropertyEnum.NAME, resourceName, modelName);
418 public StorageOperationStatus validateCsarUuidUniqueness(String csarUUID) {
419 Map<GraphPropertyEnum, Object> properties = new EnumMap<>(GraphPropertyEnum.class);
420 properties.put(GraphPropertyEnum.CSAR_UUID, csarUUID);
421 Either<List<GraphVertex>, JanusGraphOperationStatus> resources = janusGraphDao
422 .getByCriteria(null, properties, JsonParseFlagEnum.ParseMetadata);
423 if (resources.isRight()) {
424 if (resources.right().value() == JanusGraphOperationStatus.NOT_FOUND) {
425 return StorageOperationStatus.OK;
427 log.debug("failed to get resources from graph with property name: {}", csarUUID);
428 return DaoStatusConverter.convertJanusGraphStatusToStorageStatus(resources.right().value());
431 return StorageOperationStatus.ENTITY_ALREADY_EXISTS;
434 public <T extends Component> Either<Set<T>, StorageOperationStatus> getFollowed(String userId, Set<LifecycleStateEnum> lifecycleStates,
435 Set<LifecycleStateEnum> lastStateStates,
436 ComponentTypeEnum componentType) {
437 Either<List<ToscaElement>, StorageOperationStatus> followedResources;
438 if (componentType == ComponentTypeEnum.RESOURCE) {
439 followedResources = nodeTypeOperation.getFollowedComponent(userId, lifecycleStates, lastStateStates, componentType);
441 followedResources = topologyTemplateOperation.getFollowedComponent(userId, lifecycleStates, lastStateStates, componentType);
443 Set<T> components = new HashSet<>();
444 if (followedResources.isRight() && followedResources.right().value() != StorageOperationStatus.NOT_FOUND) {
445 return Either.right(followedResources.right().value());
447 if (followedResources.isLeft()) {
448 List<ToscaElement> toscaElements = followedResources.left().value();
449 toscaElements.forEach(te -> {
450 T component = ModelConverter.convertFromToscaElement(te);
451 components.add(component);
454 return Either.left(components);
457 public Either<Resource, StorageOperationStatus> getLatestCertifiedNodeTypeByToscaResourceName(String toscaResourceName) {
458 return getLatestCertifiedByToscaResourceName(toscaResourceName, VertexTypeEnum.NODE_TYPE, JsonParseFlagEnum.ParseMetadata);
461 public Either<Resource, StorageOperationStatus> getByToscaResourceNameMatchingVendorRelease(final String toscaResourceName,
462 final String vendorVersion) {
463 return getByToscaResourceNameMatchingVendorRelease(toscaResourceName, VertexTypeEnum.NODE_TYPE, JsonParseFlagEnum.ParseMetadata,
467 public Either<Resource, StorageOperationStatus> getByToscaResourceNameMatchingVendorRelease(String toscaResourceName, VertexTypeEnum vertexType,
468 JsonParseFlagEnum parseFlag, String vendorRelease) {
469 Map<GraphPropertyEnum, Object> props = new EnumMap<>(GraphPropertyEnum.class);
470 props.put(GraphPropertyEnum.TOSCA_RESOURCE_NAME, toscaResourceName);
471 props.put(GraphPropertyEnum.STATE, LifecycleStateEnum.CERTIFIED.name());
472 Map<String, Entry<JanusGraphPredicate, Object>> predicateCriteria = getVendorVersionPredicate(vendorRelease);
473 Either<List<GraphVertex>, JanusGraphOperationStatus> getLatestRes = janusGraphDao
474 .getByCriteria(vertexType, props, null, predicateCriteria, parseFlag, null);
475 if (getLatestRes.isRight() || CollectionUtils.isEmpty(getLatestRes.left().value())) {
476 getLatestRes = janusGraphDao.getByCriteria(vertexType, props, parseFlag);
478 return getLatestRes.right().map(status -> {
480 .addRecordToLog(log, LogLevelEnum.DEBUG, "Failed to fetch {} with name {}. status={} ", vertexType, toscaResourceName, status);
481 return DaoStatusConverter.convertJanusGraphStatusToStorageStatus(status);
482 }).left().bind(resources -> {
483 double version = 0.0;
484 GraphVertex highestResource = null;
485 for (GraphVertex resource : resources) {
486 double resourceVersion = Double.parseDouble((String) resource.getJsonMetadataField(JsonPresentationFields.VERSION));
487 if (resourceVersion > version && isValidForVendorRelease(resource, vendorRelease)) {
488 version = resourceVersion;
489 highestResource = resource;
492 if (highestResource != null) {
493 return getToscaFullElement(highestResource.getUniqueId());
495 log.debug("The vertex with the highest version could not be found for {}", toscaResourceName);
496 return Either.right(StorageOperationStatus.GENERAL_ERROR);
501 public <T extends Component> Either<T, StorageOperationStatus> getByToscaResourceNameAndVersion(final String toscaResourceName,
502 final String version, final String model) {
503 Either<T, StorageOperationStatus> result;
505 Map<GraphPropertyEnum, Object> hasProperties = new EnumMap<>(GraphPropertyEnum.class);
506 Map<GraphPropertyEnum, Object> hasNotProperties = new EnumMap<>(GraphPropertyEnum.class);
508 hasProperties.put(GraphPropertyEnum.TOSCA_RESOURCE_NAME, toscaResourceName);
509 hasProperties.put(GraphPropertyEnum.VERSION, version);
510 hasNotProperties.put(GraphPropertyEnum.IS_DELETED, true);
512 Either<List<GraphVertex>, JanusGraphOperationStatus> getResourceRes = janusGraphDao
513 .getByCriteria(VertexTypeEnum.NODE_TYPE, hasProperties, hasNotProperties, JsonParseFlagEnum.ParseAll, model);
514 if (getResourceRes.isRight()) {
515 JanusGraphOperationStatus status = getResourceRes.right().value();
516 log.debug("failed to find resource with toscaResourceName {}, version {}. Status is {} ", toscaResourceName, version, status);
517 result = Either.right(DaoStatusConverter.convertJanusGraphStatusToStorageStatus(status));
520 return getToscaElementByOperation(getResourceRes.left().value().get(0));
523 private Map<String, Entry<JanusGraphPredicate, Object>> getVendorVersionPredicate(final String vendorRelease) {
524 Map<String, Entry<JanusGraphPredicate, Object>> predicateCriteria = new HashMap<>();
525 if (!"1.0".equals(vendorRelease)) {
526 String[] vendorReleaseElements = vendorRelease.split("\\.");
527 if (vendorReleaseElements.length > 0) {
528 String regex = ".*\"vendorRelease\":\"";
529 for (int i = 0; i < vendorReleaseElements.length; i++) {
530 regex += vendorReleaseElements[i];
531 regex += i < vendorReleaseElements.length - 1 ? "\\." : "\".*";
533 predicateCriteria.put("metadata", new HashMap.SimpleEntry<>(REGEX, regex));
536 return predicateCriteria;
539 public boolean isNodeAssociatedToModel(final String model, final Resource resource) {
540 final List<GraphVertex> modelElementVertices = getResourceModelElementVertices(resource);
542 return modelElementVertices.isEmpty();
544 return modelElementVertices.stream().anyMatch(graphVertex -> graphVertex.getMetadataProperty(GraphPropertyEnum.NAME).equals(model));
547 public List<GraphVertex> getResourceModelElementVertices(final Resource resource) {
548 final Either<GraphVertex, JanusGraphOperationStatus> vertex =
549 janusGraphDao.getVertexById(resource.getUniqueId(), JsonParseFlagEnum.NoParse);
550 if (vertex.isRight() || Objects.isNull(vertex.left().value())) {
551 return Collections.emptyList();
553 final Either<List<GraphVertex>, JanusGraphOperationStatus> nodeModelVertices =
554 janusGraphDao.getParentVertices(vertex.left().value(), EdgeLabelEnum.MODEL_ELEMENT, JsonParseFlagEnum.NoParse);
555 if (nodeModelVertices.isRight() || nodeModelVertices.left().value() == null) {
556 return Collections.emptyList();
558 return nodeModelVertices.left().value();
561 private boolean isValidForVendorRelease(final GraphVertex resource, final String vendorRelease) {
562 if (!vendorRelease.equals("1.0")) {
564 Semver resourceSemVer = new Semver((String) resource.getJsonMetadataField(JsonPresentationFields.VENDOR_RELEASE), SemverType.NPM);
565 Semver packageSemVer = new Semver(vendorRelease, SemverType.NPM);
566 return !resourceSemVer.isGreaterThan(packageSemVer);
567 } catch (Exception exception) {
568 log.debug("Error in comparing vendor release", exception);
575 public Either<Resource, StorageOperationStatus> getLatestCertifiedByToscaResourceName(String toscaResourceName, VertexTypeEnum vertexType,
576 JsonParseFlagEnum parseFlag) {
577 Map<GraphPropertyEnum, Object> props = new EnumMap<>(GraphPropertyEnum.class);
578 props.put(GraphPropertyEnum.TOSCA_RESOURCE_NAME, toscaResourceName);
579 props.put(GraphPropertyEnum.IS_HIGHEST_VERSION, true);
580 props.put(GraphPropertyEnum.STATE, LifecycleStateEnum.CERTIFIED.name());
581 Either<List<GraphVertex>, JanusGraphOperationStatus> getLatestRes = janusGraphDao.getByCriteria(vertexType, props, parseFlag);
582 return getLatestRes.right().map(status -> {
584 .addRecordToLog(log, LogLevelEnum.DEBUG, "Failed to fetch {} with name {}. status={} ", vertexType, toscaResourceName, status);
585 return DaoStatusConverter.convertJanusGraphStatusToStorageStatus(status);
586 }).left().bind(resources -> {
587 double version = 0.0;
588 GraphVertex highestResource = null;
589 for (GraphVertex resource : resources) {
590 double resourceVersion = Double.parseDouble((String) resource.getJsonMetadataField(JsonPresentationFields.VERSION));
591 if (resourceVersion > version) {
592 version = resourceVersion;
593 highestResource = resource;
596 if (highestResource != null) {
597 return getToscaFullElement(highestResource.getUniqueId());
599 log.debug("The vertex with the highest version could not be found for {}", toscaResourceName);
600 return Either.right(StorageOperationStatus.GENERAL_ERROR);
605 public Either<Resource, StorageOperationStatus> getLatestResourceByToscaResourceName(String toscaResourceName) {
606 if (toscaResourceName != null && toscaResourceName.contains("org.openecomp.resource.vf")) {
607 return getLatestResourceByToscaResourceName(toscaResourceName, VertexTypeEnum.TOPOLOGY_TEMPLATE, JsonParseFlagEnum.ParseMetadata);
609 return getLatestResourceByToscaResourceName(toscaResourceName, VertexTypeEnum.NODE_TYPE, JsonParseFlagEnum.ParseMetadata);
613 public Either<Resource, StorageOperationStatus> getLatestResourceByToscaResourceName(String toscaResourceName, VertexTypeEnum vertexType,
614 JsonParseFlagEnum parseFlag) {
615 Either<Resource, StorageOperationStatus> result = null;
616 Map<GraphPropertyEnum, Object> props = new EnumMap<>(GraphPropertyEnum.class);
617 props.put(GraphPropertyEnum.TOSCA_RESOURCE_NAME, toscaResourceName);
618 props.put(GraphPropertyEnum.IS_HIGHEST_VERSION, true);
619 if (!toscaResourceName.contains("org.openecomp.resource.vf")) {
620 props.put(GraphPropertyEnum.STATE, LifecycleStateEnum.CERTIFIED.name());
622 Either<List<GraphVertex>, JanusGraphOperationStatus> getLatestRes = janusGraphDao.getByCriteria(vertexType, props, parseFlag);
623 if (getLatestRes.isRight()) {
624 JanusGraphOperationStatus status = getLatestRes.right().value();
626 .addRecordToLog(log, LogLevelEnum.DEBUG, "Failed to fetch {} with name {}. status={} ", vertexType, toscaResourceName, status);
627 result = Either.right(DaoStatusConverter.convertJanusGraphStatusToStorageStatus(status));
629 if (result == null) {
630 List<GraphVertex> resources = getLatestRes.left().value();
631 double version = 0.0;
632 GraphVertex highestResource = null;
633 for (GraphVertex resource : resources) {
634 double resourceVersion = Double.parseDouble((String) resource.getJsonMetadataField(JsonPresentationFields.VERSION));
635 if (resourceVersion > version) {
636 version = resourceVersion;
637 highestResource = resource;
640 if (highestResource != null) {
641 result = getToscaFullElement(highestResource.getUniqueId());
643 log.debug("The vertex with the highest version could not be found for {}", toscaResourceName);
644 result = Either.right(StorageOperationStatus.GENERAL_ERROR);
650 public Either<Boolean, StorageOperationStatus> validateToscaResourceNameExists(String templateName) {
651 Either<Boolean, StorageOperationStatus> validateUniquenessRes = validateToscaResourceNameUniqueness(templateName);
652 if (validateUniquenessRes.isLeft()) {
653 return Either.left(!validateUniquenessRes.left().value());
655 return validateUniquenessRes;
658 public Either<RequirementCapabilityRelDef, StorageOperationStatus> dissociateResourceInstances(String componentId,
659 RequirementCapabilityRelDef requirementDef) {
660 return nodeTemplateOperation.dissociateResourceInstances(componentId, requirementDef);
664 * Allows to get fulfilled requirement by relation and received predicate
666 public Either<RequirementDataDefinition, StorageOperationStatus> getFulfilledRequirementByRelation(String componentId, String instanceId,
667 RequirementCapabilityRelDef relation,
668 BiPredicate<RelationshipInfo, RequirementDataDefinition> predicate) {
669 return nodeTemplateOperation.getFulfilledRequirementByRelation(componentId, instanceId, relation, predicate);
673 * Allows to get fulfilled capability by relation and received predicate
675 public Either<CapabilityDataDefinition, StorageOperationStatus> getFulfilledCapabilityByRelation(String componentId, String instanceId,
676 RequirementCapabilityRelDef relation,
677 BiPredicate<RelationshipInfo, CapabilityDataDefinition> predicate) {
678 return nodeTemplateOperation.getFulfilledCapabilityByRelation(componentId, instanceId, relation, predicate);
681 public Either<List<RequirementCapabilityRelDef>, StorageOperationStatus> associateResourceInstances(Component component, String componentId,
682 List<RequirementCapabilityRelDef> relations) {
683 Either<List<RequirementCapabilityRelDef>, StorageOperationStatus> reqAndCapListEither = nodeTemplateOperation
684 .associateResourceInstances(componentId, relations);
685 if (component != null) {
686 updateInstancesCapAndReqOnComponentFromDB(component);
688 return reqAndCapListEither;
691 protected Either<Boolean, StorageOperationStatus> validateToscaResourceNameUniqueness(String name) {
692 Map<GraphPropertyEnum, Object> properties = new EnumMap<>(GraphPropertyEnum.class);
693 properties.put(GraphPropertyEnum.TOSCA_RESOURCE_NAME, name);
694 Either<List<GraphVertex>, JanusGraphOperationStatus> resources = janusGraphDao
695 .getByCriteria(null, properties, JsonParseFlagEnum.ParseMetadata);
696 if (resources.isRight() && resources.right().value() != JanusGraphOperationStatus.NOT_FOUND) {
697 log.debug("failed to get resources from graph with property name: {}", name);
698 return Either.right(DaoStatusConverter.convertJanusGraphStatusToStorageStatus(resources.right().value()));
700 List<GraphVertex> resourceList = (resources.isLeft() ? resources.left().value() : null);
701 if (isNotEmpty(resourceList)) {
702 if (log.isDebugEnabled()) {
703 StringBuilder builder = new StringBuilder();
704 for (GraphVertex resourceData : resourceList) {
705 builder.append(resourceData.getUniqueId() + "|");
707 log.debug("resources with property name:{} exists in graph. found {}", name, builder);
709 return Either.left(false);
711 log.debug("resources with property name:{} does not exists in graph", name);
712 return Either.left(true);
716 // region - Component Update
717 public Either<Resource, StorageOperationStatus> overrideComponent(Resource newComponent, Resource oldComponent) {
718 copyArtifactsToNewComponent(newComponent, oldComponent);
719 Either<GraphVertex, JanusGraphOperationStatus> componentVEither = janusGraphDao
720 .getVertexById(oldComponent.getUniqueId(), JsonParseFlagEnum.NoParse);
721 if (componentVEither.isRight()) {
722 log.debug("Failed to fetch component {} error {}", oldComponent.getUniqueId(), componentVEither.right().value());
723 return Either.right(DaoStatusConverter.convertJanusGraphStatusToStorageStatus(componentVEither.right().value()));
725 GraphVertex componentv = componentVEither.left().value();
726 Either<GraphVertex, JanusGraphOperationStatus> parentVertexEither = janusGraphDao
727 .getParentVertex(componentv, EdgeLabelEnum.VERSION, JsonParseFlagEnum.NoParse);
728 if (parentVertexEither.isRight() && parentVertexEither.right().value() != JanusGraphOperationStatus.NOT_FOUND) {
729 log.debug("Failed to fetch parent version for component {} error {}", oldComponent.getUniqueId(), parentVertexEither.right().value());
730 return Either.right(DaoStatusConverter.convertJanusGraphStatusToStorageStatus(parentVertexEither.right().value()));
732 Either<ToscaElement, StorageOperationStatus> deleteToscaComponent = deleteToscaElement(componentv);
733 if (deleteToscaComponent.isRight()) {
734 log.debug("Failed to remove old component {} error {}", oldComponent.getUniqueId(), deleteToscaComponent.right().value());
735 return Either.right(deleteToscaComponent.right().value());
737 Either<Resource, StorageOperationStatus> createToscaComponent = createToscaComponent(newComponent);
738 if (createToscaComponent.isRight()) {
739 log.debug("Failed to create tosca element component {} error {}", newComponent.getUniqueId(), createToscaComponent.right().value());
740 return Either.right(createToscaComponent.right().value());
742 Resource newElement = createToscaComponent.left().value();
743 Either<GraphVertex, JanusGraphOperationStatus> newVersionEither = janusGraphDao
744 .getVertexById(newElement.getUniqueId(), JsonParseFlagEnum.NoParse);
745 if (newVersionEither.isRight()) {
746 log.debug("Failed to fetch new tosca element component {} error {}", newComponent.getUniqueId(), newVersionEither.right().value());
747 return Either.right(DaoStatusConverter.convertJanusGraphStatusToStorageStatus(newVersionEither.right().value()));
749 if (parentVertexEither.isLeft()) {
750 GraphVertex previousVersionV = parentVertexEither.left().value();
751 JanusGraphOperationStatus createEdge = janusGraphDao
752 .createEdge(previousVersionV, newVersionEither.left().value(), EdgeLabelEnum.VERSION, null);
753 if (createEdge != JanusGraphOperationStatus.OK) {
754 log.debug("Failed to associate to previous version {} new version {} error {}", previousVersionV.getUniqueId(),
755 newVersionEither.right().value(), createEdge);
756 return Either.right(DaoStatusConverter.convertJanusGraphStatusToStorageStatus(createEdge));
759 return Either.left(newElement);
762 void copyArtifactsToNewComponent(Resource newComponent, Resource oldComponent) {
763 // TODO - check if required
764 Map<String, ArtifactDefinition> toscaArtifacts = oldComponent.getToscaArtifacts();
765 if (toscaArtifacts != null && !toscaArtifacts.isEmpty()) {
766 toscaArtifacts.values().stream().forEach(a -> a.setDuplicated(Boolean.TRUE));
768 newComponent.setToscaArtifacts(toscaArtifacts);
769 Map<String, ArtifactDefinition> artifacts = oldComponent.getArtifacts();
770 if (artifacts != null && !artifacts.isEmpty()) {
771 artifacts.values().stream().forEach(a -> a.setDuplicated(Boolean.TRUE));
773 newComponent.setArtifacts(artifacts);
774 Map<String, ArtifactDefinition> depArtifacts = oldComponent.getDeploymentArtifacts();
775 if (depArtifacts != null && !depArtifacts.isEmpty()) {
776 depArtifacts.values().stream().forEach(a -> a.setDuplicated(Boolean.TRUE));
778 newComponent.setDeploymentArtifacts(depArtifacts);
779 newComponent.setLastUpdateDate(null);
780 newComponent.setHighestVersion(true);
783 public <T extends Component> Either<T, StorageOperationStatus> updateToscaElement(T componentToUpdate) {
784 return updateToscaElement(componentToUpdate, new ComponentParametersView());
787 public <T extends Component> Either<T, StorageOperationStatus> updateToscaElement(T componentToUpdate, ComponentParametersView filterResult) {
788 String componentId = componentToUpdate.getUniqueId();
789 Either<GraphVertex, JanusGraphOperationStatus> getVertexEither = janusGraphDao.getVertexById(componentId, JsonParseFlagEnum.ParseAll);
790 if (getVertexEither.isRight()) {
791 log.debug(COULDNT_FETCH_COMPONENT_WITH_AND_UNIQUE_ID_ERROR, componentId, getVertexEither.right().value());
792 return Either.right(DaoStatusConverter.convertJanusGraphStatusToStorageStatus(getVertexEither.right().value()));
794 GraphVertex elementV = getVertexEither.left().value();
795 ToscaElementOperation toscaElementOperation = getToscaElementOperation(elementV);
796 ToscaElement toscaElementToUpdate = ModelConverter.convertToToscaElement(componentToUpdate);
797 Either<ToscaElement, StorageOperationStatus> updateToscaElement = null;
798 if (toscaElementOperation != null) {
799 updateToscaElement = toscaElementOperation.updateToscaElement(toscaElementToUpdate, elementV, filterResult);
801 log.debug("Null value returned by `getToscaElementOperation` with value {}", elementV);
802 updateToscaElement = Either.right(StorageOperationStatus.GENERAL_ERROR);
804 return updateToscaElement.bimap(ModelConverter::convertFromToscaElement, status -> {
805 log.debug("Failed to update tosca element {} error {}", componentId, status);
810 private <T extends Component> Either<T, StorageOperationStatus> getLatestByName(GraphPropertyEnum property, String nodeName,
811 JsonParseFlagEnum parseFlag, String modelName) {
812 return getLatestByName(property, nodeName, parseFlag, new ComponentParametersView(), modelName);
815 private <T extends Component> Either<T, StorageOperationStatus> getLatestByName(GraphPropertyEnum property, String nodeName,
816 JsonParseFlagEnum parseFlag, ComponentParametersView filter,
818 Either<T, StorageOperationStatus> result;
819 Map<GraphPropertyEnum, Object> propertiesToMatch = new EnumMap<>(GraphPropertyEnum.class);
820 Map<GraphPropertyEnum, Object> propertiesNotToMatch = new EnumMap<>(GraphPropertyEnum.class);
821 propertiesToMatch.put(property, nodeName);
822 propertiesToMatch.put(GraphPropertyEnum.IS_HIGHEST_VERSION, true);
823 propertiesNotToMatch.put(GraphPropertyEnum.IS_DELETED, true);
824 Either<List<GraphVertex>, JanusGraphOperationStatus> highestResources = janusGraphDao
825 .getByCriteria(null, propertiesToMatch, propertiesNotToMatch, parseFlag, model);
826 if (highestResources.isRight()) {
827 JanusGraphOperationStatus status = highestResources.right().value();
828 log.debug("failed to find resource with name {}. status={} ", nodeName, status);
829 result = Either.right(DaoStatusConverter.convertJanusGraphStatusToStorageStatus(status));
832 List<GraphVertex> resources = highestResources.left().value();
833 double version = 0.0;
834 GraphVertex highestResource = null;
835 for (GraphVertex vertex : resources) {
836 Object versionObj = vertex.getMetadataProperty(GraphPropertyEnum.VERSION);
837 double resourceVersion = Double.parseDouble((String) versionObj);
838 if (resourceVersion > version) {
839 version = resourceVersion;
840 highestResource = vertex;
843 return getToscaElementByOperation(highestResource, filter);
846 // region - Component Get By ..
847 private <T extends Component> Either<T, StorageOperationStatus> getLatestByName(GraphPropertyEnum property, String nodeName, String modelName) {
848 return getLatestByName(property, nodeName, JsonParseFlagEnum.ParseMetadata, modelName);
851 public <T extends Component> Either<T, StorageOperationStatus> getBySystemNameAndVersion(final ComponentTypeEnum componentType,
852 final String systemName,
853 final String version) {
854 final Map<GraphPropertyEnum, Object> propertiesToMatch = new EnumMap<>(GraphPropertyEnum.class);
855 final Map<GraphPropertyEnum, Object> propertiesNotToMatch = new EnumMap<>(GraphPropertyEnum.class);
856 propertiesToMatch.put(GraphPropertyEnum.SYSTEM_NAME, systemName);
857 propertiesToMatch.put(GraphPropertyEnum.VERSION, version);
858 if (componentType != null) {
859 propertiesToMatch.put(GraphPropertyEnum.COMPONENT_TYPE, componentType.name());
861 propertiesNotToMatch.put(GraphPropertyEnum.IS_DELETED, true);
863 final Either<List<GraphVertex>, JanusGraphOperationStatus> getResourceResult
864 = janusGraphDao.getByCriteria(null, propertiesToMatch, propertiesNotToMatch,JsonParseFlagEnum.ParseAll);
865 if (getResourceResult.isRight()) {
866 final JanusGraphOperationStatus status = getResourceResult.right().value();
867 log.debug("Failed to find resource with systemName {}, version {}. Status is {} ", systemName, version, status);
868 return Either.right(DaoStatusConverter.convertJanusGraphStatusToStorageStatus(status));
870 return getToscaElementByOperation(getResourceResult.left().value().get(0));
873 public <T extends Component> Either<T, StorageOperationStatus> getComponentByNameAndVersion(ComponentTypeEnum componentType, String name,
875 return getComponentByNameAndVersion(componentType, name, version, JsonParseFlagEnum.ParseAll);
878 public <T extends Component> Either<T, StorageOperationStatus> getComponentByNameAndVersion(ComponentTypeEnum componentType, String name,
879 String version, JsonParseFlagEnum parseFlag) {
880 Map<GraphPropertyEnum, Object> hasProperties = new EnumMap<>(GraphPropertyEnum.class);
881 Map<GraphPropertyEnum, Object> hasNotProperties = new EnumMap<>(GraphPropertyEnum.class);
882 hasProperties.put(GraphPropertyEnum.NAME, name);
883 hasProperties.put(GraphPropertyEnum.VERSION, version);
884 hasNotProperties.put(GraphPropertyEnum.IS_DELETED, true);
885 if (componentType != null) {
886 hasProperties.put(GraphPropertyEnum.COMPONENT_TYPE, componentType.name());
888 Either<List<GraphVertex>, JanusGraphOperationStatus> getResourceRes = janusGraphDao
889 .getByCriteria(null, hasProperties, hasNotProperties, parseFlag);
890 if (getResourceRes.isRight()) {
891 JanusGraphOperationStatus status = getResourceRes.right().value();
892 log.debug("failed to find resource with name {}, version {}. Status is {} ", name, version, status);
893 return Either.right(DaoStatusConverter.convertJanusGraphStatusToStorageStatus(status));
895 return getToscaElementByOperation(getResourceRes.left().value().get(0));
898 public <T extends Component> Either<T, StorageOperationStatus> getComponentByNameAndVendorRelease(final ComponentTypeEnum componentType,
899 final String name, final String vendorRelease,
900 final JsonParseFlagEnum parseFlag,
901 final String modelName) {
902 Map<GraphPropertyEnum, Object> hasProperties = new EnumMap<>(GraphPropertyEnum.class);
903 Map<GraphPropertyEnum, Object> hasNotProperties = new EnumMap<>(GraphPropertyEnum.class);
904 hasProperties.put(GraphPropertyEnum.NAME, name);
905 hasNotProperties.put(GraphPropertyEnum.IS_DELETED, true);
906 if (componentType != null) {
907 hasProperties.put(GraphPropertyEnum.COMPONENT_TYPE, componentType.name());
909 Map<String, Entry<JanusGraphPredicate, Object>> predicateCriteria = getVendorVersionPredicate(vendorRelease);
910 Either<List<GraphVertex>, JanusGraphOperationStatus> getResourceRes = janusGraphDao.getByCriteria(null, hasProperties, hasNotProperties,
911 predicateCriteria, parseFlag, modelName);
912 if (getResourceRes.isRight()) {
913 JanusGraphOperationStatus status = getResourceRes.right().value();
914 log.debug("failed to find resource with name {}, version {}. Status is {} ", name, predicateCriteria, status);
915 return Either.right(DaoStatusConverter.convertJanusGraphStatusToStorageStatus(status));
917 return getToscaElementByOperation(getResourceRes.left().value().get(0));
920 public Either<List<CatalogComponent>, StorageOperationStatus> getCatalogOrArchiveComponents(boolean isCatalog,
921 List<OriginTypeEnum> excludeTypes) {
922 List<ResourceTypeEnum> excludedResourceTypes = Optional.ofNullable(excludeTypes).orElse(Collections.emptyList()).stream()
923 .filter(type -> !type.equals(OriginTypeEnum.SERVICE)).map(type -> ResourceTypeEnum.getTypeByName(type.name()))
924 .collect(Collectors.toList());
925 return topologyTemplateOperation.getElementCatalogData(isCatalog, excludedResourceTypes);
929 public <T extends Component> Either<List<T>, StorageOperationStatus> getCatalogComponents(ComponentTypeEnum componentType,
930 List<OriginTypeEnum> excludeTypes,
931 boolean isHighestVersions) {
932 List<T> components = new ArrayList<>();
933 Either<List<ToscaElement>, StorageOperationStatus> catalogDataResult;
934 List<ToscaElement> toscaElements = new ArrayList<>();
935 List<ResourceTypeEnum> excludedResourceTypes = Optional.ofNullable(excludeTypes).orElse(Collections.emptyList()).stream()
936 .filter(type -> !type.equals(OriginTypeEnum.SERVICE)).map(type -> ResourceTypeEnum.getTypeByName(type.name()))
937 .collect(Collectors.toList());
938 switch (componentType) {
940 catalogDataResult = nodeTypeOperation.getElementCatalogData(ComponentTypeEnum.RESOURCE, excludedResourceTypes, isHighestVersions);
941 if (catalogDataResult.isRight()) {
942 return Either.right(catalogDataResult.right().value());
944 toscaElements = catalogDataResult.left().value();
947 if (excludeTypes != null && excludeTypes.contains(OriginTypeEnum.SERVICE)) {
950 catalogDataResult = topologyTemplateOperation.getElementCatalogData(ComponentTypeEnum.SERVICE, null, isHighestVersions);
951 if (catalogDataResult.isRight()) {
952 return Either.right(catalogDataResult.right().value());
954 toscaElements = catalogDataResult.left().value();
957 log.debug(NOT_SUPPORTED_COMPONENT_TYPE, componentType);
958 return Either.right(StorageOperationStatus.BAD_REQUEST);
960 toscaElements.forEach(te -> {
961 T component = ModelConverter.convertFromToscaElement(te);
962 components.add(component);
964 return Either.left(components);
967 public Either<List<String>, StorageOperationStatus> deleteMarkedElements(ComponentTypeEnum componentType) {
968 Either<List<GraphVertex>, StorageOperationStatus> allComponentsMarkedForDeletion;
969 switch (componentType) {
971 allComponentsMarkedForDeletion = nodeTypeOperation.getAllComponentsMarkedForDeletion(componentType);
975 allComponentsMarkedForDeletion = topologyTemplateOperation.getAllComponentsMarkedForDeletion(componentType);
978 log.debug(NOT_SUPPORTED_COMPONENT_TYPE, componentType);
979 return Either.right(StorageOperationStatus.BAD_REQUEST);
981 if (allComponentsMarkedForDeletion.isRight()) {
982 return Either.right(allComponentsMarkedForDeletion.right().value());
984 List<GraphVertex> allMarked = allComponentsMarkedForDeletion.left().value();
985 return Either.left(checkIfInUseAndDelete(allMarked));
988 public List<String> deleteService(String invariantUUID, final boolean inTransaction) {
989 return deleteComponent(invariantUUID, NodeTypeEnum.Service, inTransaction);
992 public List<String> deleteComponent(String invariantUUID, NodeTypeEnum componentType, final boolean inTransaction) {
993 final List<GraphVertex> allServiceVerticesToDelete = findVertexListByInvariantUuid(invariantUUID);
994 List<String> affectedComponentIds = new ArrayList<>();
996 checkNotUsed(allServiceVerticesToDelete);
997 lockAllVerticesByNodeType(allServiceVerticesToDelete, componentType);
998 for (GraphVertex elementV : allServiceVerticesToDelete) {
999 Either<ToscaElement, StorageOperationStatus> deleteToscaElement = deleteToscaElement(elementV);
1000 if (deleteToscaElement.isRight()) {
1001 log.debug("Failed to delete element UniqueID {}, Name {}, error {}", elementV.getUniqueId(),
1002 elementV.getMetadataProperties().get(GraphPropertyEnum.NAME), deleteToscaElement.right().value());
1003 throwStorageException(deleteToscaElement.right().value());
1005 affectedComponentIds.add(elementV.getUniqueId());
1007 if (!inTransaction) {
1008 janusGraphDao.commit();
1010 } catch (Exception exception) {
1011 if (!inTransaction) {
1012 janusGraphDao.rollback();
1016 unlockAllVerticesByNodeType(allServiceVerticesToDelete, componentType);
1018 return affectedComponentIds;
1021 private void checkNotUsed(List<GraphVertex> vertices) {
1022 boolean isInUse = isAnyComponentInUse(vertices);
1024 Set<GraphVertex> listOfVertices = getComponentsUsingComponents(vertices);
1025 List<String> listOfStringComponents = new ArrayList<>();
1026 for (GraphVertex componentVertex : listOfVertices) {
1027 listOfStringComponents.add(
1028 componentVertex.getMetadataJson().get(GraphPropertyEnum.COMPONENT_TYPE.getProperty()) + " "
1029 + componentVertex.getMetadataJson().get(GraphPropertyEnum.NAME.getProperty())
1032 String stringOfComponents = String.join(", ", listOfStringComponents);
1033 throw ToscaOperationExceptionSupplier.componentInUse(stringOfComponents).get();
1037 public List<GraphVertex> findVertexListByInvariantUuid(final String invariantUuid) {
1039 return janusGraphDao.findAllVertexByInvariantUuid(invariantUuid, Collections.emptyMap());
1040 } catch (final JanusGraphException e) {
1041 log.error(EcompLoggerErrorCode.DATA_ERROR, this.getClass().getName(), e.getMessage());
1042 throw new StorageException(e.getStatus());
1046 public void commitAndCheck(String componentId) {
1047 JanusGraphOperationStatus status = janusGraphDao.commit();
1048 if (!status.equals(JanusGraphOperationStatus.OK)) {
1049 log.debug("error occurred when trying to DELETE {}. Return code is: {}", componentId, status);
1050 throwStorageException(DaoStatusConverter.convertJanusGraphStatusToStorageStatus(status));
1054 private Set<GraphVertex> getComponentsUsingComponents(List<GraphVertex> componentVertices) {
1055 Set<GraphVertex> inUseBy = new TreeSet<>(Comparator.comparing(GraphVertex::getUniqueId));
1056 for (final GraphVertex elementV : componentVertices) {
1057 List<GraphVertex> inUseByVertex = isInUse(elementV);
1058 if (!inUseByVertex.isEmpty()) {
1059 inUseBy.addAll(inUseByVertex);
1065 private boolean isAnyComponentInUse(List<GraphVertex> componentVertices) {
1066 boolean isComponentInUse = false;
1067 if (log.isDebugEnabled()) {
1068 for (final GraphVertex graphVertex : componentVertices) {
1069 if (!isInUse(graphVertex).isEmpty()) {
1070 isComponentInUse = true;
1074 isComponentInUse = componentVertices.stream().anyMatch(vertex -> !isInUse(vertex).isEmpty());
1076 return isComponentInUse;
1079 private List<GraphVertex> isInUse(GraphVertex elementV) {
1080 final List<EdgeLabelEnum> forbiddenEdgeLabelEnums = Arrays
1081 .asList(EdgeLabelEnum.INSTANCE_OF, EdgeLabelEnum.PROXY_OF, EdgeLabelEnum.ALLOTTED_OF);
1082 for (EdgeLabelEnum edgeLabelEnum : forbiddenEdgeLabelEnums) {
1083 Either<List<GraphVertex>, JanusGraphOperationStatus> inUseBy =
1084 janusGraphDao.getParentVertices(elementV, edgeLabelEnum, JsonParseFlagEnum.ParseAll);
1085 if (inUseBy.isLeft()) {
1086 if (log.isDebugEnabled()) {
1087 log.debug("Element {} in use.", elementV.getUniqueId());
1089 return inUseBy.left().value();
1092 return Collections.emptyList();
1095 private List<String> checkIfInUseAndDelete(List<GraphVertex> allMarked) {
1096 List<String> deleted = new ArrayList<>();
1097 for (GraphVertex elementV : allMarked) {
1098 boolean isAllowedToDelete = !isInUse(elementV).isEmpty();
1099 if (isAllowedToDelete) {
1100 Either<ToscaElement, StorageOperationStatus> deleteToscaElement = deleteToscaElement(elementV);
1101 if (deleteToscaElement.isRight()) {
1102 log.debug("Failed to delete marked element UniqueID {}, Name {}, error {}", elementV.getUniqueId(),
1103 elementV.getMetadataProperties().get(GraphPropertyEnum.NAME), deleteToscaElement.right().value());
1106 deleted.add(elementV.getUniqueId());
1112 private void lockAllVerticesByNodeType(List<GraphVertex> allVerticesToLock, NodeTypeEnum nodeType) {
1113 for (GraphVertex graphVertex : allVerticesToLock) {
1114 StorageOperationStatus storageOperationStatus = graphLockOperation.lockComponent(graphVertex.getUniqueId(), nodeType);
1115 if (!storageOperationStatus.equals(StorageOperationStatus.OK)) {
1116 throwStorageException(storageOperationStatus);
1121 private void unlockAllVerticesByNodeType(List<GraphVertex> allVerticesToUnlock, NodeTypeEnum nodeType) {
1122 for (GraphVertex graphVertex : allVerticesToUnlock) {
1123 graphLockOperation.unlockComponent(graphVertex.getUniqueId(), nodeType);
1127 public Either<List<String>, StorageOperationStatus> getAllComponentsMarkedForDeletion(ComponentTypeEnum componentType) {
1128 Either<List<GraphVertex>, StorageOperationStatus> allComponentsMarkedForDeletion;
1129 switch (componentType) {
1131 allComponentsMarkedForDeletion = nodeTypeOperation.getAllComponentsMarkedForDeletion(componentType);
1135 allComponentsMarkedForDeletion = topologyTemplateOperation.getAllComponentsMarkedForDeletion(componentType);
1138 log.debug(NOT_SUPPORTED_COMPONENT_TYPE, componentType);
1139 return Either.right(StorageOperationStatus.BAD_REQUEST);
1141 if (allComponentsMarkedForDeletion.isRight()) {
1142 return Either.right(allComponentsMarkedForDeletion.right().value());
1144 return Either.left(allComponentsMarkedForDeletion.left().value().stream().map(GraphVertex::getUniqueId).collect(Collectors.toList()));
1147 // region - Component Update
1148 public Either<ImmutablePair<Component, String>, StorageOperationStatus> addComponentInstanceToTopologyTemplate(Component containerComponent,
1149 Component origComponent,
1150 ComponentInstance componentInstance,
1151 boolean allowDeleted, User user) {
1152 Either<ImmutablePair<Component, String>, StorageOperationStatus> result = null;
1153 Either<ToscaElement, StorageOperationStatus> updateContainerComponentRes = null;
1154 if (StringUtils.isEmpty(componentInstance.getIcon())) {
1155 componentInstance.setIcon(origComponent.getIcon());
1157 String nameToFindForCounter;
1158 switch (componentInstance.getOriginType()) {
1160 nameToFindForCounter = ValidationUtils.normaliseComponentName(componentInstance.getSourceModelName()) + PROXY_SUFFIX;
1162 case ServiceSubstitution:
1163 nameToFindForCounter = ValidationUtils.normaliseComponentName(componentInstance.getSourceModelName());
1166 nameToFindForCounter = origComponent.getName();
1168 String nextComponentInstanceCounter = getNextComponentInstanceCounter(containerComponent, nameToFindForCounter);
1169 Either<ImmutablePair<TopologyTemplate, String>, StorageOperationStatus> addResult = nodeTemplateOperation
1170 .addComponentInstanceToTopologyTemplate(ModelConverter.convertToToscaElement(containerComponent),
1171 ModelConverter.convertToToscaElement(origComponent), nextComponentInstanceCounter, componentInstance, allowDeleted, user);
1172 if (addResult.isRight()) {
1173 CommonUtility.addRecordToLog(log, LogLevelEnum.DEBUG, "Failed to add the component instance {} to container component {}. ",
1174 componentInstance.getName(), containerComponent.getName());
1175 result = Either.right(addResult.right().value());
1177 if (result == null) {
1178 updateContainerComponentRes = topologyTemplateOperation.getToscaElement(containerComponent.getUniqueId());
1179 if (updateContainerComponentRes.isRight()) {
1181 .addRecordToLog(log, LogLevelEnum.DEBUG, "Failed to fetch updated topology template {} with updated component instance {}. ",
1182 containerComponent.getName(), componentInstance.getName());
1183 result = Either.right(updateContainerComponentRes.right().value());
1186 if (result == null) {
1187 Component updatedComponent = ModelConverter.convertFromToscaElement(updateContainerComponentRes.left().value());
1188 String createdInstanceId = addResult.left().value().getRight();
1190 .addRecordToLog(log, LogLevelEnum.TRACE, "The component instance {} has been added to container component {}. ", createdInstanceId,
1191 updatedComponent.getName());
1192 result = Either.left(new ImmutablePair<>(updatedComponent, createdInstanceId));
1197 public void associateComponentInstancesToComponent(Component containerComponent, Map<ComponentInstance, Resource> resourcesInstancesMap,
1198 boolean allowDeleted, boolean isUpdateCsar) {
1199 CommonUtility.addRecordToLog(log, LogLevelEnum.DEBUG, "Going to add component instances to component {}", containerComponent.getUniqueId());
1200 Either<GraphVertex, JanusGraphOperationStatus> metadataVertex = janusGraphDao
1201 .getVertexById(containerComponent.getUniqueId(), JsonParseFlagEnum.ParseAll);
1202 if (metadataVertex.isRight()) {
1203 JanusGraphOperationStatus status = metadataVertex.right().value();
1204 if (status == JanusGraphOperationStatus.NOT_FOUND) {
1205 status = JanusGraphOperationStatus.INVALID_ID;
1207 throw new StorageException(DaoStatusConverter.convertJanusGraphStatusToStorageStatus(status));
1209 Map<String, ComponentInstanceDataDefinition> compnentInstancesMap = nodeTemplateOperation
1210 .associateComponentInstancesToComponent(containerComponent, resourcesInstancesMap, metadataVertex.left().value(), allowDeleted,
1212 containerComponent.setComponentInstances(ModelConverter.getComponentInstancesFromMapObject(compnentInstancesMap, containerComponent));
1215 public Either<ImmutablePair<Component, String>, StorageOperationStatus> updateComponentInstanceMetadataOfTopologyTemplate(
1216 Component containerComponent, Component origComponent, ComponentInstance componentInstance) {
1217 Either<ImmutablePair<Component, String>, StorageOperationStatus> result = null;
1218 CommonUtility.addRecordToLog(log, LogLevelEnum.TRACE,
1219 "Going to update the metadata of the component instance {} belonging to container component {}. ", componentInstance.getName(),
1220 containerComponent.getName());
1221 componentInstance.setIcon(origComponent.getIcon());
1222 Either<ImmutablePair<TopologyTemplate, String>, StorageOperationStatus> updateResult = nodeTemplateOperation
1223 .updateComponentInstanceMetadataOfTopologyTemplate(ModelConverter.convertToToscaElement(containerComponent),
1224 ModelConverter.convertToToscaElement(origComponent), componentInstance);
1225 if (updateResult.isRight()) {
1226 CommonUtility.addRecordToLog(log, LogLevelEnum.DEBUG,
1227 "Failed to update the metadata of the component instance {} belonging to container component {}. ", componentInstance.getName(),
1228 containerComponent.getName());
1229 result = Either.right(updateResult.right().value());
1231 if (result == null) {
1232 Component updatedComponent = ModelConverter.convertFromToscaElement(updateResult.left().value().getLeft());
1233 String createdInstanceId = updateResult.left().value().getRight();
1235 .addRecordToLog(log, LogLevelEnum.TRACE, "The metadata of the component instance {} has been updated to container component {}. ",
1236 createdInstanceId, updatedComponent.getName());
1237 result = Either.left(new ImmutablePair<>(updatedComponent, createdInstanceId));
1242 public Either<Component, StorageOperationStatus> updateComponentInstanceMetadataOfTopologyTemplate(Component containerComponent) {
1243 return updateComponentInstanceMetadataOfTopologyTemplate(containerComponent, new ComponentParametersView());
1246 public Either<Component, StorageOperationStatus> updateComponentInstanceMetadataOfTopologyTemplate(Component containerComponent,
1247 ComponentParametersView filter) {
1248 Either<Component, StorageOperationStatus> result = null;
1249 CommonUtility.addRecordToLog(log, LogLevelEnum.TRACE, "Going to update the metadata belonging to container component {}. ",
1250 containerComponent.getName());
1251 Either<TopologyTemplate, StorageOperationStatus> updateResult = nodeTemplateOperation
1252 .updateComponentInstanceMetadataOfTopologyTemplate(ModelConverter.convertToToscaElement(containerComponent), filter);
1253 if (updateResult.isRight()) {
1254 CommonUtility.addRecordToLog(log, LogLevelEnum.DEBUG, "Failed to update the metadata belonging to container component {}. ",
1255 containerComponent.getName());
1256 result = Either.right(updateResult.right().value());
1258 if (result == null) {
1259 Component updatedComponent = ModelConverter.convertFromToscaElement(updateResult.left().value());
1261 .addRecordToLog(log, LogLevelEnum.TRACE, "The metadata has been updated to container component {}. ", updatedComponent.getName());
1262 result = Either.left(updatedComponent);
1268 public Either<ImmutablePair<Component, String>, StorageOperationStatus> deleteComponentInstanceFromTopologyTemplate(Component containerComponent,
1269 String resourceInstanceId) {
1270 Either<ImmutablePair<Component, String>, StorageOperationStatus> result = null;
1271 CommonUtility.addRecordToLog(log, LogLevelEnum.TRACE, "Going to delete the component instance {} belonging to container component {}. ",
1272 resourceInstanceId, containerComponent.getName());
1273 Either<ImmutablePair<TopologyTemplate, String>, StorageOperationStatus> updateResult = nodeTemplateOperation
1274 .deleteComponentInstanceFromTopologyTemplate(ModelConverter.convertToToscaElement(containerComponent), resourceInstanceId);
1275 if (updateResult.isRight()) {
1276 CommonUtility.addRecordToLog(log, LogLevelEnum.DEBUG, "Failed to delete the component instance {} belonging to container component {}. ",
1277 resourceInstanceId, containerComponent.getName());
1278 result = Either.right(updateResult.right().value());
1280 if (result == null) {
1281 Component updatedComponent = ModelConverter.convertFromToscaElement(updateResult.left().value().getLeft());
1282 String deletedInstanceId = updateResult.left().value().getRight();
1283 CommonUtility.addRecordToLog(log, LogLevelEnum.TRACE, "The component instance {} has been deleted from container component {}. ",
1284 deletedInstanceId, updatedComponent.getName());
1285 result = Either.left(new ImmutablePair<>(updatedComponent, deletedInstanceId));
1290 private String getNextComponentInstanceCounter(Component containerComponent, String originResourceName) {
1291 Integer nextCounter = 0;
1292 if (CollectionUtils.isNotEmpty(containerComponent.getComponentInstances())) {
1293 String normalizedName = ValidationUtils.normalizeComponentInstanceName(originResourceName);
1294 Integer maxCounter = getMaxCounterFromNamesAndIds(containerComponent, normalizedName);
1295 if (maxCounter != null) {
1296 nextCounter = maxCounter + 1;
1299 return nextCounter.toString();
1303 * @return max counter of component instance Id's, null if not found
1305 private Integer getMaxCounterFromNamesAndIds(Component containerComponent, String normalizedName) {
1306 List<String> countersInNames = containerComponent.getComponentInstances().stream()
1307 .filter(ci -> ci.getNormalizedName() != null && ci.getNormalizedName().startsWith(normalizedName))
1308 .map(ci -> ci.getNormalizedName().split(normalizedName)[1].replaceAll("\\D", "")).collect(Collectors.toList());
1309 List<String> countersInIds = containerComponent.getComponentInstances().stream()
1310 .filter(ci -> ci.getUniqueId() != null && ci.getUniqueId().contains(normalizedName))
1311 .map(ci -> ci.getUniqueId().split(normalizedName)[1].replaceAll("\\D", "")).collect(Collectors.toList());
1312 List<String> namesAndIdsList = new ArrayList<>(countersInNames);
1313 namesAndIdsList.addAll(countersInIds);
1314 return getMaxInteger(namesAndIdsList);
1317 private Integer getMaxInteger(List<String> counters) {
1318 Integer maxCounter = 0;
1319 Integer currCounter = null;
1320 for (String counter : counters) {
1322 currCounter = Integer.parseInt(counter);
1323 if (maxCounter < currCounter) {
1324 maxCounter = currCounter;
1326 } catch (NumberFormatException e) {
1329 return currCounter == null ? null : maxCounter;
1332 public Either<RequirementCapabilityRelDef, StorageOperationStatus> associateResourceInstances(Component component, String componentId,
1333 RequirementCapabilityRelDef requirementDef) {
1334 return nodeTemplateOperation.associateResourceInstances(componentId, requirementDef);
1337 public Either<List<InputDefinition>, StorageOperationStatus> createAndAssociateInputs(Map<String, InputDefinition> inputs, String componentId) {
1338 Either<GraphVertex, JanusGraphOperationStatus> getVertexEither = janusGraphDao.getVertexById(componentId, JsonParseFlagEnum.NoParse);
1339 if (getVertexEither.isRight()) {
1340 log.debug(COULDNT_FETCH_COMPONENT_WITH_AND_UNIQUE_ID_ERROR, componentId, getVertexEither.right().value());
1341 return Either.right(DaoStatusConverter.convertJanusGraphStatusToStorageStatus(getVertexEither.right().value()));
1343 GraphVertex vertex = getVertexEither.left().value();
1344 Map<String, PropertyDataDefinition> inputsMap = inputs.entrySet().stream()
1345 .collect(Collectors.toMap(Map.Entry::getKey, e -> new PropertyDataDefinition(e.getValue())));
1346 StorageOperationStatus status = topologyTemplateOperation.associateInputsToComponent(vertex, inputsMap, componentId);
1347 if (StorageOperationStatus.OK == status) {
1348 log.debug(INPUTS_ASSOCIATED_TO_COMPONENT_SUCCESSFULLY);
1349 List<InputDefinition> inputsResList = null;
1350 if (inputsMap != null && !inputsMap.isEmpty()) {
1351 inputsResList = inputsMap.values().stream().map(InputDefinition::new).collect(Collectors.toList());
1353 return Either.left(inputsResList);
1355 return Either.right(status);
1358 public Either<List<OutputDefinition>, StorageOperationStatus> createAndAssociateOutputs(final Map<String, OutputDefinition> outputs,
1359 final String componentId) {
1360 final Either<GraphVertex, JanusGraphOperationStatus> getVertexEither = janusGraphDao.getVertexById(componentId, JsonParseFlagEnum.NoParse);
1361 if (getVertexEither.isRight()) {
1362 log.debug(COULDNT_FETCH_COMPONENT_WITH_AND_UNIQUE_ID_ERROR, componentId, getVertexEither.right().value());
1363 return Either.right(DaoStatusConverter.convertJanusGraphStatusToStorageStatus(getVertexEither.right().value()));
1365 final GraphVertex vertex = getVertexEither.left().value();
1366 final Map<String, OutputDefinition> outputsMap = outputs.entrySet().stream()
1367 .collect(Collectors.toMap(Map.Entry::getKey, e -> new OutputDefinition(e.getValue())));
1368 final StorageOperationStatus status = topologyTemplateOperation.associateOutputsToComponent(vertex, outputsMap, componentId);
1369 if (StorageOperationStatus.OK == status) {
1370 log.debug(OUTPUTS_ASSOCIATED_TO_COMPONENT_SUCCESSFULLY);
1371 List<OutputDefinition> outputsResList = null;
1372 if (MapUtils.isNotEmpty(outputsMap)) {
1373 outputsResList = outputsMap.values().stream().map(OutputDefinition::new).collect(Collectors.toList());
1375 return Either.left(outputsResList);
1377 return Either.right(status);
1380 public Either<List<InputDefinition>, StorageOperationStatus> addInputsToComponent(Map<String, InputDefinition> inputs, String componentId) {
1381 Either<GraphVertex, JanusGraphOperationStatus> getVertexEither = janusGraphDao.getVertexById(componentId, JsonParseFlagEnum.NoParse);
1382 if (getVertexEither.isRight()) {
1383 log.debug(COULDNT_FETCH_COMPONENT_WITH_AND_UNIQUE_ID_ERROR, componentId, getVertexEither.right().value());
1384 return Either.right(DaoStatusConverter.convertJanusGraphStatusToStorageStatus(getVertexEither.right().value()));
1386 GraphVertex vertex = getVertexEither.left().value();
1387 Map<String, PropertyDefinition> inputsMap = inputs.entrySet().stream()
1388 .collect(Collectors.toMap(Map.Entry::getKey, e -> new PropertyDefinition(e.getValue())));
1389 StorageOperationStatus status = topologyTemplateOperation
1390 .addToscaDataToToscaElement(vertex, EdgeLabelEnum.INPUTS, VertexTypeEnum.INPUTS, inputsMap, JsonPresentationFields.NAME);
1391 if (StorageOperationStatus.OK == status) {
1392 log.debug(COMPONENT_CREATED_SUCCESSFULLY);
1393 List<InputDefinition> inputsResList = null;
1394 if (inputsMap != null && !inputsMap.isEmpty()) {
1395 inputsResList = inputsMap.values().stream().map(InputDefinition::new).collect(Collectors.toList());
1397 return Either.left(inputsResList);
1399 return Either.right(status);
1402 public Either<List<OutputDefinition>, StorageOperationStatus> addOutputsToComponent(Map<String, OutputDefinition> outputs, String componentId) {
1403 Either<GraphVertex, JanusGraphOperationStatus> getVertexEither = janusGraphDao.getVertexById(componentId, JsonParseFlagEnum.NoParse);
1404 if (getVertexEither.isRight()) {
1405 log.debug(COULDNT_FETCH_COMPONENT_WITH_AND_UNIQUE_ID_ERROR, componentId, getVertexEither.right().value());
1406 return Either.right(DaoStatusConverter.convertJanusGraphStatusToStorageStatus(getVertexEither.right().value()));
1408 GraphVertex vertex = getVertexEither.left().value();
1409 Map<String, AttributeDefinition> outputsMap = outputs.entrySet().stream()
1410 .collect(Collectors.toMap(Map.Entry::getKey, e -> new AttributeDefinition(e.getValue())));
1411 StorageOperationStatus status = topologyTemplateOperation
1412 .addToscaDataToToscaElement(vertex, EdgeLabelEnum.OUTPUTS, VertexTypeEnum.OUTPUTS, outputsMap, JsonPresentationFields.NAME);
1413 if (StorageOperationStatus.OK == status) {
1414 log.debug(COMPONENT_CREATED_SUCCESSFULLY);
1415 List<OutputDefinition> outputsResList = null;
1416 if (outputsMap != null && !outputsMap.isEmpty()) {
1417 outputsResList = outputsMap.values().stream().map(OutputDefinition::new).collect(Collectors.toList());
1419 return Either.left(outputsResList);
1421 return Either.right(status);
1425 * Add data types into a Component.
1427 * @param dataTypes datatypes to be added. the key should be each name of data type.
1428 * @param componentId unique ID of Component.
1429 * @return list of data types.
1431 public Either<List<DataTypeDefinition>, StorageOperationStatus> addDataTypesToComponent(Map<String, DataTypeDefinition> dataTypes,
1432 String componentId) {
1433 log.trace("#addDataTypesToComponent - enter, componentId={}", componentId);
1434 /* get component vertex */
1435 Either<GraphVertex, JanusGraphOperationStatus> getVertexEither = janusGraphDao
1436 .getVertexById(componentId, JsonParseFlagEnum.NoParse);
1437 if (getVertexEither.isRight()) {
1438 /* not found / error */
1439 log.debug(COULDNT_FETCH_COMPONENT_WITH_AND_UNIQUE_ID_ERROR, componentId, getVertexEither.right().value());
1440 return Either.right(DaoStatusConverter.convertJanusGraphStatusToStorageStatus(getVertexEither.right().value()));
1442 GraphVertex vertex = getVertexEither.left().value();
1443 log.trace("#addDataTypesToComponent - get vertex ok");
1444 // convert DataTypeDefinition to DataTypeDataDefinition
1445 Map<String, DataTypeDataDefinition> dataTypeDataMap = dataTypes.entrySet().stream()
1446 .collect(Collectors.toMap(Map.Entry::getKey, e -> convertDataTypeToDataTypeData(e.getValue())));
1447 // add datatype(s) to the Component.
1449 // if child vertex does not exist, it will be created.
1450 StorageOperationStatus status = topologyTemplateOperation
1451 .addToscaDataToToscaElement(vertex, EdgeLabelEnum.DATA_TYPES, VertexTypeEnum.DATA_TYPES, dataTypeDataMap, JsonPresentationFields.NAME);
1452 if (StorageOperationStatus.OK == status) {
1453 log.debug(COMPONENT_CREATED_SUCCESSFULLY);
1454 List<DataTypeDefinition> inputsResList = null;
1455 if (!dataTypes.isEmpty()) {
1456 inputsResList = new ArrayList<>(dataTypes.values());
1458 return Either.left(inputsResList);
1460 log.trace("#addDataTypesToComponent - leave");
1461 return Either.right(status);
1464 private DataTypeDataDefinition convertDataTypeToDataTypeData(DataTypeDefinition dataType) {
1465 DataTypeDataDefinition dataTypeData = new DataTypeDataDefinition(dataType);
1466 if (CollectionUtils.isNotEmpty(dataType.getProperties())) {
1467 List<PropertyDataDefinition> propertyDataList = dataType.getProperties().stream().map(PropertyDataDefinition::new)
1468 .collect(Collectors.toList());
1469 dataTypeData.setPropertiesData(propertyDataList);
1471 // if "derivedFrom" data_type exists, copy the name to "derivedFromName"
1472 if (dataType.getDerivedFrom() != null && StringUtils.isNotEmpty(dataType.getDerivedFrom().getName())) {
1473 // if names are different, log it
1474 if (!StringUtils.equals(dataTypeData.getDerivedFromName(), dataType.getDerivedFrom().getName())) {
1475 log.debug("#convertDataTypeToDataTypeData - derivedFromName(={}) overwritten by derivedFrom.name(={})", dataType.getDerivedFromName(),
1476 dataType.getDerivedFrom().getName());
1478 dataTypeData.setDerivedFromName(dataType.getDerivedFrom().getName());
1480 // supply "name" field to toscaPresentationValue in each datatype object for DAO operations
1481 dataTypeData.setToscaPresentationValue(JsonPresentationFields.NAME, dataType.getName());
1482 return dataTypeData;
1485 public Either<List<InputDefinition>, StorageOperationStatus> getComponentInputs(String componentId) {
1486 Either<GraphVertex, JanusGraphOperationStatus> getVertexEither = janusGraphDao.getVertexById(componentId, JsonParseFlagEnum.NoParse);
1487 if (getVertexEither.isRight()) {
1488 log.debug(COULDNT_FETCH_COMPONENT_WITH_AND_UNIQUE_ID_ERROR, componentId, getVertexEither.right().value());
1489 return Either.right(DaoStatusConverter.convertJanusGraphStatusToStorageStatus(getVertexEither.right().value()));
1491 Either<ToscaElement, StorageOperationStatus> toscaElement = topologyTemplateOperation.getToscaElement(componentId);
1492 if (toscaElement.isRight()) {
1493 return Either.right(toscaElement.right().value());
1495 TopologyTemplate topologyTemplate = (TopologyTemplate) toscaElement.left().value();
1496 Map<String, PropertyDataDefinition> inputsMap = topologyTemplate.getInputs();
1497 List<InputDefinition> inputs = new ArrayList<>();
1498 if (MapUtils.isNotEmpty(inputsMap)) {
1499 inputs = inputsMap.values().stream().map(p -> new InputDefinition(p)).collect(Collectors.toList());
1501 return Either.left(inputs);
1504 public Either<List<InputDefinition>, StorageOperationStatus> updateInputsToComponent(List<InputDefinition> inputs, String componentId) {
1505 Either<GraphVertex, JanusGraphOperationStatus> getVertexEither = janusGraphDao.getVertexById(componentId, JsonParseFlagEnum.NoParse);
1506 if (getVertexEither.isRight()) {
1507 log.debug(COULDNT_FETCH_COMPONENT_WITH_AND_UNIQUE_ID_ERROR, componentId, getVertexEither.right().value());
1508 return Either.right(DaoStatusConverter.convertJanusGraphStatusToStorageStatus(getVertexEither.right().value()));
1510 GraphVertex vertex = getVertexEither.left().value();
1511 List<PropertyDataDefinition> inputsAsDataDef = inputs.stream().map(PropertyDataDefinition::new).collect(Collectors.toList());
1512 StorageOperationStatus status = topologyTemplateOperation
1513 .updateToscaDataOfToscaElement(vertex, EdgeLabelEnum.INPUTS, VertexTypeEnum.INPUTS, inputsAsDataDef, JsonPresentationFields.NAME);
1514 if (StorageOperationStatus.OK == status) {
1515 log.debug(COMPONENT_CREATED_SUCCESSFULLY);
1516 List<InputDefinition> inputsResList = null;
1517 if (CollectionUtils.isNotEmpty(inputsAsDataDef)) {
1518 inputsResList = inputsAsDataDef.stream().map(InputDefinition::new).collect(Collectors.toList());
1520 return Either.left(inputsResList);
1522 return Either.right(status);
1525 public Either<List<OutputDefinition>, StorageOperationStatus> updateOutputsToComponent(List<OutputDefinition> outputs, String componentId) {
1526 Either<GraphVertex, JanusGraphOperationStatus> getVertexEither = janusGraphDao.getVertexById(componentId, JsonParseFlagEnum.NoParse);
1527 if (getVertexEither.isRight()) {
1528 log.debug(COULDNT_FETCH_COMPONENT_WITH_AND_UNIQUE_ID_ERROR, componentId, getVertexEither.right().value());
1529 return Either.right(DaoStatusConverter.convertJanusGraphStatusToStorageStatus(getVertexEither.right().value()));
1531 GraphVertex vertex = getVertexEither.left().value();
1532 List<AttributeDataDefinition> outputsAsDataDef = outputs.stream().map(AttributeDataDefinition::new).collect(Collectors.toList());
1533 StorageOperationStatus status = topologyTemplateOperation
1534 .updateToscaDataOfToscaElement(vertex, EdgeLabelEnum.OUTPUTS, VertexTypeEnum.OUTPUTS, outputsAsDataDef, JsonPresentationFields.NAME);
1535 if (StorageOperationStatus.OK == status) {
1536 log.debug(COMPONENT_CREATED_SUCCESSFULLY);
1537 List<OutputDefinition> outputsResList = null;
1538 if (!outputsAsDataDef.isEmpty()) {
1539 outputsResList = outputsAsDataDef.stream().map(OutputDefinition::new).collect(Collectors.toList());
1541 return Either.left(outputsResList);
1543 return Either.right(status);
1546 // region - ComponentInstance
1547 public Either<Map<String, List<ComponentInstanceProperty>>, StorageOperationStatus> associateComponentInstancePropertiesToComponent(
1548 Map<String, List<ComponentInstanceProperty>> instProperties, String componentId) {
1549 Either<GraphVertex, JanusGraphOperationStatus> getVertexEither = janusGraphDao.getVertexById(componentId, JsonParseFlagEnum.NoParse);
1550 if (getVertexEither.isRight()) {
1551 log.debug(COULDNT_FETCH_COMPONENT_WITH_AND_UNIQUE_ID_ERROR, componentId, getVertexEither.right().value());
1552 return Either.right(DaoStatusConverter.convertJanusGraphStatusToStorageStatus(getVertexEither.right().value()));
1554 GraphVertex vertex = getVertexEither.left().value();
1555 Map<String, MapPropertiesDataDefinition> instPropsMap = new HashMap<>();
1556 if (instProperties != null) {
1557 MapPropertiesDataDefinition propertiesMap;
1558 for (Entry<String, List<ComponentInstanceProperty>> entry : instProperties.entrySet()) {
1559 propertiesMap = new MapPropertiesDataDefinition();
1560 propertiesMap.setMapToscaDataDefinition(
1561 entry.getValue().stream().map(PropertyDataDefinition::new).collect(Collectors.toMap(PropertyDataDefinition::getName, e -> e)));
1562 instPropsMap.put(entry.getKey(), propertiesMap);
1565 StorageOperationStatus status = topologyTemplateOperation.associateInstPropertiesToComponent(vertex, instPropsMap);
1566 if (StorageOperationStatus.OK == status) {
1567 log.debug(COMPONENT_CREATED_SUCCESSFULLY);
1568 return Either.left(instProperties);
1570 return Either.right(status);
1574 * saves the instInputs as the updated instance inputs of the component container in DB
1576 public Either<Map<String, List<ComponentInstanceInput>>, StorageOperationStatus> updateComponentInstanceInputsToComponent(
1577 Map<String, List<ComponentInstanceInput>> instInputs, String componentId) {
1578 if (instInputs == null || instInputs.isEmpty()) {
1579 return Either.left(instInputs);
1581 StorageOperationStatus status;
1582 for (Entry<String, List<ComponentInstanceInput>> inputsPerIntance : instInputs.entrySet()) {
1583 List<ComponentInstanceInput> toscaDataListPerInst = inputsPerIntance.getValue();
1584 List<String> pathKeysPerInst = new ArrayList<>();
1585 pathKeysPerInst.add(inputsPerIntance.getKey());
1586 status = topologyTemplateOperation
1587 .updateToscaDataDeepElementsOfToscaElement(componentId, EdgeLabelEnum.INST_INPUTS, VertexTypeEnum.INST_INPUTS, toscaDataListPerInst,
1588 pathKeysPerInst, JsonPresentationFields.NAME);
1589 if (status != StorageOperationStatus.OK) {
1590 log.debug("Failed to update component instance inputs for instance {} in component {} edge type {} error {}",
1591 inputsPerIntance.getKey(), componentId, EdgeLabelEnum.INST_INPUTS, status);
1592 return Either.right(status);
1595 return Either.left(instInputs);
1599 * saves the instProps as the updated instance properties of the component container in DB
1601 public Either<Map<String, List<ComponentInstanceProperty>>, StorageOperationStatus> updateComponentInstancePropsToComponent(
1602 Map<String, List<ComponentInstanceProperty>> instProps, String componentId) {
1603 if (instProps == null || instProps.isEmpty()) {
1604 return Either.left(instProps);
1606 StorageOperationStatus status;
1607 for (Entry<String, List<ComponentInstanceProperty>> propsPerIntance : instProps.entrySet()) {
1608 List<ComponentInstanceProperty> toscaDataListPerInst = propsPerIntance.getValue();
1609 List<String> pathKeysPerInst = new ArrayList<>();
1610 pathKeysPerInst.add(propsPerIntance.getKey());
1611 status = topologyTemplateOperation
1612 .updateToscaDataDeepElementsOfToscaElement(componentId, EdgeLabelEnum.INST_PROPERTIES, VertexTypeEnum.INST_PROPERTIES,
1613 toscaDataListPerInst, pathKeysPerInst, JsonPresentationFields.NAME);
1614 if (status != StorageOperationStatus.OK) {
1615 log.debug("Failed to update component instance inputs for instance {} in component {} edge type {} error {}",
1616 propsPerIntance.getKey(), componentId, EdgeLabelEnum.INST_PROPERTIES, status);
1617 return Either.right(status);
1620 return Either.left(instProps);
1623 public Either<Map<String, List<ComponentInstanceInput>>, StorageOperationStatus> associateComponentInstanceInputsToComponent(
1624 Map<String, List<ComponentInstanceInput>> instInputs, String componentId) {
1625 Either<GraphVertex, JanusGraphOperationStatus> getVertexEither = janusGraphDao.getVertexById(componentId, JsonParseFlagEnum.NoParse);
1626 if (getVertexEither.isRight()) {
1627 log.debug(COULDNT_FETCH_COMPONENT_WITH_AND_UNIQUE_ID_ERROR, componentId, getVertexEither.right().value());
1628 return Either.right(DaoStatusConverter.convertJanusGraphStatusToStorageStatus(getVertexEither.right().value()));
1630 GraphVertex vertex = getVertexEither.left().value();
1631 Map<String, MapPropertiesDataDefinition> instPropsMap = new HashMap<>();
1632 if (instInputs != null) {
1633 MapPropertiesDataDefinition propertiesMap;
1634 for (Entry<String, List<ComponentInstanceInput>> entry : instInputs.entrySet()) {
1635 propertiesMap = new MapPropertiesDataDefinition();
1636 propertiesMap.setMapToscaDataDefinition(
1637 entry.getValue().stream().map(PropertyDataDefinition::new).collect(Collectors.toMap(PropertyDataDefinition::getName, e -> e)));
1638 instPropsMap.put(entry.getKey(), propertiesMap);
1641 StorageOperationStatus status = topologyTemplateOperation.associateInstInputsToComponent(vertex, instPropsMap);
1642 if (StorageOperationStatus.OK == status) {
1643 log.debug(COMPONENT_CREATED_SUCCESSFULLY);
1644 return Either.left(instInputs);
1646 return Either.right(status);
1649 public Either<Map<String, MapInterfaceDataDefinition>, StorageOperationStatus> associateComponentInstanceInterfacesToComponent(
1650 Map<String, Map<String, InterfaceDefinition>> instInterfaces,
1653 Either<GraphVertex, JanusGraphOperationStatus> getVertexEither = janusGraphDao.getVertexById(
1655 JsonParseFlagEnum.NoParse
1657 if (getVertexEither.isRight()) {
1659 COULDNT_FETCH_COMPONENT_WITH_AND_UNIQUE_ID_ERROR,
1661 getVertexEither.right().value()
1663 return Either.right(
1664 DaoStatusConverter.convertJanusGraphStatusToStorageStatus(
1665 getVertexEither.right().value()
1669 GraphVertex vertex = getVertexEither.left().value();
1670 Map<String, MapInterfaceDataDefinition> instInterfacesMap = new HashMap<>();
1671 if (instInterfaces != null) {
1672 MapInterfaceDataDefinition interfacesMap = new MapInterfaceDataDefinition();
1673 for (Map.Entry<String, Map<String, InterfaceDefinition>> entryInstances : instInterfaces.entrySet()) {
1674 Map<String, InterfaceDataDefinition> incomingInterfacesMap = entryInstances.getValue().entrySet().stream()
1675 .collect(Collectors.toMap(e -> e.getKey(), e -> e.getValue()));
1676 interfacesMap.setMapToscaDataDefinition(incomingInterfacesMap);
1677 instInterfacesMap.put(entryInstances.getKey(), interfacesMap);
1680 StorageOperationStatus status = topologyTemplateOperation.associateInstInterfacesToComponent(
1684 if (StorageOperationStatus.OK == status) {
1685 log.debug(COMPONENT_CREATED_SUCCESSFULLY);
1686 return Either.left(instInterfacesMap);
1688 return Either.right(status);
1691 public Either<Map<String, List<ComponentInstanceInput>>, StorageOperationStatus> addComponentInstanceInputsToComponent(
1692 Component containerComponent, Map<String, List<ComponentInstanceInput>> instProperties) {
1693 requireNonNull(instProperties);
1694 StorageOperationStatus status;
1695 for (Entry<String, List<ComponentInstanceInput>> entry : instProperties.entrySet()) {
1696 List<ComponentInstanceInput> props = entry.getValue();
1697 String componentInstanceId = entry.getKey();
1698 if (!isEmpty(props)) {
1699 for (ComponentInstanceInput property : props) {
1700 List<ComponentInstanceInput> componentInstancesInputs = containerComponent.getComponentInstancesInputs().get(componentInstanceId);
1701 Optional<ComponentInstanceInput> instanceProperty = componentInstancesInputs.stream()
1702 .filter(p -> p.getName().equals(property.getName())).findAny();
1703 if (instanceProperty.isPresent()) {
1704 status = updateComponentInstanceInput(containerComponent, componentInstanceId, property);
1706 status = addComponentInstanceInput(containerComponent, componentInstanceId, property);
1708 if (status != StorageOperationStatus.OK) {
1709 log.debug("Failed to update instance input {} for instance {} error {} ", property, componentInstanceId, status);
1710 return Either.right(status);
1712 log.trace("instance input {} for instance {} updated", property, componentInstanceId);
1717 return Either.left(instProperties);
1720 public Either<Map<String, List<ComponentInstanceOutput>>, StorageOperationStatus> addComponentInstanceOutputsToComponent(
1721 Component containerComponent, Map<String, List<ComponentInstanceOutput>> instOutputs) {
1722 requireNonNull(instOutputs);
1723 StorageOperationStatus status;
1724 for (final Entry<String, List<ComponentInstanceOutput>> entry : instOutputs.entrySet()) {
1725 final List<ComponentInstanceOutput> outputs = entry.getValue();
1726 final String componentInstanceId = entry.getKey();
1727 if (!isEmpty(outputs)) {
1728 for (final ComponentInstanceOutput output : outputs) {
1729 final List<ComponentInstanceOutput> componentInstanceOutputs = containerComponent.getComponentInstancesOutputs()
1730 .get(componentInstanceId);
1731 final Optional<ComponentInstanceOutput> componentInstanceOutput = componentInstanceOutputs.stream()
1732 .filter(p -> p.getName().equals(output.getName())).findAny();
1733 if (componentInstanceOutput.isPresent()) {
1734 status = updateComponentInstanceOutput(containerComponent, componentInstanceId, output);
1736 status = addComponentInstanceOutput(containerComponent, componentInstanceId, output);
1738 if (status != StorageOperationStatus.OK) {
1739 log.debug("Failed to update instance output {} for instance {} error {} ", output, componentInstanceId, status);
1740 return Either.right(status);
1742 log.trace("instance output {} for instance {} updated", output, componentInstanceId);
1747 return Either.left(instOutputs);
1750 public Either<Map<String, List<ComponentInstanceProperty>>, StorageOperationStatus> addComponentInstancePropertiesToComponent(
1751 Component containerComponent, Map<String, List<ComponentInstanceProperty>> instProperties) {
1752 requireNonNull(instProperties);
1753 for (Entry<String, List<ComponentInstanceProperty>> entry : instProperties.entrySet()) {
1754 List<ComponentInstanceProperty> props = entry.getValue();
1755 String componentInstanceId = entry.getKey();
1756 List<ComponentInstanceProperty> originalComponentInstProps = containerComponent.getComponentInstancesProperties()
1757 .get(componentInstanceId);
1758 Map<String, List<CapabilityDefinition>> containerComponentCapabilities = containerComponent.getCapabilities();
1759 if (isEmpty(props)) {
1762 for (ComponentInstanceProperty property : props) {
1763 StorageOperationStatus status = null;
1764 String propertyParentUniqueId = property.getParentUniqueId();
1765 Optional<CapabilityDefinition> capPropDefinition = getPropertyCapability(propertyParentUniqueId, containerComponent);
1766 if (capPropDefinition.isPresent() && MapUtils.isNotEmpty(containerComponentCapabilities)) {
1767 status = populateAndUpdateInstanceCapProperty(containerComponent, componentInstanceId, containerComponentCapabilities, property,
1768 capPropDefinition.get());
1770 if (status == null) {
1771 status = updateOrAddComponentInstanceProperty(containerComponent, componentInstanceId, originalComponentInstProps, property);
1773 if (status != StorageOperationStatus.OK) {
1774 return Either.right(status);
1778 return Either.left(instProperties);
1781 public Either<Map<String, List<ComponentInstanceAttribute>>, StorageOperationStatus> addComponentInstanceAttributesToComponent(
1782 final Component containerComponent, final Map<String, List<ComponentInstanceAttribute>> instProperties) {
1783 requireNonNull(instProperties);
1784 for (final Entry<String, List<ComponentInstanceAttribute>> entry : instProperties.entrySet()) {
1785 final List<ComponentInstanceAttribute> props = entry.getValue();
1786 if (isEmpty(props)) {
1789 final String componentInstanceId = entry.getKey();
1790 final List<ComponentInstanceAttribute> originalComponentInstProps = containerComponent.getComponentInstancesAttributes()
1791 .get(componentInstanceId);
1792 for (final ComponentInstanceAttribute property : props) {
1793 final StorageOperationStatus status = updateOrAddComponentInstanceAttribute(containerComponent, componentInstanceId,
1794 originalComponentInstProps, property);
1795 if (status != StorageOperationStatus.OK) {
1796 return Either.right(status);
1800 return Either.left(instProperties);
1803 private StorageOperationStatus populateAndUpdateInstanceCapProperty(Component containerComponent, String componentInstanceId,
1804 Map<String, List<CapabilityDefinition>> containerComponentCapabilities,
1805 ComponentInstanceProperty property,
1806 CapabilityDefinition capabilityDefinition) {
1807 List<CapabilityDefinition> capabilityDefinitions = containerComponentCapabilities.get(capabilityDefinition.getType());
1808 if (CollectionUtils.isEmpty(capabilityDefinitions)) {
1811 Optional<CapabilityDefinition> capDefToGetProp = capabilityDefinitions.stream()
1812 .filter(cap -> cap.getUniqueId().equals(capabilityDefinition.getUniqueId()) && cap.getPath().size() == 1).findAny();
1813 if (capDefToGetProp.isPresent()) {
1814 return updateInstanceCapabilityProperty(containerComponent, componentInstanceId, property, capDefToGetProp.get());
1819 private StorageOperationStatus updateOrAddComponentInstanceProperty(Component containerComponent, String componentInstanceId,
1820 List<ComponentInstanceProperty> originalComponentInstProps,
1821 ComponentInstanceProperty property) {
1822 StorageOperationStatus status;
1823 // check if the property already exists or not
1824 Optional<ComponentInstanceProperty> instanceProperty = originalComponentInstProps.stream()
1825 .filter(p -> p.getUniqueId().equals(property.getUniqueId())).findAny();
1826 if (instanceProperty.isPresent()) {
1827 status = updateComponentInstanceProperty(containerComponent, componentInstanceId, property);
1829 status = addComponentInstanceProperty(containerComponent, componentInstanceId, property);
1831 if (status != StorageOperationStatus.OK) {
1832 log.debug("Failed to update instance property {} for instance {} error {} ", property, componentInstanceId, status);
1837 private StorageOperationStatus updateOrAddComponentInstanceAttribute(Component containerComponent, String componentInstanceId,
1838 List<ComponentInstanceAttribute> originalComponentInstProps,
1839 ComponentInstanceAttribute property) {
1840 StorageOperationStatus status;
1841 // check if the property already exists or not
1842 Optional<ComponentInstanceAttribute> instanceProperty = originalComponentInstProps.stream()
1843 .filter(p -> p.getUniqueId().equals(property.getUniqueId())).findAny();
1844 if (instanceProperty.isPresent()) {
1845 status = updateComponentInstanceAttribute(containerComponent, componentInstanceId, property);
1847 status = addComponentInstanceAttribute(containerComponent, componentInstanceId, property);
1849 if (status != StorageOperationStatus.OK) {
1850 log.debug("Failed to update instance property {} for instance {} error {} ", property, componentInstanceId, status);
1855 public StorageOperationStatus updateInstanceCapabilityProperty(Component containerComponent, String componentInstanceId,
1856 ComponentInstanceProperty property, CapabilityDefinition capabilityDefinition) {
1857 Optional<ComponentInstance> fetchedCIOptional = containerComponent.getComponentInstanceById(componentInstanceId);
1858 if (!fetchedCIOptional.isPresent()) {
1859 return StorageOperationStatus.GENERAL_ERROR;
1861 Either<Component, StorageOperationStatus> getComponentRes = getToscaFullElement(fetchedCIOptional.get().getComponentUid());
1862 if (getComponentRes.isRight()) {
1863 return StorageOperationStatus.GENERAL_ERROR;
1865 Optional<Component> componentOptional = isNodeServiceProxy(getComponentRes.left().value());
1867 if (!componentOptional.isPresent()) {
1868 propOwner = componentInstanceId;
1870 propOwner = fetchedCIOptional.get().getSourceModelUid();
1872 StorageOperationStatus status;
1873 StringBuilder sb = new StringBuilder(componentInstanceId);
1874 sb.append(ModelConverter.CAP_PROP_DELIM).append(propOwner).append(ModelConverter.CAP_PROP_DELIM).append(capabilityDefinition.getType())
1875 .append(ModelConverter.CAP_PROP_DELIM).append(capabilityDefinition.getName());
1876 String capKey = sb.toString();
1877 status = updateComponentInstanceCapabiltyProperty(containerComponent, componentInstanceId, capKey, property);
1878 if (status != StorageOperationStatus.OK) {
1879 log.debug("Failed to update instance capability property {} for instance {} error {} ", property, componentInstanceId, status);
1882 return StorageOperationStatus.OK;
1885 private Optional<Component> isNodeServiceProxy(Component component) {
1886 if (component.getComponentType().equals(ComponentTypeEnum.SERVICE)) {
1887 return Optional.empty();
1889 Resource resource = (Resource) component;
1890 ResourceTypeEnum resType = resource.getResourceType();
1891 if (resType.equals(ResourceTypeEnum.ServiceProxy)) {
1892 return Optional.of(component);
1894 return Optional.empty();
1897 public StorageOperationStatus associateCapabilitiesToService(Map<String, ListCapabilityDataDefinition> capabilities, String componentId) {
1898 Either<GraphVertex, JanusGraphOperationStatus> getVertexEither = janusGraphDao.getVertexById(componentId, JsonParseFlagEnum.NoParse);
1899 if (getVertexEither.isRight()) {
1900 log.debug(COULDNT_FETCH_COMPONENT_WITH_AND_UNIQUE_ID_ERROR, componentId, getVertexEither.right().value());
1901 return DaoStatusConverter.convertJanusGraphStatusToStorageStatus(getVertexEither.right().value());
1903 GraphVertex vertex = getVertexEither.left().value();
1904 if (MapUtils.isNotEmpty(capabilities)) {
1905 Either<GraphVertex, StorageOperationStatus> associateElementToData = topologyTemplateOperation
1906 .associateElementToData(vertex, VertexTypeEnum.CAPABILITIES, EdgeLabelEnum.CAPABILITIES, capabilities);
1907 if (associateElementToData.isRight()) {
1908 return associateElementToData.right().value();
1911 return StorageOperationStatus.OK;
1914 public StorageOperationStatus associateRequirementsToService(Map<String, ListRequirementDataDefinition> requirements, String componentId) {
1915 Either<GraphVertex, JanusGraphOperationStatus> getVertexEither = janusGraphDao.getVertexById(componentId, JsonParseFlagEnum.NoParse);
1916 if (getVertexEither.isRight()) {
1917 log.debug(COULDNT_FETCH_COMPONENT_WITH_AND_UNIQUE_ID_ERROR, componentId, getVertexEither.right().value());
1918 return DaoStatusConverter.convertJanusGraphStatusToStorageStatus(getVertexEither.right().value());
1920 GraphVertex vertex = getVertexEither.left().value();
1921 if (MapUtils.isNotEmpty(requirements)) {
1922 Either<GraphVertex, StorageOperationStatus> associateElementToData = topologyTemplateOperation
1923 .associateElementToData(vertex, VertexTypeEnum.REQUIREMENTS, EdgeLabelEnum.REQUIREMENTS, requirements);
1924 if (associateElementToData.isRight()) {
1925 return associateElementToData.right().value();
1928 return StorageOperationStatus.OK;
1931 public StorageOperationStatus associateDeploymentArtifactsToInstances(Map<String, Map<String, ArtifactDefinition>> instDeploymentArtifacts,
1932 Component component, User user) {
1933 Either<GraphVertex, JanusGraphOperationStatus> getVertexEither = janusGraphDao
1934 .getVertexById(component.getUniqueId(), JsonParseFlagEnum.NoParse);
1935 if (getVertexEither.isRight()) {
1936 log.debug(COULDNT_FETCH_COMPONENT_WITH_AND_UNIQUE_ID_ERROR, component.getUniqueId(), getVertexEither.right().value());
1937 return DaoStatusConverter.convertJanusGraphStatusToStorageStatus(getVertexEither.right().value());
1939 GraphVertex vertex = getVertexEither.left().value();
1940 Map<String, MapArtifactDataDefinition> instArtMap = new HashMap<>();
1941 if (instDeploymentArtifacts != null) {
1942 MapArtifactDataDefinition artifactsMap;
1943 for (Entry<String, Map<String, ArtifactDefinition>> entry : instDeploymentArtifacts.entrySet()) {
1944 Map<String, ArtifactDefinition> artList = entry.getValue();
1945 Map<String, ArtifactDataDefinition> artifacts = artList.entrySet().stream()
1946 .collect(Collectors.toMap(Map.Entry::getKey, e -> new ArtifactDataDefinition(e.getValue())));
1947 artifactsMap = nodeTemplateOperation
1948 .prepareInstDeploymentArtifactPerInstance(artifacts, entry.getKey(), user, NodeTemplateOperation.HEAT_VF_ENV_NAME);
1949 instArtMap.put(entry.getKey(), artifactsMap);
1952 ModelConverter.setComponentInstancesDeploymentArtifactsToComponent(instArtMap, component);
1953 return topologyTemplateOperation.associateInstDeploymentArtifactsToComponent(vertex, instArtMap);
1956 public StorageOperationStatus associateArtifactsToInstances(Map<String, Map<String, ArtifactDefinition>> instArtifacts, Component component) {
1957 Either<GraphVertex, JanusGraphOperationStatus> getVertexEither = janusGraphDao
1958 .getVertexById(component.getUniqueId(), JsonParseFlagEnum.NoParse);
1959 if (getVertexEither.isRight()) {
1960 log.debug(COULDNT_FETCH_COMPONENT_WITH_AND_UNIQUE_ID_ERROR, component.getUniqueId(), getVertexEither.right().value());
1961 return DaoStatusConverter.convertJanusGraphStatusToStorageStatus(getVertexEither.right().value());
1963 GraphVertex vertex = getVertexEither.left().value();
1964 Map<String, MapArtifactDataDefinition> instArtMap = new HashMap<>();
1965 if (instArtifacts != null) {
1966 MapArtifactDataDefinition artifactsMap;
1967 for (Entry<String, Map<String, ArtifactDefinition>> entry : instArtifacts.entrySet()) {
1968 Map<String, ArtifactDefinition> artList = entry.getValue();
1969 Map<String, ArtifactDataDefinition> artifacts = artList.entrySet().stream()
1970 .collect(Collectors.toMap(Map.Entry::getKey, e -> new ArtifactDataDefinition(e.getValue())));
1971 artifactsMap = new MapArtifactDataDefinition(artifacts);
1972 instArtMap.put(entry.getKey(), artifactsMap);
1975 ModelConverter.setComponentInstancesInformationalArtifactsToComponent(instArtMap, component);
1976 return topologyTemplateOperation.associateInstArtifactsToComponent(vertex, instArtMap);
1979 public StorageOperationStatus associateInstAttributeToComponentToInstances(Map<String, List<AttributeDefinition>> instArttributes,
1980 Component component) {
1981 Either<GraphVertex, JanusGraphOperationStatus> getVertexEither = janusGraphDao
1982 .getVertexById(component.getUniqueId(), JsonParseFlagEnum.NoParse);
1983 if (getVertexEither.isRight()) {
1984 log.debug(COULDNT_FETCH_COMPONENT_WITH_AND_UNIQUE_ID_ERROR, component.getUniqueId(), getVertexEither.right().value());
1985 return DaoStatusConverter.convertJanusGraphStatusToStorageStatus(getVertexEither.right().value());
1987 GraphVertex vertex = getVertexEither.left().value();
1988 Map<String, MapAttributesDataDefinition> instAttr = new HashMap<>();
1989 if (instArttributes != null) {
1990 MapAttributesDataDefinition attributesMap;
1991 for (Entry<String, List<AttributeDefinition>> entry : instArttributes.entrySet()) {
1992 final List<AttributeDefinition> value = entry.getValue();
1993 attributesMap = new MapAttributesDataDefinition();
1994 attributesMap.setMapToscaDataDefinition(
1995 value.stream().map(AttributeDefinition::new).collect(Collectors.toMap(AttributeDefinition::getName, e -> e)));
1996 instAttr.put(entry.getKey(), attributesMap);
1999 setComponentInstanceAttributesOnComponent(component, instAttr);
2000 return topologyTemplateOperation.associateInstAttributeToComponent(vertex, instAttr);
2004 private void setComponentInstanceAttributesOnComponent(Component resource, Map<String, MapAttributesDataDefinition> instAttr) {
2005 Map<String, List<ComponentInstanceAttribute>> componentInstancesAttributes = resource.getComponentInstancesAttributes();
2006 if (componentInstancesAttributes == null) {
2007 componentInstancesAttributes = new HashMap<>();
2009 componentInstancesAttributes.putAll(ModelConverter.getComponentInstancesAttributes(instAttr));
2010 resource.setComponentInstancesAttributes(componentInstancesAttributes);
2013 public StorageOperationStatus associateOrAddCalculatedCapReq(Map<ComponentInstance, Map<String, List<CapabilityDefinition>>> instCapabilties,
2014 Map<ComponentInstance, Map<String, List<RequirementDefinition>>> instReg,
2015 Component component) {
2016 Either<GraphVertex, JanusGraphOperationStatus> getVertexEither = janusGraphDao
2017 .getVertexById(component.getUniqueId(), JsonParseFlagEnum.NoParse);
2018 if (getVertexEither.isRight()) {
2019 log.debug(COULDNT_FETCH_COMPONENT_WITH_AND_UNIQUE_ID_ERROR, component.getUniqueId(), getVertexEither.right().value());
2020 return DaoStatusConverter.convertJanusGraphStatusToStorageStatus(getVertexEither.right().value());
2022 GraphVertex vertex = getVertexEither.left().value();
2023 Map<String, MapListRequirementDataDefinition> calcRequirements = new HashMap<>();
2024 Map<String, MapListCapabilityDataDefinition> calcCapabilty = new HashMap<>();
2025 Map<String, MapCapabilityProperty> calculatedCapabilitiesProperties = new HashMap<>();
2026 if (instCapabilties != null) {
2027 for (Entry<ComponentInstance, Map<String, List<CapabilityDefinition>>> entry : instCapabilties.entrySet()) {
2028 Map<String, List<CapabilityDefinition>> caps = entry.getValue();
2029 Map<String, ListCapabilityDataDefinition> mapToscaDataDefinition = new HashMap<>();
2030 for (Entry<String, List<CapabilityDefinition>> instCapability : caps.entrySet()) {
2031 mapToscaDataDefinition.put(instCapability.getKey(), new ListCapabilityDataDefinition(
2032 instCapability.getValue().stream().map(CapabilityDataDefinition::new).collect(Collectors.toList())));
2034 ComponentInstanceDataDefinition componentInstance = new ComponentInstanceDataDefinition(entry.getKey());
2035 MapListCapabilityDataDefinition capMap = nodeTemplateOperation
2036 .prepareCalculatedCapabiltyForNodeType(mapToscaDataDefinition, componentInstance);
2037 MapCapabilityProperty mapCapabilityProperty = ModelConverter
2038 .convertToMapOfMapCapabiltyProperties(caps, componentInstance.getUniqueId(), true);
2039 calcCapabilty.put(entry.getKey().getUniqueId(), capMap);
2040 calculatedCapabilitiesProperties.put(entry.getKey().getUniqueId(), mapCapabilityProperty);
2043 if (instReg != null) {
2044 for (Entry<ComponentInstance, Map<String, List<RequirementDefinition>>> entry : instReg.entrySet()) {
2045 Map<String, List<RequirementDefinition>> req = entry.getValue();
2046 Map<String, ListRequirementDataDefinition> mapToscaDataDefinition = new HashMap<>();
2047 for (Entry<String, List<RequirementDefinition>> instReq : req.entrySet()) {
2048 mapToscaDataDefinition.put(instReq.getKey(), new ListRequirementDataDefinition(
2049 instReq.getValue().stream().map(RequirementDataDefinition::new).collect(Collectors.toList())));
2051 MapListRequirementDataDefinition reqMap = nodeTemplateOperation
2052 .prepareCalculatedRequirementForNodeType(mapToscaDataDefinition, new ComponentInstanceDataDefinition(entry.getKey()));
2053 String componentInstanceId = entry.getKey().getUniqueId();
2054 calcRequirements.put(componentInstanceId, reqMap);
2057 StorageOperationStatus storageOperationStatus = topologyTemplateOperation
2058 .associateOrAddCalcCapReqToComponent(vertex, calcRequirements, calcCapabilty, calculatedCapabilitiesProperties);
2059 updateInstancesCapAndReqOnComponentFromDB(component);
2060 return storageOperationStatus;
2063 public StorageOperationStatus updateCalculatedCapabilitiesRequirements(
2064 final Map<ComponentInstance, Map<String, List<CapabilityDefinition>>> instCapabilties,
2065 final Map<ComponentInstance, Map<String, List<RequirementDefinition>>> instReg,
2066 final Component component) {
2067 StorageOperationStatus storageOperationStatus = StorageOperationStatus.OK;
2068 if (instCapabilties != null) {
2069 for (Entry<ComponentInstance, Map<String, List<CapabilityDefinition>>> entry : instCapabilties.entrySet()) {
2070 final Map<String, List<CapabilityDefinition>> cap = entry.getValue();
2071 for (List<CapabilityDefinition> capabilityList : cap.values()) {
2072 for (CapabilityDefinition capability : capabilityList) {
2073 nodeTemplateOperation.updateComponentInstanceCapabilities(component.getUniqueId(), entry.getKey().getUniqueId(), capability);
2078 if (instReg != null) {
2079 for (Entry<ComponentInstance, Map<String, List<RequirementDefinition>>> entry : instReg.entrySet()) {
2080 final Map<String, List<RequirementDefinition>> req = entry.getValue();
2081 for (List<RequirementDefinition> requirementList : req.values()) {
2082 for (RequirementDefinition requirement : requirementList) {
2083 storageOperationStatus = nodeTemplateOperation.updateComponentInstanceRequirement(component.getUniqueId(),
2084 entry.getKey().getUniqueId(), requirement);
2085 if (storageOperationStatus != StorageOperationStatus.OK) {
2086 return storageOperationStatus;
2092 return storageOperationStatus;
2095 private void updateInstancesCapAndReqOnComponentFromDB(Component component) {
2096 ComponentParametersView componentParametersView = new ComponentParametersView(true);
2097 componentParametersView.setIgnoreCapabilities(false);
2098 componentParametersView.setIgnoreRequirements(false);
2099 componentParametersView.setIgnoreCapabiltyProperties(false);
2100 componentParametersView.setIgnoreComponentInstances(false);
2101 Either<Component, StorageOperationStatus> componentEither = getToscaElement(component.getUniqueId(), componentParametersView);
2102 if (componentEither.isRight()) {
2103 throw new StorageException(StorageOperationStatus.NOT_FOUND);
2105 Component updatedComponent = componentEither.left().value();
2106 component.setCapabilities(updatedComponent.getCapabilities());
2107 component.setRequirements(updatedComponent.getRequirements());
2108 component.setComponentInstancesRelations(updatedComponent.getComponentInstancesRelations());
2109 component.setComponentInstances(updatedComponent.getComponentInstances());
2112 private Either<List<Service>, StorageOperationStatus> getLatestVersionNonCheckoutServicesMetadataOnly(Map<GraphPropertyEnum, Object> hasProps,
2113 Map<GraphPropertyEnum, Object> hasNotProps,
2115 List<Service> services = new ArrayList<>();
2116 List<LifecycleStateEnum> states = new ArrayList<>();
2118 hasProps.put(GraphPropertyEnum.COMPONENT_TYPE, ComponentTypeEnum.SERVICE.name());
2119 hasProps.put(GraphPropertyEnum.IS_HIGHEST_VERSION, true);
2120 if (modelName != null) {
2121 hasProps.put(GraphPropertyEnum.MODEL, modelName);
2124 states.add(LifecycleStateEnum.NOT_CERTIFIED_CHECKOUT);
2125 hasNotProps.put(GraphPropertyEnum.STATE, states);
2126 hasNotProps.put(GraphPropertyEnum.IS_DELETED, true);
2127 hasNotProps.put(GraphPropertyEnum.IS_ARCHIVED, true);
2128 return fetchServicesByCriteria(services, hasProps, hasNotProps, modelName);
2131 private Either<List<Component>, StorageOperationStatus> getLatestVersionNotAbstractToscaElementsMetadataOnly(final boolean isAbstract,
2132 final ComponentTypeEnum componentTypeEnum,
2133 final String internalComponentType,
2134 final VertexTypeEnum vertexType,
2135 final String modelName,
2136 final boolean includeNormativeExtensionModels) {
2137 List<Service> services = null;
2138 Map<GraphPropertyEnum, Object> hasProps = new EnumMap<>(GraphPropertyEnum.class);
2139 Map<GraphPropertyEnum, Object> hasNotProps = new EnumMap<>(GraphPropertyEnum.class);
2140 fillPropsMap(hasProps, hasNotProps, internalComponentType, componentTypeEnum, isAbstract, vertexType, modelName);
2141 Either<List<GraphVertex>, JanusGraphOperationStatus> getRes = janusGraphDao
2142 .getByCriteria(vertexType, hasProps, hasNotProps, JsonParseFlagEnum.ParseMetadata, modelName, includeNormativeExtensionModels);
2143 if (getRes.isRight() && !JanusGraphOperationStatus.NOT_FOUND.equals(getRes.right().value())) {
2144 return Either.right(DaoStatusConverter.convertJanusGraphStatusToStorageStatus(getRes.right().value()));
2146 // region -> Fetch non checked-out services
2147 if (internalComponentType != null && internalComponentType.toLowerCase().trim().equals(SERVICE) && VertexTypeEnum.NODE_TYPE == vertexType) {
2148 Either<List<Service>, StorageOperationStatus> result = getLatestVersionNonCheckoutServicesMetadataOnly(
2149 new EnumMap<>(GraphPropertyEnum.class), new EnumMap<>(GraphPropertyEnum.class), modelName);
2150 if (result.isRight()) {
2151 log.debug("Failed to fetch services for");
2152 return Either.right(result.right().value());
2154 services = result.left().value();
2155 if (log.isTraceEnabled() && isEmpty(services)) {
2156 log.trace("No relevant services available");
2160 List<Component> nonAbstractLatestComponents = new ArrayList<>();
2161 ComponentParametersView params = new ComponentParametersView(true);
2162 params.setIgnoreAllVersions(false);
2163 if (getRes.isLeft()) {
2164 for (GraphVertex vertexComponent : getRes.left().value()) {
2165 Either<ToscaElement, StorageOperationStatus> componentRes = topologyTemplateOperation
2166 .getLightComponent(vertexComponent, componentTypeEnum, params);
2167 if (componentRes.isRight()) {
2168 log.debug("Failed to fetch light element for {} error {}", vertexComponent.getUniqueId(), componentRes.right().value());
2169 return Either.right(componentRes.right().value());
2171 Component component = ModelConverter.convertFromToscaElement(componentRes.left().value());
2172 nonAbstractLatestComponents.add(component);
2176 if (CollectionUtils.isNotEmpty(services)) {
2177 nonAbstractLatestComponents.addAll(services);
2179 return Either.left(nonAbstractLatestComponents);
2182 public Either<ComponentMetadataData, StorageOperationStatus> getLatestComponentMetadataByUuid(String componentUuid, JsonParseFlagEnum parseFlag,
2183 Boolean isHighest) {
2184 Either<ComponentMetadataData, StorageOperationStatus> result;
2185 Map<GraphPropertyEnum, Object> hasProperties = new EnumMap<>(GraphPropertyEnum.class);
2186 hasProperties.put(GraphPropertyEnum.UUID, componentUuid);
2187 if (isHighest != null) {
2188 hasProperties.put(GraphPropertyEnum.IS_HIGHEST_VERSION, isHighest);
2190 Map<GraphPropertyEnum, Object> propertiesNotToMatch = new EnumMap<>(GraphPropertyEnum.class);
2191 propertiesNotToMatch.put(GraphPropertyEnum.IS_DELETED, true);
2192 propertiesNotToMatch.put(GraphPropertyEnum.IS_ARCHIVED, true); //US382674, US382683
2193 Either<List<GraphVertex>, JanusGraphOperationStatus> getRes = janusGraphDao
2194 .getByCriteria(null, hasProperties, propertiesNotToMatch, parseFlag);
2195 if (getRes.isRight()) {
2196 result = Either.right(DaoStatusConverter.convertJanusGraphStatusToStorageStatus(getRes.right().value()));
2198 List<ComponentMetadataData> latestVersionList = getRes.left().value().stream().map(ModelConverter::convertToComponentMetadata)
2199 .collect(Collectors.toList());
2200 ComponentMetadataData latestVersion = latestVersionList.size() == 1 ? latestVersionList.get(0) : latestVersionList.stream().max(
2201 (c1, c2) -> Double.compare(Double.parseDouble(c1.getMetadataDataDefinition().getVersion()),
2202 Double.parseDouble(c2.getMetadataDataDefinition().getVersion()))).get();
2203 result = Either.left(latestVersion);
2208 public Either<ComponentMetadataData, StorageOperationStatus> getComponentMetadata(String componentId) {
2209 Either<ComponentMetadataData, StorageOperationStatus> result;
2210 Either<GraphVertex, JanusGraphOperationStatus> getRes = janusGraphDao.getVertexById(componentId, JsonParseFlagEnum.ParseMetadata);
2211 if (getRes.isRight()) {
2212 result = Either.right(DaoStatusConverter.convertJanusGraphStatusToStorageStatus(getRes.right().value()));
2214 ComponentMetadataData componentMetadata = ModelConverter.convertToComponentMetadata(getRes.left().value());
2215 result = Either.left(componentMetadata);
2220 public Either<List<Component>, StorageOperationStatus> getLatestVersionNotAbstractComponents(boolean isAbstract,
2221 ComponentTypeEnum componentTypeEnum,
2222 String internalComponentType,
2223 List<String> componentUids) {
2224 List<Component> components = new ArrayList<>();
2225 if (componentUids == null) {
2226 Either<List<String>, StorageOperationStatus> componentUidsRes = getComponentUids(isAbstract, componentTypeEnum, internalComponentType);
2227 if (componentUidsRes.isRight()) {
2228 return Either.right(componentUidsRes.right().value());
2230 componentUids = componentUidsRes.left().value();
2232 if (!isEmpty(componentUids)) {
2233 for (String componentUid : componentUids) {
2234 ComponentParametersView componentParametersView = buildComponentViewForNotAbstract();
2235 if ("vl".equalsIgnoreCase(internalComponentType)) {
2236 componentParametersView.setIgnoreCapabilities(false);
2237 componentParametersView.setIgnoreRequirements(false);
2239 Either<ToscaElement, StorageOperationStatus> getToscaElementRes = nodeTemplateOperation.getToscaElementOperation(componentTypeEnum)
2240 .getLightComponent(componentUid, componentTypeEnum, componentParametersView);
2241 if (getToscaElementRes.isRight()) {
2242 log.debug("Failed to fetch resource for error is {}", getToscaElementRes.right().value());
2243 return Either.right(getToscaElementRes.right().value());
2245 Component component = ModelConverter.convertFromToscaElement(getToscaElementRes.left().value());
2246 nullifySomeComponentProperties(component);
2247 components.add(component);
2250 return Either.left(components);
2253 public void nullifySomeComponentProperties(Component component) {
2254 component.setContactId(null);
2255 component.setCreationDate(null);
2256 component.setCreatorUserId(null);
2257 component.setCreatorFullName(null);
2258 component.setLastUpdateDate(null);
2259 component.setLastUpdaterUserId(null);
2260 component.setLastUpdaterFullName(null);
2261 component.setNormalizedName(null);
2264 private Either<List<String>, StorageOperationStatus> getComponentUids(boolean isAbstract, ComponentTypeEnum componentTypeEnum,
2265 String internalComponentType) {
2266 Either<List<Component>, StorageOperationStatus> getToscaElementsRes = getLatestVersionNotAbstractMetadataOnly(isAbstract, componentTypeEnum,
2267 internalComponentType, null, false);
2268 if (getToscaElementsRes.isRight()) {
2269 return Either.right(getToscaElementsRes.right().value());
2271 List<Component> collection = getToscaElementsRes.left().value();
2272 List<String> componentUids;
2273 if (collection == null) {
2274 componentUids = new ArrayList<>();
2276 componentUids = collection.stream().map(Component::getUniqueId).collect(Collectors.toList());
2278 return Either.left(componentUids);
2281 private ComponentParametersView buildComponentViewForNotAbstract() {
2282 ComponentParametersView componentParametersView = new ComponentParametersView();
2283 componentParametersView.disableAll();
2284 componentParametersView.setIgnoreCategories(false);
2285 componentParametersView.setIgnoreAllVersions(false);
2286 return componentParametersView;
2289 public Either<Boolean, StorageOperationStatus> validateComponentNameExists(String name, ResourceTypeEnum resourceType,
2290 ComponentTypeEnum componentType) {
2291 Either<Boolean, StorageOperationStatus> result = validateComponentNameUniqueness(name, resourceType, componentType);
2292 if (result.isLeft()) {
2293 result = Either.left(!result.left().value());
2298 public Either<Boolean, StorageOperationStatus> validateComponentNameUniqueness(String name, ResourceTypeEnum resourceType,
2299 ComponentTypeEnum componentType) {
2300 String normalizedName = ValidationUtils.normaliseComponentName(name);
2301 Either<List<GraphVertex>, JanusGraphOperationStatus> vertexEither = janusGraphDao
2302 .getByCriteria(getVertexTypeEnum(resourceType), propertiesToMatch(normalizedName, componentType), JsonParseFlagEnum.NoParse);
2303 if (vertexEither.isRight() && vertexEither.right().value() != JanusGraphOperationStatus.NOT_FOUND) {
2304 log.debug("failed to get vertex from graph with property normalizedName: {}", normalizedName);
2305 return Either.right(DaoStatusConverter.convertJanusGraphStatusToStorageStatus(vertexEither.right().value()));
2307 return Either.left(CollectionUtils.isEmpty(vertexEither.isLeft() ? vertexEither.left().value() : null));
2310 public Either<Boolean, StorageOperationStatus> validateComponentNameAndModelExists(final String resourceName, final String model,
2311 final ResourceTypeEnum resourceType,
2312 final ComponentTypeEnum componentType) {
2313 Either<Boolean, StorageOperationStatus> result = validateComponentNameAndModelUniqueness(resourceName, model, resourceType, componentType);
2314 if (result.isLeft()) {
2315 result = Either.left(!result.left().value());
2320 private Either<Boolean, StorageOperationStatus> validateComponentNameAndModelUniqueness(final String resourceName, final String modelName,
2321 final ResourceTypeEnum resourceType,
2322 final ComponentTypeEnum componentType) {
2323 final String normalizedName = ValidationUtils.normaliseComponentName(resourceName);
2324 final Either<List<GraphVertex>, JanusGraphOperationStatus> vertexEither = janusGraphDao
2325 .getByCriteria(getVertexTypeEnum(resourceType), propertiesToMatch(normalizedName, componentType), null, null, JsonParseFlagEnum.NoParse,
2327 if (vertexEither.isRight() && vertexEither.right().value() != JanusGraphOperationStatus.NOT_FOUND) {
2328 log.debug("failed to get vertex from graph with property normalizedName: {} and model: {}", normalizedName, modelName);
2329 return Either.right(DaoStatusConverter.convertJanusGraphStatusToStorageStatus(vertexEither.right().value()));
2331 return Either.left(CollectionUtils.isEmpty(vertexEither.isLeft() ? vertexEither.left().value().stream()
2332 .collect(Collectors.toList()) : null));
2335 private VertexTypeEnum getVertexTypeEnum(final ResourceTypeEnum resourceType) {
2336 return ModelConverter.isAtomicComponent(resourceType) ? VertexTypeEnum.NODE_TYPE : VertexTypeEnum.TOPOLOGY_TEMPLATE;
2339 private Map<GraphPropertyEnum, Object> propertiesToMatch(final String normalizedName, final ComponentTypeEnum componentType) {
2340 final Map<GraphPropertyEnum, Object> properties = new EnumMap<>(GraphPropertyEnum.class);
2341 properties.put(GraphPropertyEnum.NORMALIZED_NAME, normalizedName);
2342 properties.put(GraphPropertyEnum.COMPONENT_TYPE, componentType.name());
2346 private void fillNodeTypePropsMap(final Map<GraphPropertyEnum, Object> hasProps, final Map<GraphPropertyEnum, Object> hasNotProps,
2347 final String internalComponentType, String modelName) {
2348 final Configuration configuration = ConfigurationManager.getConfigurationManager().getConfiguration();
2349 final List<String> allowedTypes;
2350 if (ComponentTypeEnum.SERVICE.getValue().equalsIgnoreCase(internalComponentType)) {
2351 allowedTypes = containerInstanceTypesData.getServiceAllowedList(modelName);
2353 final ResourceTypeEnum resourceType = ResourceTypeEnum.getTypeIgnoreCase(internalComponentType);
2354 allowedTypes = containerInstanceTypesData.getComponentAllowedList(ComponentTypeEnum.RESOURCE, resourceType);
2356 final List<String> allResourceTypes = configuration.getResourceTypes();
2357 if (allowedTypes == null) {
2358 hasNotProps.put(GraphPropertyEnum.RESOURCE_TYPE, allResourceTypes);
2361 if (ResourceTypeEnum.VL.getValue().equalsIgnoreCase(internalComponentType)) {
2362 hasProps.put(GraphPropertyEnum.RESOURCE_TYPE, allowedTypes);
2364 final List<String> notAllowedTypes = allResourceTypes.stream().filter(s -> !allowedTypes.contains(s)).collect(Collectors.toList());
2365 hasNotProps.put(GraphPropertyEnum.RESOURCE_TYPE, notAllowedTypes);
2369 private void fillTopologyTemplatePropsMap(Map<GraphPropertyEnum, Object> hasProps, Map<GraphPropertyEnum, Object> hasNotProps,
2370 ComponentTypeEnum componentTypeEnum) {
2371 switch (componentTypeEnum) {
2373 hasProps.put(GraphPropertyEnum.COMPONENT_TYPE, ComponentTypeEnum.RESOURCE.name());
2376 hasProps.put(GraphPropertyEnum.COMPONENT_TYPE, ComponentTypeEnum.SERVICE.name());
2381 hasNotProps.put(GraphPropertyEnum.RESOURCE_TYPE, ResourceTypeEnum.CVFC.name());
2384 private void fillPropsMap(Map<GraphPropertyEnum, Object> hasProps, Map<GraphPropertyEnum, Object> hasNotProps, String internalComponentType,
2385 ComponentTypeEnum componentTypeEnum, boolean isAbstract, VertexTypeEnum internalVertexType, String modelName) {
2386 hasNotProps.put(GraphPropertyEnum.STATE, LifecycleStateEnum.NOT_CERTIFIED_CHECKOUT.name());
2387 hasNotProps.put(GraphPropertyEnum.IS_DELETED, true);
2388 hasNotProps.put(GraphPropertyEnum.IS_ARCHIVED, true);
2389 hasProps.put(GraphPropertyEnum.IS_HIGHEST_VERSION, true);
2391 if (VertexTypeEnum.NODE_TYPE == internalVertexType) {
2392 hasProps.put(GraphPropertyEnum.IS_ABSTRACT, isAbstract);
2393 if (internalComponentType != null) {
2394 fillNodeTypePropsMap(hasProps, hasNotProps, internalComponentType, modelName);
2397 fillTopologyTemplatePropsMap(hasProps, hasNotProps, componentTypeEnum);
2401 private List<VertexTypeEnum> getInternalVertexTypes(ComponentTypeEnum componentTypeEnum, String internalComponentType) {
2402 List<VertexTypeEnum> internalVertexTypes = new ArrayList<>();
2403 if (ComponentTypeEnum.RESOURCE == componentTypeEnum) {
2404 internalVertexTypes.add(VertexTypeEnum.NODE_TYPE);
2406 if (ComponentTypeEnum.SERVICE == componentTypeEnum || SERVICE.equalsIgnoreCase(internalComponentType) || VF.equalsIgnoreCase(
2407 internalComponentType)) {
2408 internalVertexTypes.add(VertexTypeEnum.TOPOLOGY_TEMPLATE);
2410 return internalVertexTypes;
2413 public Either<List<Component>, StorageOperationStatus> getLatestVersionNotAbstractMetadataOnly(boolean isAbstract,
2414 final ComponentTypeEnum componentTypeEnum,
2415 final String internalComponentType,
2416 final String modelName,
2417 final boolean includeNormativeExtensionModels) {
2418 List<VertexTypeEnum> internalVertexTypes = getInternalVertexTypes(componentTypeEnum, internalComponentType);
2419 List<Component> result = new ArrayList<>();
2420 for (VertexTypeEnum vertexType : internalVertexTypes) {
2421 Either<List<Component>, StorageOperationStatus> listByVertexType = getLatestVersionNotAbstractToscaElementsMetadataOnly(isAbstract,
2422 componentTypeEnum, internalComponentType, vertexType, modelName, includeNormativeExtensionModels);
2423 if (listByVertexType.isRight()) {
2424 return listByVertexType;
2426 result.addAll(listByVertexType.left().value());
2428 return Either.left(result);
2431 private Either<List<Component>, StorageOperationStatus> getLatestComponentListByUuid(String componentUuid,
2432 Map<GraphPropertyEnum, Object> additionalPropertiesToMatch) {
2433 Map<GraphPropertyEnum, Object> propertiesToMatch = new EnumMap<>(GraphPropertyEnum.class);
2434 if (additionalPropertiesToMatch != null) {
2435 propertiesToMatch.putAll(additionalPropertiesToMatch);
2437 propertiesToMatch.put(GraphPropertyEnum.IS_HIGHEST_VERSION, true);
2438 return getComponentListByUuid(componentUuid, propertiesToMatch);
2441 public Either<Component, StorageOperationStatus> getComponentByUuidAndVersion(String componentUuid, String version) {
2442 Map<GraphPropertyEnum, Object> propertiesToMatch = new EnumMap<>(GraphPropertyEnum.class);
2443 propertiesToMatch.put(GraphPropertyEnum.UUID, componentUuid);
2444 propertiesToMatch.put(GraphPropertyEnum.VERSION, version);
2445 Map<GraphPropertyEnum, Object> propertiesNotToMatch = new EnumMap<>(GraphPropertyEnum.class);
2446 propertiesNotToMatch.put(GraphPropertyEnum.IS_DELETED, true);
2447 Either<List<GraphVertex>, JanusGraphOperationStatus> vertexEither = janusGraphDao
2448 .getByCriteria(null, propertiesToMatch, propertiesNotToMatch, JsonParseFlagEnum.ParseAll);
2449 if (vertexEither.isRight()) {
2450 return Either.right(DaoStatusConverter.convertJanusGraphStatusToStorageStatus(vertexEither.right().value()));
2452 List<GraphVertex> vertexList = vertexEither.isLeft() ? vertexEither.left().value() : null;
2453 if (vertexList == null || vertexList.isEmpty() || vertexList.size() > 1) {
2454 return Either.right(StorageOperationStatus.NOT_FOUND);
2456 return getToscaElementByOperation(vertexList.get(0));
2459 public Either<List<Component>, StorageOperationStatus> getComponentListByUuid(String componentUuid,
2460 Map<GraphPropertyEnum, Object> additionalPropertiesToMatch) {
2461 Map<GraphPropertyEnum, Object> propertiesToMatch = new EnumMap<>(GraphPropertyEnum.class);
2462 if (additionalPropertiesToMatch != null) {
2463 propertiesToMatch.putAll(additionalPropertiesToMatch);
2465 propertiesToMatch.put(GraphPropertyEnum.UUID, componentUuid);
2466 Map<GraphPropertyEnum, Object> propertiesNotToMatch = new EnumMap<>(GraphPropertyEnum.class);
2467 propertiesNotToMatch.put(GraphPropertyEnum.IS_DELETED, true);
2468 propertiesNotToMatch.put(GraphPropertyEnum.IS_ARCHIVED, true); //US382674, US382683
2469 Either<List<GraphVertex>, JanusGraphOperationStatus> vertexEither = janusGraphDao
2470 .getByCriteria(null, propertiesToMatch, propertiesNotToMatch, JsonParseFlagEnum.ParseAll);
2471 if (vertexEither.isRight()) {
2472 log.debug("Couldn't fetch metadata for component with uuid {}, error: {}", componentUuid, vertexEither.right().value());
2473 return Either.right(DaoStatusConverter.convertJanusGraphStatusToStorageStatus(vertexEither.right().value()));
2475 List<GraphVertex> vertexList = vertexEither.isLeft() ? vertexEither.left().value() : null;
2476 if (vertexList == null || vertexList.isEmpty()) {
2477 log.debug("Component with uuid {} was not found", componentUuid);
2478 return Either.right(StorageOperationStatus.NOT_FOUND);
2480 ArrayList<Component> latestComponents = new ArrayList<>();
2481 for (GraphVertex vertex : vertexList) {
2482 Either<Component, StorageOperationStatus> toscaElementByOperation = getToscaElementByOperation(vertex);
2483 if (toscaElementByOperation.isRight()) {
2484 log.debug("Could not fetch the following Component by UUID {}", vertex.getUniqueId());
2485 return Either.right(toscaElementByOperation.right().value());
2487 latestComponents.add(toscaElementByOperation.left().value());
2489 if (latestComponents.size() > 1) {
2490 for (Component component : latestComponents) {
2491 if (Boolean.TRUE.equals(component.isHighestVersion())) {
2492 LinkedList<Component> highestComponent = new LinkedList<>();
2493 highestComponent.add(component);
2494 return Either.left(highestComponent);
2498 return Either.left(latestComponents);
2501 public Either<Component, StorageOperationStatus> getLatestServiceByUuid(String serviceUuid) {
2502 Map<GraphPropertyEnum, Object> propertiesToMatch = new EnumMap<>(GraphPropertyEnum.class);
2503 propertiesToMatch.put(GraphPropertyEnum.COMPONENT_TYPE, ComponentTypeEnum.SERVICE.name());
2504 return getLatestComponentByUuid(serviceUuid, propertiesToMatch);
2507 public Either<Component, StorageOperationStatus> getLatestComponentByUuid(String componentUuid) {
2508 return getLatestComponentByUuid(componentUuid, null);
2511 public Either<Component, StorageOperationStatus> getLatestComponentByUuid(String componentUuid,
2512 Map<GraphPropertyEnum, Object> propertiesToMatch) {
2513 Either<List<Component>, StorageOperationStatus> latestVersionListEither = getLatestComponentListByUuid(componentUuid, propertiesToMatch);
2514 if (latestVersionListEither.isRight()) {
2515 return Either.right(latestVersionListEither.right().value());
2517 List<Component> latestVersionList = latestVersionListEither.left().value();
2518 if (latestVersionList.isEmpty()) {
2519 return Either.right(StorageOperationStatus.NOT_FOUND);
2521 Component component = latestVersionList.size() == 1 ? latestVersionList.get(0)
2522 : latestVersionList.stream().max((c1, c2) -> Double.compare(Double.parseDouble(c1.getVersion()), Double.parseDouble(c2.getVersion())))
2524 return Either.left(component);
2527 public Either<List<Resource>, StorageOperationStatus> getAllCertifiedResources(boolean isAbstract, Boolean isHighest) {
2528 List<Resource> resources = new ArrayList<>();
2529 Map<GraphPropertyEnum, Object> propertiesToMatch = new EnumMap<>(GraphPropertyEnum.class);
2530 Map<GraphPropertyEnum, Object> propertiesNotToMatch = new EnumMap<>(GraphPropertyEnum.class);
2531 propertiesToMatch.put(GraphPropertyEnum.IS_ABSTRACT, isAbstract);
2532 if (isHighest != null) {
2533 propertiesToMatch.put(GraphPropertyEnum.IS_HIGHEST_VERSION, isHighest);
2535 propertiesToMatch.put(GraphPropertyEnum.STATE, LifecycleStateEnum.CERTIFIED.name());
2536 propertiesToMatch.put(GraphPropertyEnum.COMPONENT_TYPE, ComponentTypeEnum.RESOURCE.name());
2537 propertiesNotToMatch.put(GraphPropertyEnum.IS_DELETED, true);
2538 Either<List<GraphVertex>, JanusGraphOperationStatus> getResourcesRes = janusGraphDao
2539 .getByCriteria(null, propertiesToMatch, propertiesNotToMatch, JsonParseFlagEnum.ParseAll);
2540 if (getResourcesRes.isRight()) {
2541 log.debug("Failed to fetch all certified resources. Status is {}", getResourcesRes.right().value());
2542 return Either.right(DaoStatusConverter.convertJanusGraphStatusToStorageStatus(getResourcesRes.right().value()));
2544 List<GraphVertex> resourceVerticies = getResourcesRes.left().value();
2545 for (GraphVertex resourceV : resourceVerticies) {
2546 Either<Resource, StorageOperationStatus> getResourceRes = getToscaElement(resourceV);
2547 if (getResourceRes.isRight()) {
2548 return Either.right(getResourceRes.right().value());
2550 resources.add(getResourceRes.left().value());
2552 return Either.left(resources);
2555 public <T extends Component> Either<T, StorageOperationStatus> getLatestByNameAndVersion(String name, String version,
2556 JsonParseFlagEnum parseFlag, String model) {
2557 Either<T, StorageOperationStatus> result;
2558 Map<GraphPropertyEnum, Object> hasProperties = new EnumMap<>(GraphPropertyEnum.class);
2559 Map<GraphPropertyEnum, Object> hasNotProperties = new EnumMap<>(GraphPropertyEnum.class);
2560 hasProperties.put(GraphPropertyEnum.NAME, name);
2561 hasProperties.put(GraphPropertyEnum.VERSION, version);
2562 hasProperties.put(GraphPropertyEnum.IS_HIGHEST_VERSION, true);
2563 hasNotProperties.put(GraphPropertyEnum.IS_DELETED, true);
2564 Either<List<GraphVertex>, JanusGraphOperationStatus> getResourceRes = janusGraphDao
2565 .getByCriteria(null, hasProperties, hasNotProperties, parseFlag, model);
2566 if (getResourceRes.isRight()) {
2567 JanusGraphOperationStatus status = getResourceRes.right().value();
2568 log.debug("failed to find resource with name {}, version {}. Status is {} ", name, version, status);
2569 result = Either.right(DaoStatusConverter.convertJanusGraphStatusToStorageStatus(status));
2572 return getToscaElementByOperation(getResourceRes.left().value().get(0));
2575 public Either<Resource, StorageOperationStatus> getLatestComponentByCsarOrName(ComponentTypeEnum componentType, String csarUUID,
2576 String systemName) {
2577 return getLatestComponentByCsarOrName(componentType, csarUUID, systemName, JsonParseFlagEnum.ParseAll);
2580 public Either<Resource, StorageOperationStatus> getLatestComponentByCsarOrName(ComponentTypeEnum componentType, String csarUUID,
2581 String systemName, JsonParseFlagEnum parseFlag) {
2582 Map<GraphPropertyEnum, Object> props = new EnumMap<>(GraphPropertyEnum.class);
2583 Map<GraphPropertyEnum, Object> propsHasNot = new EnumMap<>(GraphPropertyEnum.class);
2584 props.put(GraphPropertyEnum.CSAR_UUID, csarUUID);
2585 props.put(GraphPropertyEnum.IS_HIGHEST_VERSION, true);
2586 if (componentType != null) {
2587 props.put(GraphPropertyEnum.COMPONENT_TYPE, componentType.name());
2589 propsHasNot.put(GraphPropertyEnum.IS_DELETED, true);
2590 GraphVertex resourceMetadataData = null;
2591 List<GraphVertex> resourceMetadataDataList = null;
2592 Either<List<GraphVertex>, JanusGraphOperationStatus> byCsar = janusGraphDao
2593 .getByCriteria(null, props, propsHasNot, JsonParseFlagEnum.ParseMetadata);
2594 if (byCsar.isRight()) {
2595 if (JanusGraphOperationStatus.NOT_FOUND == byCsar.right().value()) {
2596 // Fix Defect DE256036
2597 if (StringUtils.isEmpty(systemName)) {
2598 return Either.right(DaoStatusConverter.convertJanusGraphStatusToStorageStatus(JanusGraphOperationStatus.NOT_FOUND));
2601 props.put(GraphPropertyEnum.IS_HIGHEST_VERSION, true);
2602 props.put(GraphPropertyEnum.SYSTEM_NAME, systemName);
2603 Either<List<GraphVertex>, JanusGraphOperationStatus> bySystemname = janusGraphDao
2604 .getByCriteria(null, props, JsonParseFlagEnum.ParseMetadata);
2605 if (bySystemname.isRight()) {
2606 log.debug("getLatestResourceByCsarOrName - Failed to find by system name {} error {} ", systemName,
2607 bySystemname.right().value());
2608 return Either.right(DaoStatusConverter.convertJanusGraphStatusToStorageStatus(bySystemname.right().value()));
2610 if (bySystemname.left().value().size() > 2) {
2612 "getLatestResourceByCsarOrName - getByCriteria(by system name) must return only 2 latest version, but was returned - {}",
2613 bySystemname.left().value().size());
2614 return Either.right(StorageOperationStatus.GENERAL_ERROR);
2616 resourceMetadataDataList = bySystemname.left().value();
2617 if (resourceMetadataDataList.size() == 1) {
2618 resourceMetadataData = resourceMetadataDataList.get(0);
2620 for (GraphVertex curResource : resourceMetadataDataList) {
2621 if (!((String) curResource.getJsonMetadataField(JsonPresentationFields.LIFECYCLE_STATE)).equals("CERTIFIED")) {
2622 resourceMetadataData = curResource;
2627 if (resourceMetadataData == null) {
2628 log.debug("getLatestResourceByCsarOrName - getByCriteria(by system name) returned 2 latest CERTIFIED versions");
2629 return Either.right(StorageOperationStatus.GENERAL_ERROR);
2631 final Object csarUuid = resourceMetadataData.getJsonMetadataField(JsonPresentationFields.CSAR_UUID);
2632 if (csarUuid != null && !csarUuid.equals(csarUUID)) {
2633 log.debug("getLatestResourceByCsarOrName - same system name {} but different csarUUID. exist {} and new {} ", systemName,
2634 csarUuid, csarUUID);
2635 // correct error will be returned from create flow. with all
2637 // correct audit records!!!!!
2638 return Either.right(StorageOperationStatus.NOT_FOUND);
2640 return getToscaElement(resourceMetadataData.getUniqueId());
2643 resourceMetadataDataList = byCsar.left().value();
2644 if (resourceMetadataDataList.size() > 2) {
2645 log.debug("getLatestResourceByCsarOrName - getByCriteria(by csar) must return only 2 latest version, but was returned - {}",
2646 byCsar.left().value().size());
2647 return Either.right(StorageOperationStatus.GENERAL_ERROR);
2649 if (resourceMetadataDataList.size() == 1) {
2650 resourceMetadataData = resourceMetadataDataList.get(0);
2652 for (GraphVertex curResource : resourceMetadataDataList) {
2653 if (!((String) curResource.getJsonMetadataField(JsonPresentationFields.LIFECYCLE_STATE)).equals("CERTIFIED")) {
2654 resourceMetadataData = curResource;
2659 if (resourceMetadataData == null) {
2660 log.debug("getLatestResourceByCsarOrName - getByCriteria(by csar) returned 2 latest CERTIFIED versions");
2661 return Either.right(StorageOperationStatus.GENERAL_ERROR);
2663 return getToscaElement((String) resourceMetadataData.getJsonMetadataField(JsonPresentationFields.UNIQUE_ID), parseFlag);
2668 public Either<Boolean, StorageOperationStatus> validateToscaResourceNameExtends(String templateNameCurrent, String templateNameExtends,
2670 String currentTemplateNameChecked = templateNameExtends;
2671 while (currentTemplateNameChecked != null && !currentTemplateNameChecked.equalsIgnoreCase(templateNameCurrent)) {
2672 Either<Resource, StorageOperationStatus> latestByToscaResourceName = getLatestByToscaResourceName(currentTemplateNameChecked, model);
2673 if (latestByToscaResourceName.isRight()) {
2674 return latestByToscaResourceName.right().value() == StorageOperationStatus.NOT_FOUND ? Either.left(false)
2675 : Either.right(latestByToscaResourceName.right().value());
2677 Resource value = latestByToscaResourceName.left().value();
2678 if (value.getDerivedFrom() != null) {
2679 currentTemplateNameChecked = value.getDerivedFrom().get(0);
2681 currentTemplateNameChecked = null;
2684 return (currentTemplateNameChecked != null && currentTemplateNameChecked.equalsIgnoreCase(templateNameCurrent)) ? Either.left(true)
2685 : Either.left(false);
2688 public Either<List<Component>, StorageOperationStatus> fetchMetaDataByResourceType(String resourceType, ComponentParametersView filterBy) {
2689 Map<GraphPropertyEnum, Object> props = new EnumMap<>(GraphPropertyEnum.class);
2690 props.put(GraphPropertyEnum.RESOURCE_TYPE, resourceType);
2691 props.put(GraphPropertyEnum.IS_HIGHEST_VERSION, true);
2692 Map<GraphPropertyEnum, Object> propsHasNotToMatch = new EnumMap<>(GraphPropertyEnum.class);
2693 propsHasNotToMatch.put(GraphPropertyEnum.IS_DELETED, true);
2694 Either<List<GraphVertex>, JanusGraphOperationStatus> resourcesByTypeEither = janusGraphDao
2695 .getByCriteria(null, props, propsHasNotToMatch, JsonParseFlagEnum.ParseMetadata);
2696 if (resourcesByTypeEither.isRight()) {
2697 return Either.right(DaoStatusConverter.convertJanusGraphStatusToStorageStatus(resourcesByTypeEither.right().value()));
2699 List<GraphVertex> vertexList = resourcesByTypeEither.left().value();
2700 List<Component> components = new ArrayList<>();
2701 for (GraphVertex vertex : vertexList) {
2702 components.add(getToscaElementByOperation(vertex, filterBy).left().value());
2704 return Either.left(components);
2707 public void commit() {
2708 janusGraphDao.commit();
2711 public Either<Service, StorageOperationStatus> updateDistributionStatus(Service service, User user, DistributionStatusEnum distributionStatus) {
2712 Either<GraphVertex, StorageOperationStatus> updateDistributionStatus = topologyTemplateOperation
2713 .updateDistributionStatus(service.getUniqueId(), user, distributionStatus);
2714 if (updateDistributionStatus.isRight()) {
2715 return Either.right(updateDistributionStatus.right().value());
2717 GraphVertex serviceV = updateDistributionStatus.left().value();
2718 service.setDistributionStatus(distributionStatus);
2719 service.setLastUpdateDate((Long) serviceV.getJsonMetadataField(JsonPresentationFields.LAST_UPDATE_DATE));
2720 return Either.left(service);
2723 public Either<ComponentMetadataData, StorageOperationStatus> updateComponentLastUpdateDateOnGraph(Component component) {
2724 Either<ComponentMetadataData, StorageOperationStatus> result = null;
2725 GraphVertex serviceVertex;
2726 Either<GraphVertex, JanusGraphOperationStatus> updateRes = null;
2727 Either<GraphVertex, JanusGraphOperationStatus> getRes = janusGraphDao.getVertexById(component.getUniqueId(), JsonParseFlagEnum.ParseMetadata);
2728 if (getRes.isRight()) {
2729 JanusGraphOperationStatus status = getRes.right().value();
2730 log.error("Failed to fetch component {}. status is {}", component.getUniqueId(), status);
2731 result = Either.right(DaoStatusConverter.convertJanusGraphStatusToStorageStatus(status));
2733 if (result == null) {
2734 serviceVertex = getRes.left().value();
2735 long lastUpdateDate = System.currentTimeMillis();
2736 serviceVertex.setJsonMetadataField(JsonPresentationFields.LAST_UPDATE_DATE, lastUpdateDate);
2737 component.setLastUpdateDate(lastUpdateDate);
2738 updateRes = janusGraphDao.updateVertex(serviceVertex);
2739 if (updateRes.isRight()) {
2740 result = Either.right(DaoStatusConverter.convertJanusGraphStatusToStorageStatus(updateRes.right().value()));
2743 if (result == null) {
2744 result = Either.left(ModelConverter.convertToComponentMetadata(updateRes.left().value()));
2749 public HealingJanusGraphDao getJanusGraphDao() {
2750 return janusGraphDao;
2753 public Either<List<Service>, StorageOperationStatus> getCertifiedServicesWithDistStatus(Set<DistributionStatusEnum> distStatus) {
2754 Map<GraphPropertyEnum, Object> propertiesToMatch = new EnumMap<>(GraphPropertyEnum.class);
2755 propertiesToMatch.put(GraphPropertyEnum.STATE, LifecycleStateEnum.CERTIFIED.name());
2756 return getServicesWithDistStatus(distStatus, propertiesToMatch);
2759 public Either<List<Service>, StorageOperationStatus> getServicesWithDistStatus(Set<DistributionStatusEnum> distStatus,
2760 Map<GraphPropertyEnum, Object> additionalPropertiesToMatch) {
2761 List<Service> servicesAll = new ArrayList<>();
2762 Map<GraphPropertyEnum, Object> propertiesToMatch = new EnumMap<>(GraphPropertyEnum.class);
2763 Map<GraphPropertyEnum, Object> propertiesNotToMatch = new EnumMap<>(GraphPropertyEnum.class);
2764 if (additionalPropertiesToMatch != null && !additionalPropertiesToMatch.isEmpty()) {
2765 propertiesToMatch.putAll(additionalPropertiesToMatch);
2767 propertiesToMatch.put(GraphPropertyEnum.COMPONENT_TYPE, ComponentTypeEnum.SERVICE.name());
2768 propertiesNotToMatch.put(GraphPropertyEnum.IS_DELETED, true);
2769 if (distStatus != null && !distStatus.isEmpty()) {
2770 for (DistributionStatusEnum state : distStatus) {
2771 propertiesToMatch.put(GraphPropertyEnum.DISTRIBUTION_STATUS, state.name());
2772 Either<List<Service>, StorageOperationStatus> fetchServicesByCriteria = fetchServicesByCriteria(servicesAll, propertiesToMatch,
2773 propertiesNotToMatch, null);
2774 if (fetchServicesByCriteria.isRight()) {
2775 return fetchServicesByCriteria;
2777 servicesAll = fetchServicesByCriteria.left().value();
2780 return Either.left(servicesAll);
2782 return fetchServicesByCriteria(servicesAll, propertiesToMatch, propertiesNotToMatch, null);
2786 private Either<List<Service>, StorageOperationStatus> fetchServicesByCriteria(List<Service> servicesAll,
2787 Map<GraphPropertyEnum, Object> propertiesToMatch,
2788 Map<GraphPropertyEnum, Object> propertiesNotToMatch,
2790 Either<List<GraphVertex>, JanusGraphOperationStatus> getRes = janusGraphDao
2791 .getByCriteria(VertexTypeEnum.TOPOLOGY_TEMPLATE, propertiesToMatch, propertiesNotToMatch, JsonParseFlagEnum.ParseAll, modelName);
2792 if (getRes.isRight()) {
2793 if (getRes.right().value() != JanusGraphOperationStatus.NOT_FOUND) {
2794 CommonUtility.addRecordToLog(log, LogLevelEnum.DEBUG,
2795 "Failed to fetch certified services by match properties {} not match properties {} . Status is {}. ", propertiesToMatch,
2796 propertiesNotToMatch, getRes.right().value());
2797 return Either.right(DaoStatusConverter.convertJanusGraphStatusToStorageStatus(getRes.right().value()));
2800 for (final GraphVertex vertex : getRes.left().value()) {
2801 Either<ToscaElement, StorageOperationStatus> getServiceRes = topologyTemplateOperation
2802 .getLightComponent(vertex, ComponentTypeEnum.SERVICE, new ComponentParametersView(true));
2803 if (getServiceRes.isRight()) {
2804 CommonUtility.addRecordToLog(log, LogLevelEnum.DEBUG, "Failed to fetch certified service {}. Status is {}. ",
2805 vertex.getJsonMetadataField(JsonPresentationFields.NAME), getServiceRes.right().value());
2806 return Either.right(getServiceRes.right().value());
2808 servicesAll.add(ModelConverter.convertFromToscaElement(getServiceRes.left().value()));
2812 return Either.left(servicesAll);
2815 public void rollback() {
2816 janusGraphDao.rollback();
2819 public StorageOperationStatus addDeploymentArtifactsToInstance(String componentId, ComponentInstance componentInstance,
2820 Map<String, ArtifactDefinition> finalDeploymentArtifacts) {
2821 Map<String, ArtifactDataDefinition> instDeplArtifacts = finalDeploymentArtifacts.entrySet().stream()
2822 .collect(Collectors.toMap(Map.Entry::getKey, e -> new ArtifactDataDefinition(e.getValue())));
2823 return nodeTemplateOperation.addDeploymentArtifactsToInstance(componentId, componentInstance.getUniqueId(), instDeplArtifacts);
2826 public StorageOperationStatus addInformationalArtifactsToInstance(String componentId, ComponentInstance componentInstance,
2827 Map<String, ArtifactDefinition> artifacts) {
2828 StorageOperationStatus status = StorageOperationStatus.OK;
2829 if (MapUtils.isNotEmpty(artifacts)) {
2830 Map<String, ArtifactDataDefinition> instDeplArtifacts = artifacts.entrySet().stream()
2831 .collect(Collectors.toMap(Map.Entry::getKey, e -> new ArtifactDataDefinition(e.getValue())));
2832 status = nodeTemplateOperation.addInformationalArtifactsToInstance(componentId, componentInstance.getUniqueId(), instDeplArtifacts);
2837 public StorageOperationStatus generateCustomizationUUIDOnInstance(String componentId, String instanceId) {
2838 return nodeTemplateOperation.generateCustomizationUUIDOnInstance(componentId, instanceId);
2841 public StorageOperationStatus generateCustomizationUUIDOnInstanceGroup(String componentId, String instanceId, List<String> groupInstances) {
2842 return nodeTemplateOperation.generateCustomizationUUIDOnInstanceGroup(componentId, instanceId, groupInstances);
2845 public Either<PropertyDefinition, StorageOperationStatus> addPropertyToComponent(PropertyDefinition newPropertyDefinition,
2846 Component component) {
2847 final String propertyName = newPropertyDefinition.getName();
2848 StorageOperationStatus status = getToscaElementOperation(component)
2849 .addToscaDataToToscaElement(component.getUniqueId(), EdgeLabelEnum.PROPERTIES, VertexTypeEnum.PROPERTIES, newPropertyDefinition,
2850 JsonPresentationFields.NAME);
2851 if (status != StorageOperationStatus.OK) {
2852 CommonUtility.addRecordToLog(log, LogLevelEnum.DEBUG, "Failed to add the property {} to the component {}. Status is {}. ", propertyName,
2853 component.getName(), status);
2854 return Either.right(status);
2856 ComponentParametersView filter = new ComponentParametersView(true);
2857 filter.setIgnoreProperties(false);
2858 filter.setIgnoreInputs(false);
2859 Either<Component, StorageOperationStatus> getUpdatedComponentRes = getToscaElement(component.getUniqueId(), filter);
2860 if (getUpdatedComponentRes.isRight()) {
2861 CommonUtility.addRecordToLog(log, LogLevelEnum.DEBUG, "Failed to get updated component {}. Status is {}. ", component.getUniqueId(),
2862 getUpdatedComponentRes.right().value());
2863 return Either.right(status);
2865 PropertyDefinition newProperty = null;
2866 List<PropertyDefinition> properties = (getUpdatedComponentRes.left().value()).getProperties();
2867 if (CollectionUtils.isNotEmpty(properties)) {
2868 Optional<PropertyDefinition> propertyOptional = properties.stream().filter(propertyEntry -> propertyEntry.getName().equals(propertyName))
2870 if (propertyOptional.isPresent()) {
2871 newProperty = propertyOptional.get();
2874 if (newProperty == null) {
2875 CommonUtility.addRecordToLog(log, LogLevelEnum.DEBUG, "Failed to find recently added property {} on the component {}. Status is {}. ",
2876 propertyName, component.getUniqueId(), StorageOperationStatus.NOT_FOUND);
2877 return Either.right(StorageOperationStatus.NOT_FOUND);
2879 return Either.left(newProperty);
2882 public Either<InputDefinition, StorageOperationStatus> addInputToComponent(String inputName, InputDefinition newInputDefinition,
2883 Component component) {
2884 newInputDefinition.setName(inputName);
2885 StorageOperationStatus status = getToscaElementOperation(component)
2886 .addToscaDataToToscaElement(component.getUniqueId(), EdgeLabelEnum.INPUTS, VertexTypeEnum.INPUTS, newInputDefinition,
2887 JsonPresentationFields.NAME);
2888 if (status != StorageOperationStatus.OK) {
2889 CommonUtility.addRecordToLog(log, LogLevelEnum.DEBUG, "Failed to add the input {} to the component {}. Status is {}. ", inputName,
2890 component.getName(), status);
2891 return Either.right(status);
2893 ComponentParametersView filter = new ComponentParametersView(true);
2894 filter.setIgnoreProperties(false);
2895 filter.setIgnoreInputs(false);
2896 Either<Component, StorageOperationStatus> getUpdatedComponentRes = getToscaElement(component.getUniqueId(), filter);
2897 if (getUpdatedComponentRes.isRight()) {
2898 CommonUtility.addRecordToLog(log, LogLevelEnum.DEBUG, "Failed to get updated component {}. Status is {}. ", component.getUniqueId(),
2899 getUpdatedComponentRes.right().value());
2900 return Either.right(status);
2902 InputDefinition newInput = null;
2903 List<InputDefinition> inputs = (getUpdatedComponentRes.left().value()).getInputs();
2904 if (CollectionUtils.isNotEmpty(inputs)) {
2905 Optional<InputDefinition> inputOptional = inputs.stream().filter(inputEntry -> inputEntry.getName().equals(inputName)).findAny();
2906 if (inputOptional.isPresent()) {
2907 newInput = inputOptional.get();
2910 if (newInput == null) {
2912 .addRecordToLog(log, LogLevelEnum.DEBUG, "Failed to find recently added input {} " + "on the component {}. Status is {}. ", inputs,
2913 component.getUniqueId(), StorageOperationStatus.NOT_FOUND);
2914 return Either.right(StorageOperationStatus.NOT_FOUND);
2916 return Either.left(newInput);
2919 public StorageOperationStatus deletePropertyOfComponent(Component component, String propertyName) {
2920 return getToscaElementOperation(component)
2921 .deleteToscaDataElement(component.getUniqueId(), EdgeLabelEnum.PROPERTIES, VertexTypeEnum.PROPERTIES, propertyName,
2922 JsonPresentationFields.NAME);
2925 public StorageOperationStatus deleteAttributeOfResource(Component component, String attributeName) {
2926 return getToscaElementOperation(component)
2927 .deleteToscaDataElement(component.getUniqueId(), EdgeLabelEnum.ATTRIBUTES, VertexTypeEnum.ATTRIBUTES, attributeName,
2928 JsonPresentationFields.NAME);
2931 public StorageOperationStatus deleteInputOfResource(Component resource, String inputName) {
2932 return getToscaElementOperation(resource)
2933 .deleteToscaDataElement(resource.getUniqueId(), EdgeLabelEnum.INPUTS, VertexTypeEnum.INPUTS, inputName, JsonPresentationFields.NAME);
2936 public StorageOperationStatus deleteOutputOfResource(final Component resource, final String outputName) {
2937 return getToscaElementOperation(resource)
2938 .deleteToscaDataElement(resource.getUniqueId(), EdgeLabelEnum.OUTPUTS, VertexTypeEnum.OUTPUTS, outputName, JsonPresentationFields.NAME);
2942 * Deletes a data type from a component.
2944 * @param component the container which has the data type
2945 * @param dataTypeName the data type name to be deleted
2946 * @return Operation result.
2948 public StorageOperationStatus deleteDataTypeOfComponent(Component component, String dataTypeName) {
2949 return getToscaElementOperation(component)
2950 .deleteToscaDataElement(component.getUniqueId(), EdgeLabelEnum.DATA_TYPES, VertexTypeEnum.DATA_TYPES, dataTypeName,
2951 JsonPresentationFields.NAME);
2954 public Either<PropertyDefinition, StorageOperationStatus> updatePropertyOfComponent(Component component,
2955 PropertyDefinition newPropertyDefinition) {
2956 Either<Component, StorageOperationStatus> getUpdatedComponentRes = null;
2957 Either<PropertyDefinition, StorageOperationStatus> result = null;
2958 StorageOperationStatus status = getToscaElementOperation(component)
2959 .updateToscaDataOfToscaElement(component.getUniqueId(), EdgeLabelEnum.PROPERTIES, VertexTypeEnum.PROPERTIES, newPropertyDefinition,
2960 JsonPresentationFields.NAME);
2961 if (status != StorageOperationStatus.OK) {
2963 .addRecordToLog(log, LogLevelEnum.DEBUG, FAILED_TO_ADD_THE_PROPERTY_TO_THE_RESOURCE_STATUS_IS, newPropertyDefinition.getName(),
2964 component.getName(), status);
2965 result = Either.right(status);
2967 if (result == null) {
2968 ComponentParametersView filter = new ComponentParametersView(true);
2969 filter.setIgnoreProperties(false);
2970 getUpdatedComponentRes = getToscaElement(component.getUniqueId(), filter);
2971 if (getUpdatedComponentRes.isRight()) {
2972 CommonUtility.addRecordToLog(log, LogLevelEnum.DEBUG, FAILED_TO_GET_UPDATED_RESOURCE_STATUS_IS, component.getUniqueId(),
2973 getUpdatedComponentRes.right().value());
2974 result = Either.right(status);
2977 if (result == null) {
2978 Optional<PropertyDefinition> newProperty = (getUpdatedComponentRes.left().value()).getProperties().stream()
2979 .filter(p -> p.getName().equals(newPropertyDefinition.getName())).findAny();
2980 if (newProperty.isPresent()) {
2981 result = Either.left(newProperty.get());
2983 CommonUtility.addRecordToLog(log, LogLevelEnum.DEBUG, FAILED_TO_FIND_RECENTLY_ADDED_PROPERTY_ON_THE_RESOURCE_STATUS_IS,
2984 newPropertyDefinition.getName(), component.getUniqueId(), StorageOperationStatus.NOT_FOUND);
2985 result = Either.right(StorageOperationStatus.NOT_FOUND);
2991 public Either<AttributeDefinition, StorageOperationStatus> updateAttributeOfComponent(Component component,
2992 AttributeDefinition newPropertyDefinition) {
2993 Either<Component, StorageOperationStatus> getUpdatedComponentRes = null;
2994 Either<AttributeDefinition, StorageOperationStatus> result = null;
2995 StorageOperationStatus status = getToscaElementOperation(component)
2996 .updateToscaDataOfToscaElement(component.getUniqueId(), EdgeLabelEnum.ATTRIBUTES, VertexTypeEnum.ATTRIBUTES, newPropertyDefinition,
2997 JsonPresentationFields.NAME);
2998 if (status != StorageOperationStatus.OK) {
3000 .addRecordToLog(log, LogLevelEnum.DEBUG, FAILED_TO_ADD_THE_PROPERTY_TO_THE_RESOURCE_STATUS_IS, newPropertyDefinition.getName(),
3001 component.getName(), status);
3002 result = Either.right(status);
3004 if (result == null) {
3005 ComponentParametersView filter = new ComponentParametersView(true);
3006 filter.setIgnoreProperties(false);
3007 getUpdatedComponentRes = getToscaElement(component.getUniqueId(), filter);
3008 if (getUpdatedComponentRes.isRight()) {
3009 CommonUtility.addRecordToLog(log, LogLevelEnum.DEBUG, FAILED_TO_GET_UPDATED_RESOURCE_STATUS_IS, component.getUniqueId(),
3010 getUpdatedComponentRes.right().value());
3011 result = Either.right(status);
3014 if (result == null) {
3015 Optional<AttributeDefinition> newProperty = (getUpdatedComponentRes.left().value()).getAttributes().stream()
3016 .filter(p -> p.getName().equals(newPropertyDefinition.getName())).findAny();
3017 if (newProperty.isPresent()) {
3018 result = Either.left(newProperty.get());
3020 CommonUtility.addRecordToLog(log, LogLevelEnum.DEBUG, FAILED_TO_FIND_RECENTLY_ADDED_PROPERTY_ON_THE_RESOURCE_STATUS_IS,
3021 newPropertyDefinition.getName(), component.getUniqueId(), StorageOperationStatus.NOT_FOUND);
3022 result = Either.right(StorageOperationStatus.NOT_FOUND);
3028 public Either<AttributeDefinition, StorageOperationStatus> addAttributeOfResource(Component component, AttributeDefinition newAttributeDef) {
3029 Either<Component, StorageOperationStatus> getUpdatedComponentRes = null;
3030 Either<AttributeDefinition, StorageOperationStatus> result = null;
3031 if (newAttributeDef.getUniqueId() == null || newAttributeDef.getUniqueId().isEmpty()) {
3032 String attUniqueId = UniqueIdBuilder.buildAttributeUid(component.getUniqueId(), newAttributeDef.getName());
3033 newAttributeDef.setUniqueId(attUniqueId);
3034 newAttributeDef.setOwnerId(component.getUniqueId());
3036 StorageOperationStatus status = getToscaElementOperation(component)
3037 .addToscaDataToToscaElement(component.getUniqueId(), EdgeLabelEnum.ATTRIBUTES, VertexTypeEnum.ATTRIBUTES, newAttributeDef,
3038 JsonPresentationFields.NAME);
3039 if (status != StorageOperationStatus.OK) {
3040 CommonUtility.addRecordToLog(log, LogLevelEnum.DEBUG, FAILED_TO_ADD_THE_PROPERTY_TO_THE_RESOURCE_STATUS_IS, newAttributeDef.getName(),
3041 component.getName(), status);
3042 result = Either.right(status);
3044 if (result == null) {
3045 ComponentParametersView filter = new ComponentParametersView(true);
3046 filter.setIgnoreAttributes(false);
3047 getUpdatedComponentRes = getToscaElement(component.getUniqueId(), filter);
3048 if (getUpdatedComponentRes.isRight()) {
3049 CommonUtility.addRecordToLog(log, LogLevelEnum.DEBUG, FAILED_TO_GET_UPDATED_RESOURCE_STATUS_IS, component.getUniqueId(),
3050 getUpdatedComponentRes.right().value());
3051 result = Either.right(status);
3054 if (result == null) {
3055 Optional<AttributeDefinition> newAttribute = ((Resource) getUpdatedComponentRes.left().value()).getAttributes().stream()
3056 .filter(p -> p.getName().equals(newAttributeDef.getName())).findAny();
3057 if (newAttribute.isPresent()) {
3058 result = Either.left(newAttribute.get());
3060 CommonUtility.addRecordToLog(log, LogLevelEnum.DEBUG, FAILED_TO_FIND_RECENTLY_ADDED_PROPERTY_ON_THE_RESOURCE_STATUS_IS,
3061 newAttributeDef.getName(), component.getUniqueId(), StorageOperationStatus.NOT_FOUND);
3062 result = Either.right(StorageOperationStatus.NOT_FOUND);
3068 public Either<AttributeDefinition, StorageOperationStatus> updateAttributeOfResource(Component component, AttributeDefinition newAttributeDef) {
3069 Either<Component, StorageOperationStatus> getUpdatedComponentRes = null;
3070 Either<AttributeDefinition, StorageOperationStatus> result = null;
3071 StorageOperationStatus status = getToscaElementOperation(component)
3072 .updateToscaDataOfToscaElement(component.getUniqueId(), EdgeLabelEnum.ATTRIBUTES, VertexTypeEnum.ATTRIBUTES, newAttributeDef,
3073 JsonPresentationFields.NAME);
3074 if (status != StorageOperationStatus.OK) {
3075 CommonUtility.addRecordToLog(log, LogLevelEnum.DEBUG, FAILED_TO_ADD_THE_PROPERTY_TO_THE_RESOURCE_STATUS_IS, newAttributeDef.getName(),
3076 component.getName(), status);
3077 result = Either.right(status);
3079 if (result == null) {
3080 ComponentParametersView filter = new ComponentParametersView(true);
3081 filter.setIgnoreAttributes(false);
3082 getUpdatedComponentRes = getToscaElement(component.getUniqueId(), filter);
3083 if (getUpdatedComponentRes.isRight()) {
3084 CommonUtility.addRecordToLog(log, LogLevelEnum.DEBUG, FAILED_TO_GET_UPDATED_RESOURCE_STATUS_IS, component.getUniqueId(),
3085 getUpdatedComponentRes.right().value());
3086 result = Either.right(status);
3089 if (result == null) {
3090 Optional<AttributeDefinition> newProperty = ((Resource) getUpdatedComponentRes.left().value()).getAttributes().stream()
3091 .filter(p -> p.getName().equals(newAttributeDef.getName())).findAny();
3092 if (newProperty.isPresent()) {
3093 result = Either.left(newProperty.get());
3095 CommonUtility.addRecordToLog(log, LogLevelEnum.DEBUG, FAILED_TO_FIND_RECENTLY_ADDED_PROPERTY_ON_THE_RESOURCE_STATUS_IS,
3096 newAttributeDef.getName(), component.getUniqueId(), StorageOperationStatus.NOT_FOUND);
3097 result = Either.right(StorageOperationStatus.NOT_FOUND);
3103 public Either<InputDefinition, StorageOperationStatus> updateInputOfComponent(Component component, InputDefinition newInputDefinition) {
3104 Either<Component, StorageOperationStatus> getUpdatedComponentRes = null;
3105 Either<InputDefinition, StorageOperationStatus> result = null;
3106 StorageOperationStatus status = getToscaElementOperation(component)
3107 .updateToscaDataOfToscaElement(component.getUniqueId(), EdgeLabelEnum.INPUTS, VertexTypeEnum.INPUTS, newInputDefinition,
3108 JsonPresentationFields.NAME);
3109 if (status != StorageOperationStatus.OK) {
3110 CommonUtility.addRecordToLog(log, LogLevelEnum.DEBUG, "Failed to update the input {} to the component {}. Status is {}. ",
3111 newInputDefinition.getName(), component.getName(), status);
3112 result = Either.right(status);
3114 if (result == null) {
3115 ComponentParametersView filter = new ComponentParametersView(true);
3116 filter.setIgnoreInputs(false);
3117 getUpdatedComponentRes = getToscaElement(component.getUniqueId(), filter);
3118 if (getUpdatedComponentRes.isRight()) {
3119 CommonUtility.addRecordToLog(log, LogLevelEnum.DEBUG, FAILED_TO_GET_UPDATED_RESOURCE_STATUS_IS, component.getUniqueId(),
3120 getUpdatedComponentRes.right().value());
3121 result = Either.right(status);
3124 if (result == null) {
3125 Optional<InputDefinition> updatedInput = getUpdatedComponentRes.left().value().getInputs().stream()
3126 .filter(p -> p.getName().equals(newInputDefinition.getName())).findAny();
3127 if (updatedInput.isPresent()) {
3128 result = Either.left(updatedInput.get());
3130 CommonUtility.addRecordToLog(log, LogLevelEnum.DEBUG, "Failed to find recently updated inputs {} on the resource {}. Status is {}. ",
3131 newInputDefinition.getName(), component.getUniqueId(), StorageOperationStatus.NOT_FOUND);
3132 result = Either.right(StorageOperationStatus.NOT_FOUND);
3139 * method - ename the group instances after referenced container name renamed flow - VF rename -(triggers)-> Group rename
3141 * @param containerComponent - container such as service
3142 * @param componentInstance - context component
3143 * @param componentInstanceId - id
3144 * @return - successfull/failed status
3146 public Either<StorageOperationStatus, StorageOperationStatus> cleanAndAddGroupInstancesToComponentInstance(Component containerComponent,
3147 ComponentInstance componentInstance,
3148 String componentInstanceId) {
3149 String uniqueId = componentInstance.getUniqueId();
3150 StorageOperationStatus status = nodeTemplateOperation
3151 .deleteToscaDataDeepElementsBlockOfToscaElement(containerComponent.getUniqueId(), EdgeLabelEnum.INST_GROUPS,
3153 if (status != StorageOperationStatus.OK && status != StorageOperationStatus.NOT_FOUND) {
3155 .addRecordToLog(log, LogLevelEnum.DEBUG, "Failed to delete group instances for container {}. error {] ", componentInstanceId, status);
3156 return Either.right(status);
3158 if (componentInstance.getGroupInstances() != null) {
3159 status = addGroupInstancesToComponentInstance(containerComponent, componentInstance, componentInstance.getGroupInstances());
3160 if (status != StorageOperationStatus.OK && status != StorageOperationStatus.NOT_FOUND) {
3162 .addRecordToLog(log, LogLevelEnum.DEBUG, "Failed to add group instances for container {}. error {] ", componentInstanceId,
3164 return Either.right(status);
3167 return Either.left(status);
3170 public StorageOperationStatus addGroupInstancesToComponentInstance(Component containerComponent, ComponentInstance componentInstance,
3171 List<GroupDefinition> groups,
3172 Map<String, List<ArtifactDefinition>> groupInstancesArtifacts) {
3173 return nodeTemplateOperation.addGroupInstancesToComponentInstance(containerComponent, componentInstance, groups, groupInstancesArtifacts);
3176 public Either<List<GroupDefinition>, StorageOperationStatus> updateGroupsOnComponent(Component component,
3177 List<GroupDataDefinition> updatedGroups) {
3178 return groupsOperation.updateGroups(component, updatedGroups, PromoteVersionEnum.MINOR);
3181 public Either<List<GroupInstance>, StorageOperationStatus> updateGroupInstancesOnComponent(Component component, String instanceId,
3182 List<GroupInstance> updatedGroupInstances) {
3183 return groupsOperation.updateGroupInstances(component, instanceId, updatedGroupInstances);
3186 public StorageOperationStatus addGroupInstancesToComponentInstance(Component containerComponent, ComponentInstance componentInstance,
3187 List<GroupInstance> groupInstances) {
3188 return nodeTemplateOperation.addGroupInstancesToComponentInstance(containerComponent, componentInstance, groupInstances);
3191 public StorageOperationStatus addDeploymentArtifactsToComponentInstance(Component containerComponent, ComponentInstance componentInstance,
3192 Map<String, ArtifactDefinition> deploymentArtifacts) {
3193 return nodeTemplateOperation.addDeploymentArtifactsToComponentInstance(containerComponent, componentInstance, deploymentArtifacts);
3196 public StorageOperationStatus updateComponentInstanceProperty(Component containerComponent, String componentInstanceId,
3197 ComponentInstanceProperty property) {
3198 return nodeTemplateOperation.updateComponentInstanceProperty(containerComponent, componentInstanceId, property);
3201 public StorageOperationStatus updateComponentInstanceProperties(Component containerComponent, String componentInstanceId,
3202 List<ComponentInstanceProperty> properties) {
3203 return nodeTemplateOperation.updateComponentInstanceProperties(containerComponent, componentInstanceId, properties);
3206 public StorageOperationStatus updateComponentInstanceAttributes(final Component containerComponent, final String componentInstanceId,
3207 final List<ComponentInstanceAttribute> attributes) {
3208 return nodeTemplateOperation.updateComponentInstanceAttributes(containerComponent, componentInstanceId, attributes);
3211 public StorageOperationStatus addComponentInstanceProperty(Component containerComponent, String componentInstanceId,
3212 ComponentInstanceProperty property) {
3213 return nodeTemplateOperation.addComponentInstanceProperty(containerComponent, componentInstanceId, property);
3216 public StorageOperationStatus updateComponentInstanceAttribute(final Component containerComponent, final String componentInstanceId,
3217 final ComponentInstanceAttribute attribute) {
3218 return nodeTemplateOperation.updateComponentInstanceAttribute(containerComponent, componentInstanceId, attribute);
3221 public StorageOperationStatus addComponentInstanceAttribute(Component containerComponent, String componentInstanceId,
3222 ComponentInstanceAttribute attribute) {
3223 return nodeTemplateOperation.addComponentInstanceAttribute(containerComponent, componentInstanceId, attribute);
3226 public StorageOperationStatus updateComponentInstanceInput(Component containerComponent, String componentInstanceId,
3227 ComponentInstanceInput property) {
3228 return nodeTemplateOperation.updateComponentInstanceInput(containerComponent, componentInstanceId, property);
3231 public StorageOperationStatus updateComponentInstanceOutput(Component containerComponent, String componentInstanceId,
3232 ComponentInstanceOutput property) {
3233 return nodeTemplateOperation.updateComponentInstanceOutput(containerComponent, componentInstanceId, property);
3236 public StorageOperationStatus updateComponentInstanceInputs(Component containerComponent, String componentInstanceId,
3237 List<ComponentInstanceInput> instanceInputs) {
3238 return nodeTemplateOperation.updateComponentInstanceInputs(containerComponent, componentInstanceId, instanceInputs);
3241 public StorageOperationStatus updateComponentInstanceOutputs(Component containerComponent, String componentInstanceId,
3242 List<ComponentInstanceOutput> instanceInputs) {
3243 return nodeTemplateOperation.updateComponentInstanceOutputs(containerComponent, componentInstanceId, instanceInputs);
3246 public StorageOperationStatus addComponentInstanceInput(Component containerComponent, String componentInstanceId,
3247 ComponentInstanceInput property) {
3248 return nodeTemplateOperation.addComponentInstanceInput(containerComponent, componentInstanceId, property);
3251 public StorageOperationStatus addComponentInstanceOutput(Component containerComponent, String componentInstanceId,
3252 ComponentInstanceOutput property) {
3253 return nodeTemplateOperation.addComponentInstanceOutput(containerComponent, componentInstanceId, property);
3256 public void setNodeTypeOperation(NodeTypeOperation nodeTypeOperation) {
3257 this.nodeTypeOperation = nodeTypeOperation;
3260 public void setTopologyTemplateOperation(TopologyTemplateOperation topologyTemplateOperation) {
3261 this.topologyTemplateOperation = topologyTemplateOperation;
3264 public StorageOperationStatus deleteComponentInstanceInputsFromTopologyTemplate(Component containerComponent,
3265 List<InputDefinition> inputsToDelete) {
3266 return topologyTemplateOperation.deleteToscaDataElements(containerComponent.getUniqueId(), EdgeLabelEnum.INPUTS,
3267 inputsToDelete.stream().map(PropertyDataDefinition::getName).collect(Collectors.toList()));
3270 public StorageOperationStatus deleteComponentInstanceOutputsFromTopologyTemplate(final Component containerComponent,
3271 final List<OutputDefinition> outputsToDelete) {
3272 return topologyTemplateOperation.deleteToscaDataElements(containerComponent.getUniqueId(), EdgeLabelEnum.OUTPUTS,
3273 outputsToDelete.stream().map(AttributeDataDefinition::getName).collect(Collectors.toList()));
3276 public StorageOperationStatus updateComponentInstanceCapabiltyProperty(Component containerComponent, String componentInstanceUniqueId,
3277 String capabilityPropertyKey, ComponentInstanceProperty property) {
3278 return nodeTemplateOperation
3279 .updateComponentInstanceCapabilityProperty(containerComponent, componentInstanceUniqueId, capabilityPropertyKey, property);
3282 public StorageOperationStatus updateComponentInstanceCapabilityProperties(Component containerComponent, String componentInstanceUniqueId) {
3283 return convertComponentInstanceProperties(containerComponent, componentInstanceUniqueId).map(instanceCapProps -> topologyTemplateOperation
3284 .updateComponentInstanceCapabilityProperties(containerComponent, componentInstanceUniqueId, instanceCapProps))
3285 .orElse(StorageOperationStatus.NOT_FOUND);
3288 public StorageOperationStatus updateComponentInstanceRequirement(String containerComponentId, String componentInstanceUniqueId,
3289 RequirementDataDefinition requirementDataDefinition) {
3290 return nodeTemplateOperation.updateComponentInstanceRequirement(containerComponentId, componentInstanceUniqueId, requirementDataDefinition);
3293 public CapabilityDataDefinition updateComponentInstanceCapability(final String containerComponentId, final String componentInstanceUniqueId,
3294 final CapabilityDataDefinition capabilityDataDefinition) {
3296 return nodeTemplateOperation.updateComponentInstanceCapabilities(containerComponentId, componentInstanceUniqueId, capabilityDataDefinition);
3299 public StorageOperationStatus updateComponentInstanceInterfaces(Component containerComponent, String componentInstanceUniqueId) {
3300 MapInterfaceDataDefinition mapInterfaceDataDefinition = convertComponentInstanceInterfaces(containerComponent, componentInstanceUniqueId);
3301 return topologyTemplateOperation.updateComponentInstanceInterfaces(containerComponent, componentInstanceUniqueId, mapInterfaceDataDefinition);
3304 public StorageOperationStatus updateComponentInterfaces(final Component component, final String componentInterfaceUpdatedKey) {
3305 MapInterfaceDataDefinition mapInterfaceDataDefinition = convertComponentInterfaces(component.getInterfaces());
3306 return topologyTemplateOperation.updateComponentInterfaces(component.getUniqueId(), mapInterfaceDataDefinition, componentInterfaceUpdatedKey);
3309 public Either<InterfaceDefinition, StorageOperationStatus> addInterfaceToComponent(final String interfaceName,
3310 final InterfaceDefinition interfaceDefinition,
3311 final Component component) {
3313 final boolean match = component.getInterfaces().keySet().stream().anyMatch(s -> s.equals(interfaceName));
3314 StorageOperationStatus status;
3315 final ToscaElementOperation toscaElementOperation = getToscaElementOperation(component);
3317 status = toscaElementOperation.updateToscaDataOfToscaElement(component.getUniqueId(), EdgeLabelEnum.INTERFACE_ARTIFACTS,
3318 VertexTypeEnum.INTERFACE_ARTIFACTS, interfaceDefinition, JsonPresentationFields.TYPE);
3320 status = toscaElementOperation.addToscaDataToToscaElement(component.getUniqueId(), EdgeLabelEnum.INTERFACE_ARTIFACTS,
3321 VertexTypeEnum.INTERFACE_ARTIFACTS, interfaceDefinition, JsonPresentationFields.TYPE);
3324 if (status != StorageOperationStatus.OK) {
3325 CommonUtility.addRecordToLog(log, LogLevelEnum.DEBUG, "Failed to add the interface {} to the component {}. Status is {}. ",
3326 interfaceName, component.getName(), status);
3327 return Either.right(status);
3329 final ComponentParametersView filter = new ComponentParametersView(true);
3330 filter.setIgnoreInterfaces(false);
3331 filter.setIgnoreInterfaceInstances(false);
3332 final Either<Component, StorageOperationStatus> getUpdatedComponentRes = getToscaElement(component.getUniqueId(), filter);
3333 if (getUpdatedComponentRes.isRight()) {
3334 CommonUtility.addRecordToLog(log, LogLevelEnum.DEBUG, "Failed to get updated component {}. Status is {}. ",
3335 component.getUniqueId(), getUpdatedComponentRes.right().value());
3336 return Either.right(getUpdatedComponentRes.right().value());
3338 InterfaceDefinition newInterfaceDefinition = null;
3339 final Map<String, InterfaceDefinition> interfaces = (getUpdatedComponentRes.left().value()).getInterfaces();
3340 if (MapUtils.isNotEmpty(interfaces)) {
3341 final Optional<String> interfaceNameOptional = interfaces.keySet().stream().filter(key -> key.equals(interfaceName)).findAny();
3342 if (interfaceNameOptional.isPresent()) {
3343 newInterfaceDefinition = interfaces.get(interfaceNameOptional.get());
3346 if (newInterfaceDefinition == null) {
3347 CommonUtility.addRecordToLog(log, LogLevelEnum.DEBUG, "Failed to find recently added interface {} on the component {}. Status is {}. ",
3348 interfaceName, component.getUniqueId(), StorageOperationStatus.NOT_FOUND);
3349 return Either.right(StorageOperationStatus.NOT_FOUND);
3351 return Either.left(newInterfaceDefinition);
3354 public StorageOperationStatus updateComponentCalculatedCapabilitiesProperties(Component containerComponent) {
3355 Map<String, MapCapabilityProperty> mapCapabiltyPropertyMap = convertComponentCapabilitiesProperties(containerComponent);
3356 return nodeTemplateOperation.overrideComponentCapabilitiesProperties(containerComponent, mapCapabiltyPropertyMap);
3359 public StorageOperationStatus deleteAllCalculatedCapabilitiesRequirements(String topologyTemplateId) {
3360 StorageOperationStatus status = topologyTemplateOperation
3361 .removeToscaData(topologyTemplateId, EdgeLabelEnum.CALCULATED_CAPABILITIES);
3362 if (status == StorageOperationStatus.OK) {
3363 status = topologyTemplateOperation
3364 .removeToscaData(topologyTemplateId, EdgeLabelEnum.CALCULATED_REQUIREMENTS);
3366 if (status == StorageOperationStatus.OK) {
3367 status = topologyTemplateOperation
3368 .removeToscaData(topologyTemplateId, EdgeLabelEnum.CALCULATED_CAP_PROPERTIES);
3373 public Either<Component, StorageOperationStatus> shouldUpgradeToLatestDerived(Resource clonedResource) {
3374 String componentId = clonedResource.getUniqueId();
3375 Either<GraphVertex, JanusGraphOperationStatus> getVertexEither = janusGraphDao.getVertexById(componentId, JsonParseFlagEnum.NoParse);
3376 if (getVertexEither.isRight()) {
3377 log.debug(COULDNT_FETCH_COMPONENT_WITH_AND_UNIQUE_ID_ERROR, componentId, getVertexEither.right().value());
3378 return Either.right(DaoStatusConverter.convertJanusGraphStatusToStorageStatus(getVertexEither.right().value()));
3380 GraphVertex nodeTypeV = getVertexEither.left().value();
3381 ToscaElement toscaElementToUpdate = ModelConverter.convertToToscaElement(clonedResource);
3382 Either<ToscaElement, StorageOperationStatus> shouldUpdateDerivedVersion = nodeTypeOperation
3383 .shouldUpdateDerivedVersion(toscaElementToUpdate, nodeTypeV);
3384 if (shouldUpdateDerivedVersion.isRight() && StorageOperationStatus.OK != shouldUpdateDerivedVersion.right().value()) {
3385 log.debug("Failed to update derived version for node type {} derived {}, error: {}", componentId, clonedResource.getDerivedFrom().get(0),
3386 shouldUpdateDerivedVersion.right().value());
3387 return Either.right(shouldUpdateDerivedVersion.right().value());
3389 if (shouldUpdateDerivedVersion.isLeft()) {
3390 return Either.left(ModelConverter.convertFromToscaElement(shouldUpdateDerivedVersion.left().value()));
3392 return Either.left(clonedResource);
3396 * Returns list of ComponentInstanceProperty belonging to component instance capability specified by name, type and ownerId
3398 public Either<List<ComponentInstanceProperty>, StorageOperationStatus> getComponentInstanceCapabilityProperties(String componentId,
3400 String capabilityName,
3401 String capabilityType,
3403 return topologyTemplateOperation.getComponentInstanceCapabilityProperties(componentId, instanceId, capabilityName, capabilityType, ownerId);
3406 private MapInterfaceDataDefinition convertComponentInstanceInterfaces(Component currComponent, String componentInstanceId) {
3407 MapInterfaceDataDefinition mapInterfaceDataDefinition = new MapInterfaceDataDefinition();
3408 List<ComponentInstanceInterface> componentInterface = currComponent.getComponentInstancesInterfaces().get(componentInstanceId);
3409 if (CollectionUtils.isNotEmpty(componentInterface)) {
3410 componentInterface.stream().forEach(interfaceDef -> mapInterfaceDataDefinition.put(interfaceDef.getUniqueId(), interfaceDef));
3412 return mapInterfaceDataDefinition;
3415 private MapInterfaceDataDefinition convertComponentInterfaces(final Map<String, InterfaceDefinition> interfaces) {
3416 final MapInterfaceDataDefinition mapInterfaceDataDefinition = new MapInterfaceDataDefinition();
3417 if (MapUtils.isNotEmpty(interfaces)) {
3418 interfaces.values().stream().forEach(interfaceDef -> mapInterfaceDataDefinition.put(interfaceDef.getType(), interfaceDef));
3420 return mapInterfaceDataDefinition;
3423 private Map<String, MapCapabilityProperty> convertComponentCapabilitiesProperties(Component currComponent) {
3424 Map<String, MapCapabilityProperty> map = ModelConverter.extractCapabilityPropertiesFromGroups(currComponent.getGroups(), true);
3425 map.putAll(ModelConverter.extractCapabilityProperteisFromInstances(currComponent.getComponentInstances(), true));
3429 private Optional<MapCapabilityProperty> convertComponentInstanceProperties(Component component, String instanceId) {
3430 return component.fetchInstanceById(instanceId)
3431 .map(ci -> ModelConverter.convertToMapOfMapCapabilityProperties(ci.getCapabilities(), instanceId, ci.getOriginType().isAtomicType()));
3434 public Either<PolicyDefinition, StorageOperationStatus> associatePolicyToComponent(String componentId, PolicyDefinition policyDefinition,
3436 Either<PolicyDefinition, StorageOperationStatus> result = null;
3437 Either<GraphVertex, JanusGraphOperationStatus> getVertexEither;
3438 getVertexEither = janusGraphDao.getVertexById(componentId, JsonParseFlagEnum.ParseMetadata);
3439 if (getVertexEither.isRight()) {
3440 log.error(COULDNT_FETCH_A_COMPONENT_WITH_AND_UNIQUE_ID_ERROR, componentId, getVertexEither.right().value());
3441 result = Either.right(DaoStatusConverter.convertJanusGraphStatusToStorageStatus(getVertexEither.right().value()));
3443 if (getVertexEither.left().value().getLabel() != VertexTypeEnum.TOPOLOGY_TEMPLATE) {
3444 log.error("Policy association to component of Tosca type {} is not allowed. ", getVertexEither.left().value().getLabel());
3445 result = Either.right(StorageOperationStatus.BAD_REQUEST);
3448 if (result == null) {
3449 StorageOperationStatus status = topologyTemplateOperation
3450 .addPolicyToToscaElement(getVertexEither.left().value(), policyDefinition, counter);
3451 if (status != StorageOperationStatus.OK) {
3452 return Either.right(status);
3455 if (result == null) {
3456 result = Either.left(policyDefinition);
3461 public StorageOperationStatus associatePoliciesToComponent(String componentId, List<PolicyDefinition> policies) {
3462 log.debug("#associatePoliciesToComponent - associating policies for component {}.", componentId);
3463 return janusGraphDao.getVertexById(componentId, JsonParseFlagEnum.ParseMetadata)
3464 .either(containerVertex -> topologyTemplateOperation.addPoliciesToToscaElement(containerVertex, policies),
3465 DaoStatusConverter::convertJanusGraphStatusToStorageStatus);
3468 public Either<PolicyDefinition, StorageOperationStatus> updatePolicyOfComponent(String componentId, PolicyDefinition policyDefinition,
3469 PromoteVersionEnum promoteVersionEnum) {
3470 Either<PolicyDefinition, StorageOperationStatus> result = null;
3471 Either<GraphVertex, JanusGraphOperationStatus> getVertexEither;
3472 getVertexEither = janusGraphDao.getVertexById(componentId, JsonParseFlagEnum.NoParse);
3473 if (getVertexEither.isRight()) {
3474 log.error(COULDNT_FETCH_A_COMPONENT_WITH_AND_UNIQUE_ID_ERROR, componentId, getVertexEither.right().value());
3475 result = Either.right(DaoStatusConverter.convertJanusGraphStatusToStorageStatus(getVertexEither.right().value()));
3477 if (result == null) {
3478 policyDefinition.setVersion(GroupUtils.updateVersion(promoteVersionEnum, policyDefinition.getVersion()));
3479 StorageOperationStatus status = topologyTemplateOperation.updatePolicyOfToscaElement(getVertexEither.left().value(), policyDefinition);
3480 if (status != StorageOperationStatus.OK) {
3481 return Either.right(status);
3484 if (result == null) {
3485 result = Either.left(policyDefinition);
3490 public StorageOperationStatus updatePoliciesOfComponent(String componentId, List<PolicyDefinition> policyDefinition) {
3491 log.debug("#updatePoliciesOfComponent - updating policies for component {}", componentId);
3492 return janusGraphDao.getVertexById(componentId, JsonParseFlagEnum.NoParse).right()
3493 .map(DaoStatusConverter::convertJanusGraphStatusToStorageStatus)
3494 .either(containerVertex -> topologyTemplateOperation.updatePoliciesOfToscaElement(containerVertex, policyDefinition), err -> err);
3497 public StorageOperationStatus removePolicyFromComponent(String componentId, String policyId) {
3498 StorageOperationStatus status = null;
3499 Either<GraphVertex, JanusGraphOperationStatus> getVertexEither = janusGraphDao.getVertexById(componentId, JsonParseFlagEnum.NoParse);
3500 if (getVertexEither.isRight()) {
3501 log.error(COULDNT_FETCH_A_COMPONENT_WITH_AND_UNIQUE_ID_ERROR, componentId, getVertexEither.right().value());
3502 status = DaoStatusConverter.convertJanusGraphStatusToStorageStatus(getVertexEither.right().value());
3504 if (status == null) {
3505 status = topologyTemplateOperation.removePolicyFromToscaElement(getVertexEither.left().value(), policyId);
3510 public boolean canAddGroups(String componentId) {
3511 GraphVertex vertex = janusGraphDao.getVertexById(componentId).left().on(this::onJanusGraphError);
3512 return topologyTemplateOperation.hasEdgeOfType(vertex, EdgeLabelEnum.GROUPS);
3515 GraphVertex onJanusGraphError(JanusGraphOperationStatus toe) {
3516 throw new StorageException(DaoStatusConverter.convertJanusGraphStatusToStorageStatus(toe));
3519 public CatalogUpdateTimestamp updateCatalogTimes() {
3520 long now = System.currentTimeMillis();
3521 GraphVertex catalogRoot = janusGraphDao.getVertexByLabel(VertexTypeEnum.CATALOG_ROOT).left().on(this::onJanusGraphError);
3522 Long currentTime = (Long) catalogRoot.getMetadataProperty(GraphPropertyEnum.CURRENT_CATALOG_UPDATE_TIME);
3523 catalogRoot.addMetadataProperty(GraphPropertyEnum.PREV_CATALOG_UPDATE_TIME, currentTime);
3524 catalogRoot.addMetadataProperty(GraphPropertyEnum.CURRENT_CATALOG_UPDATE_TIME, now);
3525 janusGraphDao.updateVertex(catalogRoot).left().on(this::onJanusGraphError);
3526 return new CatalogUpdateTimestamp(currentTime, now);
3529 public CatalogUpdateTimestamp getCatalogTimes() {
3530 GraphVertex catalogRoot = janusGraphDao.getVertexByLabel(VertexTypeEnum.CATALOG_ROOT).left().on(this::onJanusGraphError);
3531 Long currentTime = (Long) catalogRoot.getMetadataProperty(GraphPropertyEnum.CURRENT_CATALOG_UPDATE_TIME);
3532 Long prevTime = (Long) catalogRoot.getMetadataProperty(GraphPropertyEnum.PREV_CATALOG_UPDATE_TIME);
3533 return new CatalogUpdateTimestamp(prevTime == null ? 0 : prevTime.longValue(), currentTime == null ? 0 : currentTime.longValue());
3536 public void updateNamesOfCalculatedCapabilitiesRequirements(String componentId) {
3537 topologyTemplateOperation.updateNamesOfCalculatedCapabilitiesRequirements(componentId, getTopologyTemplate(componentId));
3540 public void revertNamesOfCalculatedCapabilitiesRequirements(String componentId) {
3541 topologyTemplateOperation.revertNamesOfCalculatedCapabilitiesRequirements(componentId, getTopologyTemplate(componentId));
3544 private TopologyTemplate getTopologyTemplate(String componentId) {
3545 return (TopologyTemplate) topologyTemplateOperation.getToscaElement(componentId, getFilterComponentWithCapProperties()).left()
3546 .on(this::throwStorageException);
3549 private ComponentParametersView getFilterComponentWithCapProperties() {
3550 ComponentParametersView filter = new ComponentParametersView();
3551 filter.setIgnoreCapabiltyProperties(false);
3555 private ToscaElement throwStorageException(StorageOperationStatus status) {
3556 throw new StorageException(status);
3559 public Either<Boolean, StorageOperationStatus> isComponentInUse(String componentId) {
3560 final List<EdgeLabelEnum> forbiddenEdgeLabelEnums = Arrays
3561 .asList(EdgeLabelEnum.INSTANCE_OF, EdgeLabelEnum.PROXY_OF, EdgeLabelEnum.ALLOTTED_OF);
3562 Either<GraphVertex, JanusGraphOperationStatus> vertexById = janusGraphDao.getVertexById(componentId);
3563 if (vertexById.isLeft()) {
3564 for (EdgeLabelEnum edgeLabelEnum : forbiddenEdgeLabelEnums) {
3565 Iterator<Edge> edgeItr = vertexById.left().value().getVertex().edges(Direction.IN, edgeLabelEnum.name());
3566 if (edgeItr != null && edgeItr.hasNext()) {
3567 return Either.left(true);
3571 return Either.left(false);
3574 public Either<List<Component>, StorageOperationStatus> getComponentListByInvariantUuid(String componentInvariantUuid,
3575 Map<GraphPropertyEnum, Object> additionalPropertiesToMatch) {
3576 Map<GraphPropertyEnum, Object> propertiesToMatch = new EnumMap<>(GraphPropertyEnum.class);
3577 if (MapUtils.isNotEmpty(additionalPropertiesToMatch)) {
3578 propertiesToMatch.putAll(additionalPropertiesToMatch);
3580 propertiesToMatch.put(GraphPropertyEnum.INVARIANT_UUID, componentInvariantUuid);
3581 Either<List<GraphVertex>, JanusGraphOperationStatus> vertexEither = janusGraphDao
3582 .getByCriteria(null, propertiesToMatch, JsonParseFlagEnum.ParseMetadata);
3583 if (vertexEither.isRight()) {
3584 log.debug("Couldn't fetch metadata for component with type {} and invariantUUId {}, error: {}", componentInvariantUuid,
3585 vertexEither.right().value());
3586 return Either.right(DaoStatusConverter.convertJanusGraphStatusToStorageStatus(vertexEither.right().value()));
3588 List<GraphVertex> vertexList = vertexEither.isLeft() ? vertexEither.left().value() : null;
3589 if (vertexList == null || vertexList.isEmpty()) {
3590 log.debug("Component with invariantUUId {} was not found", componentInvariantUuid);
3591 return Either.right(StorageOperationStatus.NOT_FOUND);
3593 ArrayList<Component> components = new ArrayList<>();
3594 for (GraphVertex vertex : vertexList) {
3595 Either<Component, StorageOperationStatus> toscaElementByOperation = getToscaElementByOperation(vertex);
3596 if (toscaElementByOperation.isRight()) {
3597 log.debug("Could not fetch the following Component by Invariant UUID {}", vertex.getUniqueId());
3598 return Either.right(toscaElementByOperation.right().value());
3600 components.add(toscaElementByOperation.left().value());
3602 return Either.left(components);
3605 public Either<List<Component>, StorageOperationStatus> getParentComponents(String componentId) {
3606 List<Component> parentComponents = new ArrayList<>();
3607 final List<EdgeLabelEnum> relationEdgeLabelEnums = Arrays.asList(EdgeLabelEnum.INSTANCE_OF, EdgeLabelEnum.PROXY_OF);
3608 Either<GraphVertex, JanusGraphOperationStatus> vertexById = janusGraphDao.getVertexById(componentId);
3609 if (vertexById.isLeft()) {
3610 for (EdgeLabelEnum edgeLabelEnum : relationEdgeLabelEnums) {
3611 Either<GraphVertex, JanusGraphOperationStatus> parentVertexEither = janusGraphDao
3612 .getParentVertex(vertexById.left().value(), edgeLabelEnum, JsonParseFlagEnum.ParseJson);
3613 if (parentVertexEither.isLeft()) {
3614 Either<Component, StorageOperationStatus> componentEither = getToscaElement(parentVertexEither.left().value().getUniqueId());
3615 if (componentEither.isLeft()) {
3616 parentComponents.add(componentEither.left().value());
3621 return Either.left(parentComponents);
3624 public void updateCapReqPropertiesOwnerId(String componentId) {
3625 topologyTemplateOperation.updateCapReqPropertiesOwnerId(componentId, getTopologyTemplate(componentId));
3628 public <T extends Component> Either<T, StorageOperationStatus> getLatestByServiceName(String serviceName) {
3629 return getLatestByName(GraphPropertyEnum.NAME, serviceName, null);