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 static org.openecomp.sdc.be.utils.TypeUtils.setField;
24 import com.google.gson.Gson;
25 import com.google.gson.reflect.TypeToken;
26 import fj.data.Either;
27 import java.lang.reflect.Type;
28 import java.util.ArrayList;
29 import java.util.Collections;
30 import java.util.EnumMap;
31 import java.util.HashMap;
32 import java.util.HashSet;
33 import java.util.Iterator;
34 import java.util.List;
36 import java.util.Map.Entry;
37 import java.util.Optional;
39 import java.util.stream.Collectors;
40 import org.apache.commons.collections4.CollectionUtils;
41 import org.apache.commons.collections4.MapUtils;
42 import org.apache.tinkerpop.gremlin.structure.Direction;
43 import org.apache.tinkerpop.gremlin.structure.Edge;
44 import org.apache.tinkerpop.gremlin.structure.Vertex;
45 import org.apache.tinkerpop.gremlin.structure.VertexProperty;
46 import org.janusgraph.core.JanusGraphVertex;
47 import org.openecomp.sdc.be.config.ConfigurationManager;
48 import org.openecomp.sdc.be.dao.janusgraph.JanusGraphOperationStatus;
49 import org.openecomp.sdc.be.dao.jsongraph.GraphVertex;
50 import org.openecomp.sdc.be.dao.jsongraph.types.EdgeLabelEnum;
51 import org.openecomp.sdc.be.dao.jsongraph.types.EdgePropertyEnum;
52 import org.openecomp.sdc.be.dao.jsongraph.types.JsonParseFlagEnum;
53 import org.openecomp.sdc.be.dao.jsongraph.types.VertexTypeEnum;
54 import org.openecomp.sdc.be.dao.jsongraph.utils.JsonParserUtils;
55 import org.openecomp.sdc.be.dao.neo4j.GraphPropertiesDictionary;
56 import org.openecomp.sdc.be.datatypes.category.MetadataKeyDataDefinition;
57 import org.openecomp.sdc.be.datatypes.elements.AdditionalInfoParameterDataDefinition;
58 import org.openecomp.sdc.be.datatypes.elements.ArtifactDataDefinition;
59 import org.openecomp.sdc.be.datatypes.elements.DataTypeDataDefinition;
60 import org.openecomp.sdc.be.datatypes.elements.PropertyDataDefinition;
61 import org.openecomp.sdc.be.datatypes.enums.ComponentTypeEnum;
62 import org.openecomp.sdc.be.datatypes.enums.GraphPropertyEnum;
63 import org.openecomp.sdc.be.datatypes.enums.JsonPresentationFields;
64 import org.openecomp.sdc.be.datatypes.enums.ResourceTypeEnum;
65 import org.openecomp.sdc.be.datatypes.tosca.ToscaDataDefinition;
66 import org.openecomp.sdc.be.model.ComponentParametersView;
67 import org.openecomp.sdc.be.model.DataTypeDefinition;
68 import org.openecomp.sdc.be.model.LifecycleStateEnum;
69 import org.openecomp.sdc.be.model.catalog.CatalogComponent;
70 import org.openecomp.sdc.be.model.category.CategoryDefinition;
71 import org.openecomp.sdc.be.model.category.SubCategoryDefinition;
72 import org.openecomp.sdc.be.model.jsonjanusgraph.datamodel.NodeType;
73 import org.openecomp.sdc.be.model.jsonjanusgraph.datamodel.TopologyTemplate;
74 import org.openecomp.sdc.be.model.jsonjanusgraph.datamodel.ToscaElement;
75 import org.openecomp.sdc.be.model.jsonjanusgraph.datamodel.ToscaElementTypeEnum;
76 import org.openecomp.sdc.be.model.jsonjanusgraph.operations.exception.ModelOperationExceptionSupplier;
77 import org.openecomp.sdc.be.model.operations.api.StorageOperationStatus;
78 import org.openecomp.sdc.be.model.operations.impl.DaoStatusConverter;
79 import org.openecomp.sdc.be.model.operations.impl.ModelOperation;
80 import org.openecomp.sdc.be.model.operations.impl.UniqueIdBuilder;
81 import org.openecomp.sdc.be.utils.TypeUtils;
82 import org.openecomp.sdc.be.utils.TypeUtils.ToscaTagNamesEnum;
83 import org.openecomp.sdc.common.jsongraph.util.CommonUtility;
84 import org.openecomp.sdc.common.jsongraph.util.CommonUtility.LogLevelEnum;
85 import org.openecomp.sdc.common.log.wrappers.Logger;
86 import org.openecomp.sdc.common.util.ValidationUtils;
87 import org.springframework.beans.factory.annotation.Autowired;
88 import org.springframework.util.StopWatch;
90 public abstract class ToscaElementOperation extends BaseOperation {
92 private static final String FAILED_TO_FETCH_FOR_TOSCA_ELEMENT_WITH_ID_ERROR = "failed to fetch {} for tosca element with id {}, error {}";
93 private static final String CANNOT_FIND_USER_IN_THE_GRAPH_STATUS_IS = "Cannot find user {} in the graph. status is {}";
94 private static final String FAILED_TO_CREATE_EDGE_WITH_LABEL_FROM_USER_VERTEX_TO_TOSCA_ELEMENT_VERTEX_ON_GRAPH_STATUS_IS = "Failed to create edge with label {} from user vertex {} to tosca element vertex {} on graph. Status is {}. ";
95 private static final String FAILED_TO_GET_CREATOR_VERTEX_OF_TOSCA_ELEMENT_VERTEX_ON_GRAPH_STATUS_IS = "Failed to get creator vertex with label {} of tosca element vertex {} on graph. Status is {}. ";
96 private static final Gson gson = new Gson();
97 private static Logger log = Logger.getLogger(ToscaElementOperation.class.getName());
99 protected CategoryOperation categoryOperation;
101 protected ModelOperation modelOperation;
103 public static DataTypeDefinition createDataType(final String dataTypeName) {
104 final DataTypeDefinition dataType = new DataTypeDefinition();
105 dataType.setName(dataTypeName);
109 public static DataTypeDefinition createDataTypeDefinitionWithName(final Entry<String, Object> attributeNameValue) {
110 final Map<String, Object> attributeMap = (Map<String, Object>) attributeNameValue.getValue();
111 final DataTypeDefinition dataType = createDataType(attributeNameValue.getKey());
112 setField(attributeMap, TypeUtils.ToscaTagNamesEnum.DESCRIPTION, dataType::setDescription);
113 setField(attributeMap, TypeUtils.ToscaTagNamesEnum.DERIVED_FROM_NAME, dataType::setDerivedFromName);
114 // TODO - find the way to set the properties
116 // CommonImportManager.setProperties(attributeMap, dataType::setProperties);
117 final Object derivedFrom = attributeMap.get(JsonPresentationFields.DERIVED_FROM.getPresentation());
118 if (derivedFrom instanceof Map) {
119 final Map<String, Object> derivedFromMap = (Map<String, Object>) derivedFrom;
120 final DataTypeDefinition parentDataTypeDataDefinition = new DataTypeDefinition();
121 parentDataTypeDataDefinition.setName((String) derivedFromMap.get(JsonPresentationFields.NAME.getPresentation()));
122 parentDataTypeDataDefinition.setUniqueId((String) derivedFromMap.get(JsonPresentationFields.UNIQUE_ID.getPresentation()));
123 parentDataTypeDataDefinition.setCreationTime((Long) derivedFromMap.get(JsonPresentationFields.CREATION_TIME.getPresentation()));
124 parentDataTypeDataDefinition.setModificationTime((Long) derivedFromMap.get(JsonPresentationFields.MODIFICATION_TIME.getPresentation()));
125 dataType.setDerivedFrom(parentDataTypeDataDefinition);
130 protected Gson getGson() {
134 protected Either<GraphVertex, StorageOperationStatus> getComponentByLabelAndId(String uniqueId, ToscaElementTypeEnum nodeType,
135 JsonParseFlagEnum parseFlag) {
136 Map<GraphPropertyEnum, Object> propertiesToMatch = new EnumMap<>(GraphPropertyEnum.class);
137 propertiesToMatch.put(GraphPropertyEnum.UNIQUE_ID, uniqueId);
138 VertexTypeEnum vertexType = ToscaElementTypeEnum.getVertexTypeByToscaType(nodeType);
139 Either<List<GraphVertex>, JanusGraphOperationStatus> getResponse = janusGraphDao.getByCriteria(vertexType, propertiesToMatch, parseFlag);
140 if (getResponse.isRight()) {
141 log.debug("Couldn't fetch component with type {} and unique id {}, error: {}", vertexType, uniqueId, getResponse.right().value());
142 return Either.right(DaoStatusConverter.convertJanusGraphStatusToStorageStatus(getResponse.right().value()));
144 List<GraphVertex> componentList = getResponse.left().value();
145 if (componentList.isEmpty()) {
146 log.debug("Component with type {} and unique id {} was not found", vertexType, uniqueId);
147 return Either.right(StorageOperationStatus.NOT_FOUND);
149 GraphVertex vertexG = componentList.get(0);
150 return Either.left(vertexG);
153 public Either<ToscaElement, StorageOperationStatus> getToscaElement(String uniqueId) {
154 return getToscaElement(uniqueId, new ComponentParametersView());
157 public Either<GraphVertex, StorageOperationStatus> markComponentToDelete(GraphVertex componentToDelete) {
158 Boolean isDeleted = (Boolean) componentToDelete.getMetadataProperty(GraphPropertyEnum.IS_DELETED);
159 if (isDeleted != null && isDeleted && !(Boolean) componentToDelete.getMetadataProperty(GraphPropertyEnum.IS_HIGHEST_VERSION)) {
160 // component already marked for delete
162 componentToDelete.addMetadataProperty(GraphPropertyEnum.IS_DELETED, Boolean.TRUE);
163 componentToDelete.setJsonMetadataField(JsonPresentationFields.LAST_UPDATE_DATE, System.currentTimeMillis());
164 Either<GraphVertex, JanusGraphOperationStatus> updateNode = janusGraphDao.updateVertex(componentToDelete);
165 StorageOperationStatus updateComponent;
166 if (updateNode.isRight()) {
167 log.debug("Failed to update component {}. status is {}", componentToDelete.getUniqueId(), updateNode.right().value());
168 updateComponent = DaoStatusConverter.convertJanusGraphStatusToStorageStatus(updateNode.right().value());
169 return Either.right(updateComponent);
172 return Either.left(componentToDelete);
176 * Performs a shadow clone of previousToscaElement
178 * @param previousToscaElement
179 * @param nextToscaElement
183 public Either<GraphVertex, StorageOperationStatus> cloneToscaElement(GraphVertex previousToscaElement, GraphVertex nextToscaElement,
185 Either<GraphVertex, StorageOperationStatus> result = null;
186 GraphVertex createdToscaElementVertex = null;
187 JanusGraphOperationStatus status;
188 Either<GraphVertex, JanusGraphOperationStatus> createNextVersionRes = janusGraphDao.createVertex(nextToscaElement);
189 if (createNextVersionRes.isRight()) {
190 status = createNextVersionRes.right().value();
191 CommonUtility.addRecordToLog(log, LogLevelEnum.DEBUG, "Failed to create tosca element vertex {} with version {} on graph. Status is {}. ",
192 previousToscaElement.getMetadataProperty(GraphPropertyEnum.NORMALIZED_NAME),
193 previousToscaElement.getMetadataProperty(GraphPropertyEnum.VERSION), status);
194 result = Either.right(DaoStatusConverter.convertJanusGraphStatusToStorageStatus(status));
196 if (result == null) {
197 createdToscaElementVertex = createNextVersionRes.left().value();
198 final Map<EdgePropertyEnum, Object> properties = new EnumMap<>(EdgePropertyEnum.class);
199 properties.put(EdgePropertyEnum.STATE, createdToscaElementVertex.getMetadataProperty(GraphPropertyEnum.STATE));
200 status = janusGraphDao.createEdge(user.getVertex(), createdToscaElementVertex.getVertex(), EdgeLabelEnum.STATE, properties);
201 if (status != JanusGraphOperationStatus.OK) {
202 CommonUtility.addRecordToLog(log, LogLevelEnum.DEBUG,
203 FAILED_TO_CREATE_EDGE_WITH_LABEL_FROM_USER_VERTEX_TO_TOSCA_ELEMENT_VERTEX_ON_GRAPH_STATUS_IS, EdgeLabelEnum.STATE,
204 user.getUniqueId(), previousToscaElement.getMetadataProperty(GraphPropertyEnum.NORMALIZED_NAME), status);
205 result = Either.right(DaoStatusConverter.convertJanusGraphStatusToStorageStatus(status));
208 if (result == null) {
210 VertexTypeEnum.TOPOLOGY_TEMPLATE.equals(previousToscaElement.getLabel())
211 ? createModelEdge(previousToscaElement, nextToscaElement, user, createdToscaElementVertex, EdgeLabelEnum.MODEL)
212 : createModelEdge(previousToscaElement, nextToscaElement, user, createdToscaElementVertex, EdgeLabelEnum.MODEL_ELEMENT);
214 if (result == null) {
215 status = janusGraphDao.createEdge(user.getVertex(), createdToscaElementVertex.getVertex(), EdgeLabelEnum.LAST_MODIFIER, new HashMap<>());
216 if (status != JanusGraphOperationStatus.OK) {
217 CommonUtility.addRecordToLog(log, LogLevelEnum.DEBUG,
218 FAILED_TO_CREATE_EDGE_WITH_LABEL_FROM_USER_VERTEX_TO_TOSCA_ELEMENT_VERTEX_ON_GRAPH_STATUS_IS, EdgeLabelEnum.LAST_MODIFIER,
219 user.getUniqueId(), nextToscaElement.getMetadataProperty(GraphPropertyEnum.NORMALIZED_NAME), status);
220 result = Either.right(DaoStatusConverter.convertJanusGraphStatusToStorageStatus(status));
223 if (result == null) {
224 Either<GraphVertex, JanusGraphOperationStatus> creatorVertexRes = janusGraphDao
225 .getParentVertex(previousToscaElement, EdgeLabelEnum.CREATOR, JsonParseFlagEnum.NoParse);
226 if (creatorVertexRes.isRight()) {
227 status = creatorVertexRes.right().value();
228 CommonUtility.addRecordToLog(log, LogLevelEnum.DEBUG, FAILED_TO_GET_CREATOR_VERTEX_OF_TOSCA_ELEMENT_VERTEX_ON_GRAPH_STATUS_IS,
229 EdgeLabelEnum.CREATOR, nextToscaElement.getMetadataProperty(GraphPropertyEnum.NORMALIZED_NAME), status);
230 result = Either.right(DaoStatusConverter.convertJanusGraphStatusToStorageStatus(status));
232 status = janusGraphDao
233 .createEdge(creatorVertexRes.left().value().getVertex(), createdToscaElementVertex.getVertex(), EdgeLabelEnum.CREATOR,
235 if (status != JanusGraphOperationStatus.OK) {
236 CommonUtility.addRecordToLog(log, LogLevelEnum.DEBUG,
237 FAILED_TO_CREATE_EDGE_WITH_LABEL_FROM_USER_VERTEX_TO_TOSCA_ELEMENT_VERTEX_ON_GRAPH_STATUS_IS, EdgeLabelEnum.CREATOR,
238 user.getUniqueId(), nextToscaElement.getMetadataProperty(GraphPropertyEnum.NORMALIZED_NAME), status);
239 result = Either.right(DaoStatusConverter.convertJanusGraphStatusToStorageStatus(status));
242 if (result == null) {
243 Iterator<Edge> edgesToCopyIter = previousToscaElement.getVertex().edges(Direction.OUT);
244 while (edgesToCopyIter.hasNext()) {
245 Edge currEdge = edgesToCopyIter.next();
246 Vertex currVertex = currEdge.inVertex();
247 status = janusGraphDao
248 .createEdge(createdToscaElementVertex.getVertex(), currVertex, EdgeLabelEnum.getEdgeLabelEnum(currEdge.label()), currEdge);
249 if (status != JanusGraphOperationStatus.OK) {
250 CommonUtility.addRecordToLog(log, LogLevelEnum.DEBUG,
251 "Failed to create edge with label {} from tosca element vertex {} to vertex with label {} on graph. Status is {}. ",
252 currEdge.label(), createdToscaElementVertex.getUniqueId(), currVertex.property(GraphPropertyEnum.LABEL.getProperty()),
254 result = Either.right(DaoStatusConverter.convertJanusGraphStatusToStorageStatus(status));
259 if (result == null) {
260 result = Either.left(createdToscaElementVertex);
263 .addRecordToLog(log, LogLevelEnum.DEBUG, "Failed to clone tosca element {} with the name {}. ", previousToscaElement.getUniqueId(),
264 previousToscaElement.getMetadataProperty(GraphPropertyEnum.NORMALIZED_NAME));
270 * Creates the MODEL in case it exits on the previous version
271 * @param previousToscaElement previous element version
272 * @param nextToscaElement latest element version
274 * @param createdToscaElementVertex created tosca element
275 * @param edgeLabelEnum
278 private Either<GraphVertex, StorageOperationStatus> createModelEdge(final GraphVertex previousToscaElement,
279 final GraphVertex nextToscaElement, GraphVertex user,
280 final GraphVertex createdToscaElementVertex,
281 final EdgeLabelEnum edgeLabelEnum) {
282 Either<GraphVertex, StorageOperationStatus> result = null;
283 final Either<GraphVertex, JanusGraphOperationStatus> modelElementVertexResponse = janusGraphDao
284 .getParentVertex(previousToscaElement, edgeLabelEnum, JsonParseFlagEnum.NoParse);
285 if (modelElementVertexResponse.isLeft()) {
286 final JanusGraphOperationStatus status = janusGraphDao
287 .createEdge(modelElementVertexResponse.left().value().getVertex(), createdToscaElementVertex.getVertex(), edgeLabelEnum,
289 if (JanusGraphOperationStatus.OK != status) {
290 CommonUtility.addRecordToLog(log, LogLevelEnum.DEBUG,
291 FAILED_TO_CREATE_EDGE_WITH_LABEL_FROM_USER_VERTEX_TO_TOSCA_ELEMENT_VERTEX_ON_GRAPH_STATUS_IS, edgeLabelEnum,
292 user.getUniqueId(), nextToscaElement.getMetadataProperty(GraphPropertyEnum.NORMALIZED_NAME), status);
293 result = Either.right(DaoStatusConverter.convertJanusGraphStatusToStorageStatus(status));
299 protected JanusGraphOperationStatus setLastModifierFromGraph(GraphVertex componentV, ToscaElement toscaElement) {
300 Either<GraphVertex, JanusGraphOperationStatus> parentVertex = janusGraphDao
301 .getParentVertex(componentV, EdgeLabelEnum.LAST_MODIFIER, JsonParseFlagEnum.NoParse);
302 if (parentVertex.isRight()) {
303 log.debug("Failed to fetch last modifier for tosca element with id {} error {}", componentV.getUniqueId(), parentVertex.right().value());
304 return parentVertex.right().value();
306 GraphVertex userV = parentVertex.left().value();
307 String userId = (String) userV.getMetadataProperty(GraphPropertyEnum.USERID);
308 toscaElement.setLastUpdaterUserId(userId);
309 toscaElement.setLastUpdaterFullName(buildFullName(userV));
310 return JanusGraphOperationStatus.OK;
313 public String buildFullName(GraphVertex userV) {
314 String fullName = (String) userV.getMetadataProperty(GraphPropertyEnum.FIRST_NAME);
315 if (fullName == null) {
318 fullName = fullName + " ";
320 String lastName = (String) userV.getMetadataProperty(GraphPropertyEnum.LAST_NAME);
321 if (lastName != null) {
322 fullName += lastName;
327 protected JanusGraphOperationStatus setCreatorFromGraph(GraphVertex componentV, ToscaElement toscaElement) {
328 Either<GraphVertex, JanusGraphOperationStatus> parentVertex = janusGraphDao
329 .getParentVertex(componentV, EdgeLabelEnum.CREATOR, JsonParseFlagEnum.NoParse);
330 if (parentVertex.isRight()) {
331 log.debug("Failed to fetch creator for tosca element with id {} error {}", componentV.getUniqueId(), parentVertex.right().value());
332 return parentVertex.right().value();
334 GraphVertex userV = parentVertex.left().value();
335 String creatorUserId = (String) userV.getMetadataProperty(GraphPropertyEnum.USERID);
336 toscaElement.setCreatorUserId(creatorUserId);
337 toscaElement.setCreatorFullName(buildFullName(userV));
338 return JanusGraphOperationStatus.OK;
341 protected <T extends ToscaElement> T getResourceMetaDataFromResource(T toscaElement) {
342 if (toscaElement.getNormalizedName() == null || toscaElement.getNormalizedName().isEmpty()) {
343 toscaElement.setNormalizedName(ValidationUtils.normaliseComponentName(toscaElement.getName()));
345 if (toscaElement.getSystemName() == null || toscaElement.getSystemName().isEmpty()) {
346 toscaElement.setSystemName(ValidationUtils.convertToSystemName(toscaElement.getName()));
348 LifecycleStateEnum lifecycleStateEnum = toscaElement.getLifecycleState();
349 if (lifecycleStateEnum == null) {
350 toscaElement.setLifecycleState(LifecycleStateEnum.NOT_CERTIFIED_CHECKOUT);
352 long currentDate = System.currentTimeMillis();
353 if (toscaElement.getCreationDate() == null) {
354 toscaElement.setCreationDate(currentDate);
356 toscaElement.setLastUpdateDate(currentDate);
360 protected void fillCommonMetadata(GraphVertex nodeTypeVertex, ToscaElement toscaElement) {
361 if (toscaElement.isHighestVersion() == null) {
362 toscaElement.setHighestVersion(true);
364 nodeTypeVertex.addMetadataProperty(GraphPropertyEnum.IS_DELETED, toscaElement.getMetadataValue(JsonPresentationFields.IS_DELETED));
365 nodeTypeVertex.addMetadataProperty(GraphPropertyEnum.IS_HIGHEST_VERSION,
366 toscaElement.getMetadataValueOrDefault(JsonPresentationFields.HIGHEST_VERSION, Boolean.TRUE));
367 nodeTypeVertex.addMetadataProperty(GraphPropertyEnum.STATE, toscaElement.getMetadataValue(JsonPresentationFields.LIFECYCLE_STATE));
368 nodeTypeVertex.addMetadataProperty(GraphPropertyEnum.RESOURCE_TYPE, toscaElement.getMetadataValue(JsonPresentationFields.RESOURCE_TYPE));
369 nodeTypeVertex.addMetadataProperty(GraphPropertyEnum.VERSION, toscaElement.getMetadataValue(JsonPresentationFields.VERSION));
370 nodeTypeVertex.addMetadataProperty(GraphPropertyEnum.NORMALIZED_NAME, toscaElement.getMetadataValue(JsonPresentationFields.NORMALIZED_NAME));
371 nodeTypeVertex.addMetadataProperty(GraphPropertyEnum.UNIQUE_ID, toscaElement.getMetadataValue(JsonPresentationFields.UNIQUE_ID));
373 .addMetadataProperty(GraphPropertyEnum.TOSCA_RESOURCE_NAME, toscaElement.getMetadataValue(JsonPresentationFields.TOSCA_RESOURCE_NAME));
374 nodeTypeVertex.addMetadataProperty(GraphPropertyEnum.UUID, toscaElement.getMetadataValue(JsonPresentationFields.UUID));
375 nodeTypeVertex.addMetadataProperty(GraphPropertyEnum.IS_ABSTRACT, toscaElement.getMetadataValue(JsonPresentationFields.IS_ABSTRACT));
376 nodeTypeVertex.addMetadataProperty(GraphPropertyEnum.INVARIANT_UUID, toscaElement.getMetadataValue(JsonPresentationFields.INVARIANT_UUID));
377 nodeTypeVertex.addMetadataProperty(GraphPropertyEnum.NAME, toscaElement.getMetadataValue(JsonPresentationFields.NAME));
378 nodeTypeVertex.addMetadataProperty(GraphPropertyEnum.SYSTEM_NAME, toscaElement.getMetadataValue(JsonPresentationFields.SYSTEM_NAME));
379 nodeTypeVertex.addMetadataProperty(GraphPropertyEnum.IS_ARCHIVED, toscaElement.getMetadataValue(JsonPresentationFields.IS_ARCHIVED));
380 nodeTypeVertex.addMetadataProperty(GraphPropertyEnum.ARCHIVE_TIME, toscaElement.getMetadataValue(JsonPresentationFields.ARCHIVE_TIME));
381 nodeTypeVertex.addMetadataProperty(GraphPropertyEnum.IS_VSP_ARCHIVED, toscaElement.getMetadataValue(JsonPresentationFields.IS_VSP_ARCHIVED));
382 nodeTypeVertex.addMetadataProperty(GraphPropertyEnum.MODEL, toscaElement.getMetadataValue(JsonPresentationFields.MODEL));
383 toscaElement.getMetadata().entrySet().stream().filter(e -> e.getValue() != null)
384 .forEach(e -> nodeTypeVertex.setJsonMetadataField(e.getKey(), e.getValue()));
385 nodeTypeVertex.setUniqueId(toscaElement.getUniqueId());
386 nodeTypeVertex.setType(toscaElement.getComponentType());
387 final String toscaVersion = toscaElement.getToscaVersion();
388 if (toscaVersion != null) {
389 nodeTypeVertex.setJsonMetadataField(JsonPresentationFields.TOSCA_DEFINITIONS_VERSION, toscaVersion);
391 final Map<String, DataTypeDataDefinition> dataTypes = toscaElement.getDataTypes();
392 if (MapUtils.isNotEmpty(dataTypes)) {
393 nodeTypeVertex.setJsonMetadataField(JsonPresentationFields.DATA_TYPES, dataTypes);
397 protected StorageOperationStatus assosiateToUsers(GraphVertex nodeTypeVertex, ToscaElement toscaElement) {
399 String userId = toscaElement.getCreatorUserId();
400 Either<GraphVertex, JanusGraphOperationStatus> findUser = findUserVertex(userId);
401 if (findUser.isRight()) {
402 JanusGraphOperationStatus status = findUser.right().value();
403 log.error(CANNOT_FIND_USER_IN_THE_GRAPH_STATUS_IS, userId, status);
404 return DaoStatusConverter.convertJanusGraphStatusToStorageStatus(status);
406 GraphVertex creatorVertex = findUser.left().value();
407 GraphVertex updaterVertex = creatorVertex;
408 String updaterId = toscaElement.getLastUpdaterUserId();
409 if (updaterId != null && !updaterId.equals(userId)) {
410 findUser = findUserVertex(updaterId);
411 if (findUser.isRight()) {
412 JanusGraphOperationStatus status = findUser.right().value();
413 log.error(CANNOT_FIND_USER_IN_THE_GRAPH_STATUS_IS, userId, status);
414 return DaoStatusConverter.convertJanusGraphStatusToStorageStatus(status);
416 updaterVertex = findUser.left().value();
419 Map<EdgePropertyEnum, Object> props = new EnumMap<>(EdgePropertyEnum.class);
420 props.put(EdgePropertyEnum.STATE, (String) toscaElement.getMetadataValue(JsonPresentationFields.LIFECYCLE_STATE));
421 JanusGraphOperationStatus result = janusGraphDao.createEdge(updaterVertex, nodeTypeVertex, EdgeLabelEnum.STATE, props);
422 log.debug("After associating user {} to resource {}. Edge type is {}", updaterVertex, nodeTypeVertex.getUniqueId(), EdgeLabelEnum.STATE);
423 if (JanusGraphOperationStatus.OK != result) {
424 return DaoStatusConverter.convertJanusGraphStatusToStorageStatus(result);
426 result = janusGraphDao.createEdge(updaterVertex, nodeTypeVertex, EdgeLabelEnum.LAST_MODIFIER, null);
427 log.debug("After associating user {} to resource {}. Edge type is {}", updaterVertex, nodeTypeVertex.getUniqueId(),
428 EdgeLabelEnum.LAST_MODIFIER);
429 if (!result.equals(JanusGraphOperationStatus.OK)) {
430 log.error("Failed to associate user {} to resource {}. Edge type is {}", updaterVertex, nodeTypeVertex.getUniqueId(),
431 EdgeLabelEnum.LAST_MODIFIER);
432 return DaoStatusConverter.convertJanusGraphStatusToStorageStatus(result);
434 toscaElement.setLastUpdaterUserId(toscaElement.getCreatorUserId());
435 toscaElement.setLastUpdaterFullName(toscaElement.getCreatorFullName());
436 result = janusGraphDao.createEdge(creatorVertex, nodeTypeVertex, EdgeLabelEnum.CREATOR, null);
437 log.debug("After associating user {} to resource {}. Edge type is {} ", creatorVertex, nodeTypeVertex.getUniqueId(), EdgeLabelEnum.CREATOR);
438 if (!result.equals(JanusGraphOperationStatus.OK)) {
439 log.error("Failed to associate user {} to resource {}. Edge type is {} ", creatorVertex, nodeTypeVertex.getUniqueId(),
440 EdgeLabelEnum.CREATOR);
441 return DaoStatusConverter.convertJanusGraphStatusToStorageStatus(result);
443 return StorageOperationStatus.OK;
446 protected StorageOperationStatus assosiateResourceMetadataToCategory(GraphVertex nodeTypeVertex, ToscaElement nodeType) {
447 String subcategoryName = nodeType.getCategories().get(0).getSubcategories().get(0).getName();
448 String categoryName = nodeType.getCategories().get(0).getName();
449 Either<GraphVertex, StorageOperationStatus> getCategoryVertex = getResourceCategoryVertex(nodeType.getUniqueId(), subcategoryName,
451 if (getCategoryVertex.isRight()) {
452 return getCategoryVertex.right().value();
454 GraphVertex subCategoryV = getCategoryVertex.left().value();
455 JanusGraphOperationStatus createEdge = janusGraphDao.createEdge(nodeTypeVertex, subCategoryV, EdgeLabelEnum.CATEGORY, new HashMap<>());
456 if (createEdge != JanusGraphOperationStatus.OK) {
457 log.trace("Failed to associate resource {} to category {} with id {}", nodeType.getUniqueId(), subcategoryName,
458 subCategoryV.getUniqueId());
459 return DaoStatusConverter.convertJanusGraphStatusToStorageStatus(createEdge);
461 return StorageOperationStatus.OK;
464 protected StorageOperationStatus associateComponentToModel(final GraphVertex nodeTypeVertex, final ToscaElement nodeType,
465 final EdgeLabelEnum edgeLabelEnum) {
466 if (nodeType.getMetadataValue(JsonPresentationFields.MODEL) == null) {
467 return StorageOperationStatus.OK;
469 final String model = ((String) nodeType.getMetadataValue(JsonPresentationFields.MODEL));
470 final JanusGraphOperationStatus createEdge = janusGraphDao.createEdge(getModelVertex(model), nodeTypeVertex, edgeLabelEnum, new HashMap<>());
471 if (createEdge != JanusGraphOperationStatus.OK) {
472 log.trace("Failed to associate resource {} to model {}", nodeType.getUniqueId(), model);
473 return DaoStatusConverter.convertJanusGraphStatusToStorageStatus(createEdge);
475 return StorageOperationStatus.OK;
478 private GraphVertex getModelVertex(final String modelName) {
479 log.debug("getModelVertex: fetching model {}", modelName);
480 final Optional<GraphVertex> modelVertexByNameOptional = modelOperation.findModelVertexByName(modelName);
481 if (modelVertexByNameOptional.isEmpty()) {
482 throw ModelOperationExceptionSupplier.invalidModel(modelName).get();
484 return modelVertexByNameOptional.get();
487 protected Either<GraphVertex, StorageOperationStatus> getResourceCategoryVertex(String elementId, String subcategoryName, String categoryName) {
488 Either<GraphVertex, StorageOperationStatus> category = categoryOperation.getCategory(categoryName, VertexTypeEnum.RESOURCE_CATEGORY);
489 if (category.isRight()) {
490 log.trace("Failed to fetch category {} for resource {} error {}", categoryName, elementId, category.right().value());
491 return Either.right(category.right().value());
493 GraphVertex categoryV = category.left().value();
494 if (subcategoryName != null) {
495 Either<GraphVertex, StorageOperationStatus> subCategory = categoryOperation.getSubCategoryForCategory(categoryV, subcategoryName);
496 if (subCategory.isRight()) {
497 log.trace("Failed to fetch subcategory {} of category for resource {} error {}", subcategoryName, categoryName, elementId,
498 subCategory.right().value());
499 return Either.right(subCategory.right().value());
501 GraphVertex subCategoryV = subCategory.left().value();
502 return Either.left(subCategoryV);
504 return Either.left(categoryV);
507 private StorageOperationStatus associateArtifactsToResource(GraphVertex nodeTypeVertex, ToscaElement toscaElement) {
508 Map<String, ArtifactDataDefinition> artifacts = toscaElement.getArtifacts();
509 Either<GraphVertex, StorageOperationStatus> status;
510 if (artifacts != null) {
511 artifacts.values().stream().filter(a -> a.getUniqueId() == null).forEach(a -> {
512 String uniqueId = UniqueIdBuilder
513 .buildPropertyUniqueId(nodeTypeVertex.getUniqueId().toLowerCase(), a.getArtifactLabel().toLowerCase());
514 a.setUniqueId(uniqueId);
516 status = associateElementToData(nodeTypeVertex, VertexTypeEnum.ARTIFACTS, EdgeLabelEnum.ARTIFACTS, artifacts);
517 if (status.isRight()) {
518 return status.right().value();
521 Map<String, ArtifactDataDefinition> toscaArtifacts = toscaElement.getToscaArtifacts();
522 if (toscaArtifacts != null) {
523 toscaArtifacts.values().stream().filter(a -> a.getUniqueId() == null).forEach(a -> {
524 String uniqueId = UniqueIdBuilder
525 .buildPropertyUniqueId(nodeTypeVertex.getUniqueId().toLowerCase(), a.getArtifactLabel().toLowerCase());
526 a.setUniqueId(uniqueId);
528 status = associateElementToData(nodeTypeVertex, VertexTypeEnum.TOSCA_ARTIFACTS, EdgeLabelEnum.TOSCA_ARTIFACTS, toscaArtifacts);
529 if (status.isRight()) {
530 return status.right().value();
533 Map<String, ArtifactDataDefinition> deploymentArtifacts = toscaElement.getDeploymentArtifacts();
534 if (deploymentArtifacts != null) {
535 deploymentArtifacts.values().stream().filter(a -> a.getUniqueId() == null).forEach(a -> {
536 String uniqueId = UniqueIdBuilder
537 .buildPropertyUniqueId(nodeTypeVertex.getUniqueId().toLowerCase(), a.getArtifactLabel().toLowerCase());
538 a.setUniqueId(uniqueId);
540 status = associateElementToData(nodeTypeVertex, VertexTypeEnum.DEPLOYMENT_ARTIFACTS, EdgeLabelEnum.DEPLOYMENT_ARTIFACTS,
541 deploymentArtifacts);
542 if (status.isRight()) {
543 return status.right().value();
546 return StorageOperationStatus.OK;
549 protected JanusGraphOperationStatus disassociateAndDeleteCommonElements(GraphVertex toscaElementVertex) {
550 JanusGraphOperationStatus status = janusGraphDao.disassociateAndDeleteLast(toscaElementVertex, Direction.OUT, EdgeLabelEnum.ARTIFACTS);
551 if (status != JanusGraphOperationStatus.OK) {
552 log.debug("Failed to disaccociate artifact for {} error {}", toscaElementVertex.getUniqueId(), status);
555 status = janusGraphDao.disassociateAndDeleteLast(toscaElementVertex, Direction.OUT, EdgeLabelEnum.TOSCA_ARTIFACTS);
556 if (status != JanusGraphOperationStatus.OK) {
557 log.debug("Failed to disaccociate tosca artifact for {} error {}", toscaElementVertex.getUniqueId(), status);
560 status = janusGraphDao.disassociateAndDeleteLast(toscaElementVertex, Direction.OUT, EdgeLabelEnum.DEPLOYMENT_ARTIFACTS);
561 if (status != JanusGraphOperationStatus.OK) {
562 log.debug("Failed to deployment artifact for {} error {}", toscaElementVertex.getUniqueId(), status);
565 status = janusGraphDao.disassociateAndDeleteLast(toscaElementVertex, Direction.OUT, EdgeLabelEnum.PROPERTIES);
566 if (status != JanusGraphOperationStatus.OK) {
567 log.debug("Failed to disaccociate properties for {} error {}", toscaElementVertex.getUniqueId(), status);
570 status = janusGraphDao.disassociateAndDeleteLast(toscaElementVertex, Direction.OUT, EdgeLabelEnum.ATTRIBUTES);
571 if (status != JanusGraphOperationStatus.OK) {
572 log.debug("Failed to disaccociate attributes for {} error {}", toscaElementVertex.getUniqueId(), status);
575 status = janusGraphDao.disassociateAndDeleteLast(toscaElementVertex, Direction.OUT, EdgeLabelEnum.ADDITIONAL_INFORMATION);
576 if (status != JanusGraphOperationStatus.OK) {
577 log.debug("Failed to disaccociate additional information for {} error {}", toscaElementVertex.getUniqueId(), status);
580 status = janusGraphDao.disassociateAndDeleteLast(toscaElementVertex, Direction.OUT, EdgeLabelEnum.CAPABILITIES);
581 if (status != JanusGraphOperationStatus.OK) {
582 log.debug("Failed to disaccociate capabilities for {} error {}", toscaElementVertex.getUniqueId(), status);
585 status = janusGraphDao.disassociateAndDeleteLast(toscaElementVertex, Direction.OUT, EdgeLabelEnum.REQUIREMENTS);
586 if (status != JanusGraphOperationStatus.OK) {
587 log.debug("Failed to disaccociate requirements for {} error {}", toscaElementVertex.getUniqueId(), status);
590 status = janusGraphDao.disassociateAndDeleteLast(toscaElementVertex, Direction.OUT, EdgeLabelEnum.FORWARDING_PATH);
591 if (status != JanusGraphOperationStatus.OK) {
592 log.debug("Failed to disaccociate requirements for {} error {}", toscaElementVertex.getUniqueId(), status);
595 return JanusGraphOperationStatus.OK;
598 protected StorageOperationStatus assosiateCommonForToscaElement(GraphVertex nodeTypeVertex, ToscaElement toscaElement) {
599 return assosiateCommonForToscaElement(nodeTypeVertex, toscaElement, null);
602 protected StorageOperationStatus assosiateCommonForToscaElement(GraphVertex nodeTypeVertex, ToscaElement toscaElement,
603 List<GraphVertex> derivedResources) {
604 StorageOperationStatus associateUsers = assosiateToUsers(nodeTypeVertex, toscaElement);
605 if (associateUsers != StorageOperationStatus.OK) {
606 return associateUsers;
608 StorageOperationStatus associateArtifacts = associateArtifactsToResource(nodeTypeVertex, toscaElement);
609 if (associateArtifacts != StorageOperationStatus.OK) {
610 return associateArtifacts;
612 StorageOperationStatus associateProperties = associatePropertiesToResource(nodeTypeVertex, toscaElement, derivedResources);
613 if (associateProperties != StorageOperationStatus.OK) {
614 return associateProperties;
616 StorageOperationStatus associateAdditionaInfo = associateAdditionalInfoToResource(nodeTypeVertex, toscaElement);
617 if (associateAdditionaInfo != StorageOperationStatus.OK) {
618 return associateAdditionaInfo;
620 if (needConnectToCatalog(toscaElement)) {
621 StorageOperationStatus associateToCatalog = associateToCatalogRoot(nodeTypeVertex);
622 if (associateToCatalog != StorageOperationStatus.OK) {
623 return associateToCatalog;
626 return StorageOperationStatus.OK;
629 private boolean needConnectToCatalog(ToscaElement toscaElement) {
630 Boolean isAbstract = (Boolean) toscaElement.getMetadataValue(JsonPresentationFields.IS_ABSTRACT);
631 if (isAbstract != null && isAbstract) {
634 return toscaElement.isHighestVersion();
637 private StorageOperationStatus associateToCatalogRoot(GraphVertex nodeTypeVertex) {
638 Either<GraphVertex, JanusGraphOperationStatus> catalog = janusGraphDao.getVertexByLabel(VertexTypeEnum.CATALOG_ROOT);
639 if (catalog.isRight()) {
640 log.debug("Failed to fetch catalog vertex. error {}", catalog.right().value());
641 return DaoStatusConverter.convertJanusGraphStatusToStorageStatus(catalog.right().value());
643 JanusGraphOperationStatus createEdge = janusGraphDao.createEdge(catalog.left().value(), nodeTypeVertex, EdgeLabelEnum.CATALOG_ELEMENT, null);
644 return DaoStatusConverter.convertJanusGraphStatusToStorageStatus(createEdge);
647 protected StorageOperationStatus associatePropertiesToResource(GraphVertex nodeTypeVertex, ToscaElement nodeType,
648 List<GraphVertex> derivedResources) {
649 // Note : currently only one derived supported!!!!
650 Either<Map<String, PropertyDataDefinition>, StorageOperationStatus> dataFromDerived = getDataFromDerived(derivedResources,
651 EdgeLabelEnum.PROPERTIES);
652 if (dataFromDerived.isRight()) {
653 return dataFromDerived.right().value();
655 Map<String, PropertyDataDefinition> propertiesAll = dataFromDerived.left().value();
656 Map<String, PropertyDataDefinition> properties = nodeType.getProperties();
657 if (properties != null) {
658 properties.values().stream().filter(p -> p.getUniqueId() == null).forEach(p -> {
659 String uid = UniqueIdBuilder.buildPropertyUniqueId(nodeTypeVertex.getUniqueId(), p.getName());
662 Either<Map<String, PropertyDataDefinition>, String> eitherMerged = ToscaDataDefinition.mergeDataMaps(propertiesAll, properties);
663 if (eitherMerged.isRight()) {
664 // TODO re-factor error handling - moving BL to operation resulted in loss of info about the invalid property
665 log.debug("property {} cannot be overriden", eitherMerged.right().value());
666 return StorageOperationStatus.INVALID_PROPERTY;
669 if (!propertiesAll.isEmpty()) {
670 Either<GraphVertex, StorageOperationStatus> assosiateElementToData = associateElementToData(nodeTypeVertex, VertexTypeEnum.PROPERTIES,
671 EdgeLabelEnum.PROPERTIES, propertiesAll);
672 if (assosiateElementToData.isRight()) {
673 return assosiateElementToData.right().value();
676 return StorageOperationStatus.OK;
679 private StorageOperationStatus associateAdditionalInfoToResource(GraphVertex nodeTypeVertex, ToscaElement nodeType) {
680 Map<String, AdditionalInfoParameterDataDefinition> additionalInformation = nodeType.getAdditionalInformation();
681 if (additionalInformation != null) {
682 Either<GraphVertex, StorageOperationStatus> assosiateElementToData = associateElementToData(nodeTypeVertex,
683 VertexTypeEnum.ADDITIONAL_INFORMATION, EdgeLabelEnum.ADDITIONAL_INFORMATION, additionalInformation);
684 if (assosiateElementToData.isRight()) {
685 return assosiateElementToData.right().value();
688 return StorageOperationStatus.OK;
691 protected <T extends ToscaDataDefinition> Either<Map<String, T>, StorageOperationStatus> getDataFromDerived(List<GraphVertex> derivedResources,
692 EdgeLabelEnum edge) {
693 Map<String, T> propertiesAll = new HashMap<>();
694 if (derivedResources != null && !derivedResources.isEmpty()) {
695 for (GraphVertex derived : derivedResources) {
696 Either<List<GraphVertex>, JanusGraphOperationStatus> derivedProperties = janusGraphDao
697 .getChildrenVertices(derived, edge, JsonParseFlagEnum.ParseJson);
698 if (derivedProperties.isRight()) {
699 if (derivedProperties.right().value() != JanusGraphOperationStatus.NOT_FOUND) {
700 log.debug("Failed to get properties for derived from {} error {}", derived.getUniqueId(), derivedProperties.right().value());
701 return Either.right(DaoStatusConverter.convertJanusGraphStatusToStorageStatus(derivedProperties.right().value()));
706 List<GraphVertex> propList = derivedProperties.left().value();
707 for (GraphVertex propV : propList) {
708 Map<String, T> propertiesFromDerived = (Map<String, T>) propV.getJson();
709 if (propertiesFromDerived != null) {
710 propertiesFromDerived.entrySet().forEach(x -> x.getValue().setOwnerIdIfEmpty(derived.getUniqueId()));
711 propertiesAll.putAll(propertiesFromDerived);
716 return Either.left(propertiesAll);
719 protected JanusGraphOperationStatus setArtifactsFromGraph(GraphVertex componentV, ToscaElement toscaElement) {
720 Either<Map<String, ArtifactDataDefinition>, JanusGraphOperationStatus> result = getDataFromGraph(componentV, EdgeLabelEnum.ARTIFACTS);
721 if (result.isLeft()) {
722 toscaElement.setArtifacts(result.left().value());
724 if (result.right().value() != JanusGraphOperationStatus.NOT_FOUND) {
725 return result.right().value();
728 result = getDataFromGraph(componentV, EdgeLabelEnum.DEPLOYMENT_ARTIFACTS);
729 if (result.isLeft()) {
730 toscaElement.setDeploymentArtifacts(result.left().value());
732 if (result.right().value() != JanusGraphOperationStatus.NOT_FOUND) {
733 return result.right().value();
736 result = getDataFromGraph(componentV, EdgeLabelEnum.TOSCA_ARTIFACTS);
737 if (result.isLeft()) {
738 toscaElement.setToscaArtifacts(result.left().value());
740 if (result.right().value() != JanusGraphOperationStatus.NOT_FOUND) {
741 return result.right().value();
744 return JanusGraphOperationStatus.OK;
747 protected JanusGraphOperationStatus setAllVersions(GraphVertex componentV, ToscaElement toscaElement) {
748 Map<String, String> allVersion = new HashMap<>();
749 allVersion.put((String) componentV.getMetadataProperty(GraphPropertyEnum.VERSION), componentV.getUniqueId());
750 ArrayList<GraphVertex> allChildrenAndParants = new ArrayList<>();
751 Either<GraphVertex, JanusGraphOperationStatus> childResourceRes = janusGraphDao
752 .getChildVertex(componentV, EdgeLabelEnum.VERSION, JsonParseFlagEnum.NoParse);
753 while (childResourceRes.isLeft()) {
754 GraphVertex child = childResourceRes.left().value();
755 allChildrenAndParants.add(child);
756 childResourceRes = janusGraphDao.getChildVertex(child, EdgeLabelEnum.VERSION, JsonParseFlagEnum.NoParse);
758 JanusGraphOperationStatus operationStatus = childResourceRes.right().value();
759 if (operationStatus != JanusGraphOperationStatus.NOT_FOUND) {
760 return operationStatus;
762 Either<GraphVertex, JanusGraphOperationStatus> parentResourceRes = janusGraphDao
763 .getParentVertex(componentV, EdgeLabelEnum.VERSION, JsonParseFlagEnum.NoParse);
764 while (parentResourceRes.isLeft()) {
765 GraphVertex parent = parentResourceRes.left().value();
766 allChildrenAndParants.add(parent);
767 parentResourceRes = janusGraphDao.getParentVertex(parent, EdgeLabelEnum.VERSION, JsonParseFlagEnum.NoParse);
769 operationStatus = parentResourceRes.right().value();
770 if (operationStatus != JanusGraphOperationStatus.NOT_FOUND) {
771 return operationStatus;
773 allChildrenAndParants.stream().filter(vertex -> {
774 Boolean isDeleted = (Boolean) vertex.getMetadataProperty(GraphPropertyEnum.IS_DELETED);
775 return (isDeleted == null || !isDeleted);
776 }).forEach(vertex -> allVersion.put((String) vertex.getMetadataProperty(GraphPropertyEnum.VERSION), vertex.getUniqueId()));
777 toscaElement.setAllVersions(allVersion);
778 return JanusGraphOperationStatus.OK;
783 protected <T extends ToscaElement> Either<List<T>, StorageOperationStatus> getFollowedComponent(String userId,
784 Set<LifecycleStateEnum> lifecycleStates,
785 Set<LifecycleStateEnum> lastStateStates,
786 ComponentTypeEnum neededType) {
787 Map<GraphPropertyEnum, Object> props = null;
788 if (userId != null) {
789 props = new EnumMap<>(GraphPropertyEnum.class);
790 // for Designer retrieve specific user
791 props.put(GraphPropertyEnum.USERID, userId);
793 // in case of user id == null -> get all users by label
795 // for Tester and Admin retrieve all users
796 Either<List<GraphVertex>, JanusGraphOperationStatus> usersByCriteria = janusGraphDao
797 .getByCriteria(VertexTypeEnum.USER, props, JsonParseFlagEnum.NoParse);
798 if (usersByCriteria.isRight()) {
799 log.debug("Failed to fetch users by criteria {} error {}", props, usersByCriteria.right().value());
800 return Either.right(DaoStatusConverter.convertJanusGraphStatusToStorageStatus(usersByCriteria.right().value()));
802 GraphVertex userV = usersByCriteria.left().value().get(0);
803 List<T> components = new ArrayList<>();
804 List<T> componentsPerUser;
805 final Set<String> ids = new HashSet<>();
806 Either<List<GraphVertex>, JanusGraphOperationStatus> childrenVertecies = janusGraphDao
807 .getChildrenVertices(userV, EdgeLabelEnum.STATE, JsonParseFlagEnum.NoParse);
808 if (childrenVertecies.isRight() && childrenVertecies.right().value() != JanusGraphOperationStatus.NOT_FOUND) {
809 log.debug("Failed to fetch children vertices for user {} by edge {} error {}", userV.getMetadataProperty(GraphPropertyEnum.USERID),
810 EdgeLabelEnum.STATE, childrenVertecies.right().value());
811 return Either.right(DaoStatusConverter.convertJanusGraphStatusToStorageStatus(childrenVertecies.right().value()));
813 // get all resource with current state
814 if (childrenVertecies.isLeft()) {
815 componentsPerUser = fetchComponents(userId, lifecycleStates, childrenVertecies.left().value(), neededType, EdgeLabelEnum.STATE);
816 if (componentsPerUser != null) {
817 for (T comp : componentsPerUser) {
818 ids.add(comp.getUniqueId());
819 components.add(comp);
822 if (lastStateStates != null && !lastStateStates.isEmpty()) {
823 // get all resource with last state
824 childrenVertecies = janusGraphDao.getChildrenVertices(userV, EdgeLabelEnum.LAST_STATE, JsonParseFlagEnum.NoParse);
825 if (childrenVertecies.isRight() && childrenVertecies.right().value() != JanusGraphOperationStatus.NOT_FOUND) {
826 log.debug("Failed to fetch children vertices for user {} by edge {} error {}",
827 userV.getMetadataProperty(GraphPropertyEnum.USERID), EdgeLabelEnum.LAST_STATE, childrenVertecies.right().value());
828 return Either.right(DaoStatusConverter.convertJanusGraphStatusToStorageStatus(childrenVertecies.right().value()));
830 if (childrenVertecies.isLeft()) {
832 componentsPerUser = fetchComponents(userId, lastStateStates, childrenVertecies.left().value(), neededType,
833 EdgeLabelEnum.LAST_STATE);
834 if (componentsPerUser != null) {
835 for (T comp : componentsPerUser) {
837 if (ids.contains(comp.getUniqueId())) {
841 components.add(comp);
848 return Either.left(components);
851 private <T extends ToscaElement> List<T> fetchComponents(String userId, Set<LifecycleStateEnum> lifecycleStates, List<GraphVertex> vertices,
852 ComponentTypeEnum neededType, EdgeLabelEnum edgelabel) {
853 List<T> components = new ArrayList<>();
854 for (GraphVertex node : vertices) {
855 Iterator<Edge> edges = node.getVertex().edges(Direction.IN, edgelabel.name());
856 while (edges.hasNext()) {
857 Edge edge = edges.next();
858 String stateStr = (String) janusGraphDao.getProperty(edge, EdgePropertyEnum.STATE);
859 LifecycleStateEnum nodeState = LifecycleStateEnum.findState(stateStr);
860 if (nodeState == null) {
861 log.debug("no supported STATE {} for element {}", stateStr, node.getUniqueId());
864 //get user from edge and compare to user from followed request
865 JanusGraphVertex userVertex = (JanusGraphVertex) edge.outVertex();
866 String userIdFromEdge = (String) janusGraphDao.getProperty(userVertex, GraphPropertyEnum.USERID.getProperty());
867 if (lifecycleStates != null && lifecycleStates.contains(nodeState) && (userIdFromEdge.equals(userId))) {
868 Boolean isDeleted = (Boolean) node.getMetadataProperty(GraphPropertyEnum.IS_DELETED);
869 Boolean isArchived = (Boolean) node.getMetadataProperty(GraphPropertyEnum.IS_ARCHIVED);
870 if (isDeleted != null && isDeleted || isArchived != null && isArchived) {
871 log.trace("Deleted/Archived element {}, discard", node.getUniqueId());
874 Boolean isHighest = (Boolean) node.getMetadataProperty(GraphPropertyEnum.IS_HIGHEST_VERSION);
876 ComponentTypeEnum componentType = node.getType();
877 // get only latest versions
878 if (componentType == null) {
879 log.debug("No supported type {} for vertex {}", componentType, node.getUniqueId());
882 if (neededType == componentType) {
883 switch (componentType) {
886 handleNode(components, node, componentType);
889 Boolean isAbtract = (Boolean) node.getMetadataProperty(GraphPropertyEnum.IS_ABSTRACT);
890 if (isAbtract == null || !isAbtract) {
891 handleNode(components, node, componentType);
895 log.debug("not supported node type {}", componentType);
909 protected <T extends ToscaElement> void handleNode(List<T> components, GraphVertex vertexComponent, ComponentTypeEnum nodeType) {
910 Either<T, StorageOperationStatus> component = getLightComponent(vertexComponent, nodeType, new ComponentParametersView(true));
911 if (component.isRight()) {
912 log.debug("Failed to get component for id = {} error : {} skip resource", vertexComponent.getUniqueId(), component.right().value());
914 components.add(component.left().value());
918 protected <T extends ToscaElement> Either<T, StorageOperationStatus> getLightComponent(String componentUid, ComponentTypeEnum nodeType,
919 ComponentParametersView parametersFilter) {
920 Either<GraphVertex, JanusGraphOperationStatus> getVertexRes = janusGraphDao.getVertexById(componentUid);
921 if (getVertexRes.isRight()) {
922 return Either.right(DaoStatusConverter.convertJanusGraphStatusToStorageStatus(getVertexRes.right().value()));
924 return getLightComponent(getVertexRes.left().value(), nodeType, parametersFilter);
927 protected <T extends ToscaElement> Either<T, StorageOperationStatus> getLightComponent(GraphVertex vertexComponent, ComponentTypeEnum nodeType,
928 ComponentParametersView parametersFilter) {
929 log.trace("Starting to build light component of type {}, id {}", nodeType, vertexComponent.getUniqueId());
930 janusGraphDao.parseVertexProperties(vertexComponent, JsonParseFlagEnum.ParseMetadata);
931 T toscaElement = convertToComponent(vertexComponent);
932 JanusGraphOperationStatus status = setCreatorFromGraph(vertexComponent, toscaElement);
933 if (status != JanusGraphOperationStatus.OK) {
934 return Either.right(DaoStatusConverter.convertJanusGraphStatusToStorageStatus(status));
936 status = setLastModifierFromGraph(vertexComponent, toscaElement);
937 if (status != JanusGraphOperationStatus.OK) {
938 return Either.right(DaoStatusConverter.convertJanusGraphStatusToStorageStatus(status));
940 status = setCategoriesFromGraph(vertexComponent, toscaElement);
941 if (status != JanusGraphOperationStatus.OK) {
942 return Either.right(DaoStatusConverter.convertJanusGraphStatusToStorageStatus(status));
944 if (!parametersFilter.isIgnoreAllVersions()) {
945 status = setAllVersions(vertexComponent, toscaElement);
946 if (status != JanusGraphOperationStatus.OK) {
947 return Either.right(DaoStatusConverter.convertJanusGraphStatusToStorageStatus(status));
950 if (!parametersFilter.isIgnoreCapabilities()) {
951 status = setCapabilitiesFromGraph(vertexComponent, toscaElement);
952 if (status != JanusGraphOperationStatus.OK) {
953 return Either.right(DaoStatusConverter.convertJanusGraphStatusToStorageStatus(status));
956 if (!parametersFilter.isIgnoreRequirements()) {
957 status = setRequirementsFromGraph(vertexComponent, toscaElement);
958 if (status != JanusGraphOperationStatus.OK) {
959 return Either.right(DaoStatusConverter.convertJanusGraphStatusToStorageStatus(status));
962 log.debug("Ended to build light component of type {}, id {}", nodeType, vertexComponent.getUniqueId());
963 return Either.left(toscaElement);
966 @SuppressWarnings("unchecked")
967 protected <T extends ToscaElement> T convertToComponent(GraphVertex componentV) {
968 ToscaElement toscaElement = null;
969 VertexTypeEnum label = componentV.getLabel();
972 toscaElement = new NodeType();
974 case TOPOLOGY_TEMPLATE:
975 toscaElement = new TopologyTemplate();
978 log.debug("Not supported tosca type {}", label);
981 if (toscaElement != null) {
982 final Map<String, Object> jsonMetada = componentV.getMetadataJson();
983 if (MapUtils.isNotEmpty(jsonMetada)) {
984 toscaElement.setMetadata(jsonMetada);
985 final Object toscaVersion = jsonMetada.get(ToscaTagNamesEnum.TOSCA_VERSION.getElementName());
986 if (toscaVersion != null) {
987 toscaElement.setToscaVersion((String) toscaVersion);
989 final Object dataTypes = jsonMetada.get(ToscaTagNamesEnum.DATA_TYPES.getElementName());
990 if (dataTypes != null) {
991 final Map<String, DataTypeDataDefinition> dataTypeDefinitionMap = new HashMap<>();
992 final Map<String, Object> toscaAttributes = (Map<String, Object>) dataTypes;
993 for (final Entry<String, Object> attributeNameValue : toscaAttributes.entrySet()) {
994 final Object value = attributeNameValue.getValue();
995 final String key = attributeNameValue.getKey();
996 if (value instanceof Map) {
997 final DataTypeDefinition dataTypeDefinition = createDataTypeDefinitionWithName(attributeNameValue);
998 dataTypeDefinitionMap.put(dataTypeDefinition.getName(), dataTypeDefinition);
1000 dataTypeDefinitionMap.put(key, createDataType(String.valueOf(value)));
1003 toscaElement.setDataTypes(dataTypeDefinitionMap);
1007 return (T) toscaElement;
1010 protected JanusGraphOperationStatus setResourceCategoryFromGraphV(Vertex vertex, CatalogComponent catalogComponent) {
1011 List<CategoryDefinition> categories = new ArrayList<>();
1012 SubCategoryDefinition subcategory;
1013 Either<Vertex, JanusGraphOperationStatus> childVertex = janusGraphDao
1014 .getChildVertex(vertex, EdgeLabelEnum.CATEGORY, JsonParseFlagEnum.NoParse);
1015 if (childVertex.isRight()) {
1016 log.debug(FAILED_TO_FETCH_FOR_TOSCA_ELEMENT_WITH_ID_ERROR, EdgeLabelEnum.CATEGORY, catalogComponent.getUniqueId(),
1017 childVertex.right().value());
1018 return childVertex.right().value();
1020 Vertex subCategoryV = childVertex.left().value();
1021 String subCategoryNormalizedName = (String) subCategoryV.property(GraphPropertyEnum.NORMALIZED_NAME.getProperty()).value();
1022 catalogComponent.setSubCategoryNormalizedName(subCategoryNormalizedName);
1023 subcategory = new SubCategoryDefinition();
1024 subcategory.setUniqueId((String) subCategoryV.property(GraphPropertyEnum.UNIQUE_ID.getProperty()).value());
1025 subcategory.setNormalizedName(subCategoryNormalizedName);
1026 subcategory.setName((String) subCategoryV.property(GraphPropertyEnum.NAME.getProperty()).value());
1027 Type listTypeSubcat = new TypeToken<List<MetadataKeyDataDefinition>>() {
1029 List<MetadataKeyDataDefinition> metadataKeys = subCategoryV.property(GraphPropertyEnum.METADATA_KEYS.getProperty()).isPresent() ? getGson()
1030 .fromJson((String) subCategoryV.property(GraphPropertyEnum.METADATA_KEYS.getProperty()).value(), listTypeSubcat)
1031 : Collections.emptyList();
1032 subcategory.setMetadataKeys(metadataKeys);
1033 Either<Vertex, JanusGraphOperationStatus> parentVertex = janusGraphDao
1034 .getParentVertex(subCategoryV, EdgeLabelEnum.SUB_CATEGORY, JsonParseFlagEnum.NoParse);
1035 Vertex categoryV = parentVertex.left().value();
1036 String categoryNormalizedName = (String) categoryV.property(GraphPropertyEnum.NORMALIZED_NAME.getProperty()).value();
1037 catalogComponent.setCategoryNormalizedName(categoryNormalizedName);
1038 CategoryDefinition category = new CategoryDefinition();
1039 category.setUniqueId((String) categoryV.property(GraphPropertyEnum.UNIQUE_ID.getProperty()).value());
1040 category.setNormalizedName(categoryNormalizedName);
1041 category.setName((String) categoryV.property(GraphPropertyEnum.NAME.getProperty()).value());
1042 category.addSubCategory(subcategory);
1043 categories.add(category);
1044 catalogComponent.setCategories(categories);
1045 return JanusGraphOperationStatus.OK;
1048 protected JanusGraphOperationStatus setServiceCategoryFromGraphV(Vertex vertex, CatalogComponent catalogComponent) {
1049 List<CategoryDefinition> categories = new ArrayList<>();
1050 Either<Vertex, JanusGraphOperationStatus> childVertex = janusGraphDao
1051 .getChildVertex(vertex, EdgeLabelEnum.CATEGORY, JsonParseFlagEnum.NoParse);
1052 if (childVertex.isRight()) {
1053 log.debug(FAILED_TO_FETCH_FOR_TOSCA_ELEMENT_WITH_ID_ERROR, EdgeLabelEnum.CATEGORY, catalogComponent.getUniqueId(),
1054 childVertex.right().value());
1055 return childVertex.right().value();
1057 Vertex categoryV = childVertex.left().value();
1058 String categoryNormalizedName = (String) categoryV.property(GraphPropertyEnum.NORMALIZED_NAME.getProperty()).value();
1059 catalogComponent.setCategoryNormalizedName(categoryNormalizedName);
1060 CategoryDefinition category = new CategoryDefinition();
1061 category.setUniqueId((String) categoryV.property(GraphPropertyEnum.UNIQUE_ID.getProperty()).value());
1062 category.setNormalizedName(categoryNormalizedName);
1063 category.setName((String) categoryV.property(GraphPropertyEnum.NAME.getProperty()).value());
1064 category.setUseServiceSubstitutionForNestedServices(
1065 (Boolean) categoryV.property(GraphPropertyEnum.USE_SUBSTITUTION_FOR_NESTED_SERVICES.getProperty()).orElse(false));
1066 Type listTypeCat = new TypeToken<List<MetadataKeyDataDefinition>>() {
1068 List<MetadataKeyDataDefinition> metadataKeys = categoryV.property(GraphPropertyEnum.METADATA_KEYS.getProperty()).isPresent() ? getGson()
1069 .fromJson((String) categoryV.property(GraphPropertyEnum.METADATA_KEYS.getProperty()).value(), listTypeCat) : Collections.emptyList();
1070 category.setMetadataKeys(metadataKeys);
1071 categories.add(category);
1072 catalogComponent.setCategories(categories);
1073 return JanusGraphOperationStatus.OK;
1076 protected JanusGraphOperationStatus setResourceCategoryFromGraph(GraphVertex componentV, ToscaElement toscaElement) {
1077 List<CategoryDefinition> categories = new ArrayList<>();
1078 SubCategoryDefinition subcategory;
1079 Either<GraphVertex, JanusGraphOperationStatus> childVertex = janusGraphDao
1080 .getChildVertex(componentV, EdgeLabelEnum.CATEGORY, JsonParseFlagEnum.NoParse);
1081 if (childVertex.isRight()) {
1082 log.debug(FAILED_TO_FETCH_FOR_TOSCA_ELEMENT_WITH_ID_ERROR, EdgeLabelEnum.CATEGORY, componentV.getUniqueId(), childVertex.right().value());
1083 return childVertex.right().value();
1085 GraphVertex subCategoryV = childVertex.left().value();
1086 Map<GraphPropertyEnum, Object> metadataProperties = subCategoryV.getMetadataProperties();
1087 subcategory = new SubCategoryDefinition();
1088 subcategory.setUniqueId(subCategoryV.getUniqueId());
1089 subcategory.setNormalizedName((String) metadataProperties.get(GraphPropertyEnum.NORMALIZED_NAME));
1090 subcategory.setName((String) metadataProperties.get(GraphPropertyEnum.NAME));
1091 Type listTypeSubcat = new TypeToken<List<String>>() {
1093 List<String> iconsfromJsonSubcat = getGson().fromJson((String) metadataProperties.get(GraphPropertyEnum.ICONS), listTypeSubcat);
1094 subcategory.setIcons(iconsfromJsonSubcat);
1095 final Type metadataKeysTypeCat = new TypeToken<List<MetadataKeyDataDefinition>>() {
1097 final List<MetadataKeyDataDefinition> metadataKeysfromJsonCat = getGson()
1098 .fromJson((String) metadataProperties.get(GraphPropertyEnum.METADATA_KEYS), metadataKeysTypeCat);
1099 subcategory.setMetadataKeys(metadataKeysfromJsonCat);
1100 Either<GraphVertex, JanusGraphOperationStatus> parentVertex = janusGraphDao
1101 .getParentVertex(subCategoryV, EdgeLabelEnum.SUB_CATEGORY, JsonParseFlagEnum.NoParse);
1102 if (parentVertex.isRight()) {
1103 log.debug("failed to fetch {} for category with id {}, error {}", EdgeLabelEnum.SUB_CATEGORY, subCategoryV.getUniqueId(),
1104 parentVertex.right().value());
1105 return childVertex.right().value();
1107 GraphVertex categoryV = parentVertex.left().value();
1108 metadataProperties = categoryV.getMetadataProperties();
1109 CategoryDefinition category = new CategoryDefinition();
1110 category.setUniqueId(categoryV.getUniqueId());
1111 category.setNormalizedName((String) metadataProperties.get(GraphPropertyEnum.NORMALIZED_NAME));
1112 category.setName((String) metadataProperties.get(GraphPropertyEnum.NAME));
1113 Type listTypeCat = new TypeToken<List<String>>() {
1115 List<String> iconsfromJsonCat = getGson().fromJson((String) metadataProperties.get(GraphPropertyEnum.ICONS), listTypeCat);
1116 category.setIcons(iconsfromJsonCat);
1117 category.addSubCategory(subcategory);
1118 categories.add(category);
1119 toscaElement.setCategories(categories);
1120 return JanusGraphOperationStatus.OK;
1123 public <T extends ToscaElement> Either<T, StorageOperationStatus> updateToscaElement(T toscaElementToUpdate, GraphVertex elementV,
1124 ComponentParametersView filterResult) {
1125 Either<T, StorageOperationStatus> result = null;
1126 log.debug("In updateToscaElement. received component uid = {}", (toscaElementToUpdate == null ? null : toscaElementToUpdate.getUniqueId()));
1127 if (toscaElementToUpdate == null) {
1128 log.error("Service object is null");
1129 result = Either.right(StorageOperationStatus.BAD_REQUEST);
1132 String modifierUserId = toscaElementToUpdate.getLastUpdaterUserId();
1133 if (modifierUserId == null || modifierUserId.isEmpty()) {
1134 log.error("UserId is missing in the request.");
1135 result = Either.right(StorageOperationStatus.BAD_REQUEST);
1138 Either<GraphVertex, JanusGraphOperationStatus> findUser = findUserVertex(modifierUserId);
1139 if (findUser.isRight()) {
1140 JanusGraphOperationStatus status = findUser.right().value();
1141 log.error(CANNOT_FIND_USER_IN_THE_GRAPH_STATUS_IS, modifierUserId, status);
1144 GraphVertex modifierV = findUser.left().value();
1145 String toscaElementId = toscaElementToUpdate.getUniqueId();
1146 Either<GraphVertex, JanusGraphOperationStatus> parentVertex = janusGraphDao
1147 .getParentVertex(elementV, EdgeLabelEnum.LAST_MODIFIER, JsonParseFlagEnum.NoParse);
1148 if (parentVertex.isRight()) {
1149 log.debug("Failed to fetch last modifier for tosca element with id {} error {}", toscaElementId, parentVertex.right().value());
1150 return Either.right(DaoStatusConverter.convertJanusGraphStatusToStorageStatus(parentVertex.right().value()));
1152 GraphVertex userV = parentVertex.left().value();
1153 String currentModifier = (String) userV.getMetadataProperty(GraphPropertyEnum.USERID);
1154 String prevSystemName = (String) elementV.getMetadataProperty(GraphPropertyEnum.SYSTEM_NAME);
1155 if (currentModifier.equals(modifierUserId)) {
1156 log.debug("Graph LAST MODIFIER edge should not be changed since the modifier is the same as the last modifier.");
1158 log.debug("Going to update the last modifier user of the resource from {} to {}", currentModifier, modifierUserId);
1159 StorageOperationStatus status = moveLastModifierEdge(elementV, modifierV);
1160 log.debug("Finish to update the last modifier user of the resource from {} to {}. status is {}", currentModifier, modifierUserId, status);
1161 if (status != StorageOperationStatus.OK) {
1162 result = Either.right(status);
1166 final long currentTimeMillis = System.currentTimeMillis();
1167 log.debug("Going to update the last Update Date of the resource from {} to {}",
1168 elementV.getJsonMetadataField(JsonPresentationFields.LAST_UPDATE_DATE), currentTimeMillis);
1169 elementV.setJsonMetadataField(JsonPresentationFields.LAST_UPDATE_DATE, currentTimeMillis);
1170 StorageOperationStatus checkCategories = validateCategories(toscaElementToUpdate, elementV);
1171 if (checkCategories != StorageOperationStatus.OK) {
1172 result = Either.right(checkCategories);
1175 // update all data on vertex
1176 fillToscaElementVertexData(elementV, toscaElementToUpdate, JsonParseFlagEnum.ParseMetadata);
1177 Either<GraphVertex, JanusGraphOperationStatus> updateElement = janusGraphDao.updateVertex(elementV);
1178 if (updateElement.isRight()) {
1179 log.error("Failed to update resource {}. status is {}", toscaElementId, updateElement.right().value());
1180 result = Either.right(DaoStatusConverter.convertJanusGraphStatusToStorageStatus(updateElement.right().value()));
1183 GraphVertex updateElementV = updateElement.left().value();
1184 // DE230195 in case resource name changed update TOSCA artifacts
1186 // file names accordingly
1187 String newSystemName = (String) updateElementV.getMetadataProperty(GraphPropertyEnum.SYSTEM_NAME);
1188 if (newSystemName != null && !newSystemName.equals(prevSystemName)) {
1189 Either<Map<String, ArtifactDataDefinition>, JanusGraphOperationStatus> resultToscaArt = getDataFromGraph(updateElementV,
1190 EdgeLabelEnum.TOSCA_ARTIFACTS);
1191 if (resultToscaArt.isRight()) {
1192 log.debug("Failed to get tosca artifact from graph for tosca element {} error {}", toscaElementId, resultToscaArt.right().value());
1193 return Either.right(DaoStatusConverter.convertJanusGraphStatusToStorageStatus(resultToscaArt.right().value()));
1195 Map<String, ArtifactDataDefinition> toscaArtifacts = resultToscaArt.left().value();
1196 if (toscaArtifacts != null) {
1197 for (Entry<String, ArtifactDataDefinition> artifact : toscaArtifacts.entrySet()) {
1198 generateNewToscaFileName(toscaElementToUpdate.getComponentType().getValue().toLowerCase(), newSystemName, artifact.getValue());
1200 // TODO call to new Artifact operation in order to update list of artifacts
1203 if (toscaElementToUpdate.getComponentType() == ComponentTypeEnum.RESOURCE) {
1204 StorageOperationStatus resultDerived = updateDerived(toscaElementToUpdate, updateElementV);
1205 if (resultDerived != StorageOperationStatus.OK) {
1206 log.debug("Failed to update from derived data for element {} error {}", toscaElementId, resultDerived);
1207 return Either.right(resultDerived);
1210 Either<T, StorageOperationStatus> updatedResource = getToscaElement(updateElementV, filterResult);
1211 if (updatedResource.isRight()) {
1212 log.error("Failed to fetch tosca element {} after update , error {}", toscaElementId, updatedResource.right().value());
1213 result = Either.right(StorageOperationStatus.BAD_REQUEST);
1216 T updatedResourceValue = updatedResource.left().value();
1217 result = Either.left(updatedResourceValue);
1221 protected StorageOperationStatus moveLastModifierEdge(GraphVertex elementV, GraphVertex modifierV) {
1222 return DaoStatusConverter
1223 .convertJanusGraphStatusToStorageStatus(janusGraphDao.moveEdge(elementV, modifierV, EdgeLabelEnum.LAST_MODIFIER, Direction.IN));
1226 protected StorageOperationStatus moveCategoryEdge(GraphVertex elementV, GraphVertex categoryV) {
1227 return DaoStatusConverter
1228 .convertJanusGraphStatusToStorageStatus(janusGraphDao.moveEdge(elementV, categoryV, EdgeLabelEnum.CATEGORY, Direction.OUT));
1231 private void generateNewToscaFileName(String componentType, String componentName, ArtifactDataDefinition artifactInfo) {
1232 Map<String, Object> getConfig = (Map<String, Object>) ConfigurationManager.getConfigurationManager().getConfiguration().getToscaArtifacts()
1233 .entrySet().stream().filter(p -> p.getKey().equalsIgnoreCase(artifactInfo.getArtifactLabel())).findAny().get().getValue();
1234 artifactInfo.setArtifactName(componentType + "-" + componentName + getConfig.get("artifactName"));
1237 protected <T extends ToscaElement> StorageOperationStatus validateResourceCategory(T toscaElementToUpdate, GraphVertex elementV) {
1238 StorageOperationStatus status = StorageOperationStatus.OK;
1239 List<CategoryDefinition> newCategoryList = toscaElementToUpdate.getCategories();
1240 CategoryDefinition newCategory = newCategoryList.get(0);
1241 Either<GraphVertex, JanusGraphOperationStatus> childVertex = janusGraphDao
1242 .getChildVertex(elementV, EdgeLabelEnum.CATEGORY, JsonParseFlagEnum.NoParse);
1243 if (childVertex.isRight()) {
1244 log.debug(FAILED_TO_FETCH_FOR_TOSCA_ELEMENT_WITH_ID_ERROR, EdgeLabelEnum.CATEGORY, elementV.getUniqueId(), childVertex.right().value());
1245 return DaoStatusConverter.convertJanusGraphStatusToStorageStatus(childVertex.right().value());
1247 GraphVertex subCategoryV = childVertex.left().value();
1248 Map<GraphPropertyEnum, Object> metadataProperties = subCategoryV.getMetadataProperties();
1249 String subCategoryNameCurrent = (String) metadataProperties.get(GraphPropertyEnum.NAME);
1250 Either<GraphVertex, JanusGraphOperationStatus> parentVertex = janusGraphDao
1251 .getParentVertex(subCategoryV, EdgeLabelEnum.SUB_CATEGORY, JsonParseFlagEnum.NoParse);
1252 if (parentVertex.isRight()) {
1253 log.debug("failed to fetch {} for category with id {}, error {}", EdgeLabelEnum.SUB_CATEGORY, subCategoryV.getUniqueId(),
1254 parentVertex.right().value());
1255 return DaoStatusConverter.convertJanusGraphStatusToStorageStatus(childVertex.right().value());
1257 GraphVertex categoryV = parentVertex.left().value();
1258 metadataProperties = categoryV.getMetadataProperties();
1259 String categoryNameCurrent = (String) metadataProperties.get(GraphPropertyEnum.NAME);
1260 boolean categoryWasChanged = false;
1261 String newCategoryName = newCategory.getName();
1262 SubCategoryDefinition newSubcategory = newCategory.getSubcategories().get(0);
1263 String newSubCategoryName = newSubcategory.getName();
1264 if (newCategoryName != null && !newCategoryName.equals(categoryNameCurrent)) {
1265 // the category was changed
1266 categoryWasChanged = true;
1268 // the sub-category was changed
1269 if (newSubCategoryName != null && !newSubCategoryName.equals(subCategoryNameCurrent)) {
1270 log.debug("Going to update the category of the resource from {} to {}", categoryNameCurrent, newCategory);
1271 categoryWasChanged = true;
1274 if (categoryWasChanged) {
1275 Either<GraphVertex, StorageOperationStatus> getCategoryVertex = getResourceCategoryVertex(elementV.getUniqueId(), newSubCategoryName,
1277 if (getCategoryVertex.isRight()) {
1278 return getCategoryVertex.right().value();
1280 GraphVertex newCategoryV = getCategoryVertex.left().value();
1281 status = moveCategoryEdge(elementV, newCategoryV);
1282 log.debug("Going to update the category of the resource from {} to {}. status is {}", categoryNameCurrent, newCategory, status);
1287 public <T extends ToscaElement> Either<List<T>, StorageOperationStatus> getElementCatalogData(ComponentTypeEnum componentType,
1288 List<ResourceTypeEnum> excludeTypes,
1289 boolean isHighestVersions) {
1290 Either<List<GraphVertex>, JanusGraphOperationStatus> listOfComponents;
1291 if (isHighestVersions) {
1292 listOfComponents = getListOfHighestComponents(componentType, excludeTypes, JsonParseFlagEnum.NoParse);
1294 listOfComponents = getListOfHighestAndAllCertifiedComponents(componentType, excludeTypes);
1296 if (listOfComponents.isRight() && listOfComponents.right().value() != JanusGraphOperationStatus.NOT_FOUND) {
1297 return Either.right(DaoStatusConverter.convertJanusGraphStatusToStorageStatus(listOfComponents.right().value()));
1299 List<T> result = new ArrayList<>();
1300 if (listOfComponents.isLeft()) {
1301 List<GraphVertex> highestAndAllCertified = listOfComponents.left().value();
1302 if (highestAndAllCertified != null && !highestAndAllCertified.isEmpty()) {
1303 for (GraphVertex vertexComponent : highestAndAllCertified) {
1304 Either<T, StorageOperationStatus> component = getLightComponent(vertexComponent, componentType,
1305 new ComponentParametersView(true));
1306 if (component.isRight()) {
1307 log.debug("Failed to fetch light element for {} error {}", vertexComponent.getUniqueId(), component.right().value());
1308 return Either.right(component.right().value());
1310 result.add(component.left().value());
1315 return Either.left(result);
1318 public Either<List<CatalogComponent>, StorageOperationStatus> getElementCatalogData(boolean isCatalog, List<ResourceTypeEnum> excludeTypes) {
1319 StopWatch stopWatch = new StopWatch();
1321 Map<String, CatalogComponent> existInCatalog = new HashMap<>();
1322 Either<Iterator<Vertex>, JanusGraphOperationStatus> verticesEither = janusGraphDao.getCatalogOrArchiveVerticies(isCatalog);
1323 if (verticesEither.isRight()) {
1324 return Either.right(DaoStatusConverter.convertJanusGraphStatusToStorageStatus(verticesEither.right().value()));
1326 Iterator<Vertex> vertices = verticesEither.left().value();
1327 while (vertices.hasNext()) {
1328 handleCatalogComponent(existInCatalog, vertices.next(), excludeTypes);
1331 String timeToFetchElements = stopWatch.prettyPrint();
1332 log.info("time to fetch all catalog elements: {}", timeToFetchElements);
1333 return Either.left(existInCatalog.values().stream().collect(Collectors.toList()));
1336 private void handleCatalogComponent(Map<String, CatalogComponent> existInCatalog, Vertex vertex, List<ResourceTypeEnum> excludeTypes) {
1337 VertexProperty<Object> property = vertex.property(GraphPropertiesDictionary.METADATA.getProperty());
1338 String json = (String) property.value();
1339 Map<String, Object> metadatObj = JsonParserUtils.toMap(json);
1340 String uniqueId = (String) metadatObj.get(JsonPresentationFields.UNIQUE_ID.getPresentation());
1341 Boolean isDeleted = (Boolean) metadatObj.get(JsonPresentationFields.IS_DELETED.getPresentation());
1342 if (isAddToCatalog(excludeTypes, metadatObj) && (existInCatalog.get(uniqueId) == null && (isDeleted == null || !isDeleted.booleanValue()))) {
1343 CatalogComponent catalogComponent = new CatalogComponent();
1344 catalogComponent.setUniqueId(uniqueId);
1345 catalogComponent.setModel((String) metadatObj.get(JsonPresentationFields.MODEL.getPresentation()));
1347 .setComponentType(ComponentTypeEnum.valueOf((String) metadatObj.get(JsonPresentationFields.COMPONENT_TYPE.getPresentation())));
1348 catalogComponent.setVersion((String) metadatObj.get(JsonPresentationFields.VERSION.getPresentation()));
1349 catalogComponent.setName((String) metadatObj.get(JsonPresentationFields.NAME.getPresentation()));
1350 catalogComponent.setIcon((String) metadatObj.get(JsonPresentationFields.ICON.getPresentation()));
1351 catalogComponent.setLifecycleState((String) metadatObj.get(JsonPresentationFields.LIFECYCLE_STATE.getPresentation()));
1352 Object lastUpdateDate = metadatObj.get(JsonPresentationFields.LAST_UPDATE_DATE.getPresentation());
1353 catalogComponent.setLastUpdateDate((lastUpdateDate != null ? (Long) lastUpdateDate : 0L));
1354 catalogComponent.setDistributionStatus((String) metadatObj.get(JsonPresentationFields.DISTRIBUTION_STATUS.getPresentation()));
1355 catalogComponent.setDescription((String) metadatObj.get(JsonPresentationFields.DESCRIPTION.getPresentation()));
1356 catalogComponent.setSystemName((String) metadatObj.get(JsonPresentationFields.SYSTEM_NAME.getPresentation()));
1357 catalogComponent.setUuid((String) metadatObj.get(JsonPresentationFields.UUID.getPresentation()));
1358 catalogComponent.setInvariantUUID((String) metadatObj.get(JsonPresentationFields.INVARIANT_UUID.getPresentation()));
1359 catalogComponent.setIsHighestVersion((Boolean) metadatObj.get(JsonPresentationFields.HIGHEST_VERSION.getPresentation()));
1360 Iterator<Edge> edges = vertex.edges(Direction.IN, EdgeLabelEnum.STATE.name());
1361 if (edges.hasNext()) {
1363 .setLastUpdaterUserId((String) edges.next().outVertex().property(GraphPropertiesDictionary.USERID.getProperty()).value());
1365 Object resourceType = metadatObj.get(JsonPresentationFields.RESOURCE_TYPE.getPresentation());
1366 if (resourceType != null) {
1367 catalogComponent.setResourceType((String) resourceType);
1369 if (catalogComponent.getComponentType() == ComponentTypeEnum.SERVICE) {
1370 setServiceCategoryFromGraphV(vertex, catalogComponent);
1372 setResourceCategoryFromGraphV(vertex, catalogComponent);
1374 List<String> tags = (List<String>) metadatObj.get(JsonPresentationFields.TAGS.getPresentation());
1376 catalogComponent.setTags(tags);
1378 existInCatalog.put(uniqueId, catalogComponent);
1382 private boolean isAddToCatalog(List<ResourceTypeEnum> excludeTypes, Map<String, Object> metadatObj) {
1383 boolean isAddToCatalog = true;
1384 Object resourceTypeStr = metadatObj.get(JsonPresentationFields.RESOURCE_TYPE.getPresentation());
1385 if (resourceTypeStr != null) {
1386 ResourceTypeEnum resourceType = ResourceTypeEnum.getType((String) resourceTypeStr);
1387 if (!CollectionUtils.isEmpty(excludeTypes)) {
1388 Optional<ResourceTypeEnum> op = excludeTypes.stream().filter(rt -> rt == resourceType).findAny();
1389 if (op.isPresent()) {
1390 isAddToCatalog = false;
1394 return isAddToCatalog;
1397 public Either<List<GraphVertex>, JanusGraphOperationStatus> getListOfHighestComponents(ComponentTypeEnum componentType,
1398 List<ResourceTypeEnum> excludeTypes,
1399 JsonParseFlagEnum parseFlag) {
1400 Map<GraphPropertyEnum, Object> propertiesToMatch = new EnumMap<>(GraphPropertyEnum.class);
1401 Map<GraphPropertyEnum, Object> propertiesHasNotToMatch = new EnumMap<>(GraphPropertyEnum.class);
1402 propertiesToMatch.put(GraphPropertyEnum.COMPONENT_TYPE, componentType.name());
1403 propertiesToMatch.put(GraphPropertyEnum.IS_HIGHEST_VERSION, true);
1404 if (componentType == ComponentTypeEnum.RESOURCE) {
1405 propertiesToMatch.put(GraphPropertyEnum.IS_ABSTRACT, false);
1406 propertiesHasNotToMatch.put(GraphPropertyEnum.RESOURCE_TYPE, excludeTypes);
1408 propertiesHasNotToMatch.put(GraphPropertyEnum.IS_DELETED, true);
1409 propertiesHasNotToMatch.put(GraphPropertyEnum.IS_ARCHIVED, true); //US382674, US382683
1410 return janusGraphDao.getByCriteria(null, propertiesToMatch, propertiesHasNotToMatch, parseFlag);
1413 // highest + (certified && !highest)
1414 public Either<List<GraphVertex>, JanusGraphOperationStatus> getListOfHighestAndAllCertifiedComponents(ComponentTypeEnum componentType,
1415 List<ResourceTypeEnum> excludeTypes) {
1416 long startFetchAllStates = System.currentTimeMillis();
1417 Either<List<GraphVertex>, JanusGraphOperationStatus> highestNodes = getListOfHighestComponents(componentType, excludeTypes,
1418 JsonParseFlagEnum.ParseMetadata);
1419 Map<GraphPropertyEnum, Object> propertiesToMatchCertified = new EnumMap<>(GraphPropertyEnum.class);
1420 Map<GraphPropertyEnum, Object> propertiesHasNotToMatchCertified = new EnumMap<>(GraphPropertyEnum.class);
1421 propertiesToMatchCertified.put(GraphPropertyEnum.STATE, LifecycleStateEnum.CERTIFIED.name());
1422 propertiesToMatchCertified.put(GraphPropertyEnum.COMPONENT_TYPE, componentType.name());
1423 if (componentType == ComponentTypeEnum.RESOURCE) {
1424 propertiesToMatchCertified.put(GraphPropertyEnum.IS_ABSTRACT, false);
1425 propertiesHasNotToMatchCertified.put(GraphPropertyEnum.RESOURCE_TYPE, excludeTypes);
1427 propertiesHasNotToMatchCertified.put(GraphPropertyEnum.IS_DELETED, true);
1428 propertiesHasNotToMatchCertified.put(GraphPropertyEnum.IS_ARCHIVED, true); //US382674, US382683
1429 propertiesHasNotToMatchCertified.put(GraphPropertyEnum.IS_HIGHEST_VERSION, true);
1430 Either<List<GraphVertex>, JanusGraphOperationStatus> certifiedNotHighestNodes = janusGraphDao
1431 .getByCriteria(null, propertiesToMatchCertified, propertiesHasNotToMatchCertified, JsonParseFlagEnum.ParseMetadata);
1432 if (certifiedNotHighestNodes.isRight() && certifiedNotHighestNodes.right().value() != JanusGraphOperationStatus.NOT_FOUND) {
1433 return Either.right(certifiedNotHighestNodes.right().value());
1435 long endFetchAllStates = System.currentTimeMillis();
1436 List<GraphVertex> allNodes = new ArrayList<>();
1437 if (certifiedNotHighestNodes.isLeft()) {
1438 allNodes.addAll(certifiedNotHighestNodes.left().value());
1440 if (highestNodes.isLeft()) {
1441 allNodes.addAll(highestNodes.left().value());
1443 log.debug("Fetch catalog {}s all states from graph took {} ms", componentType, endFetchAllStates - startFetchAllStates);
1444 return Either.left(allNodes);
1447 protected Either<List<GraphVertex>, StorageOperationStatus> getAllComponentsMarkedForDeletion(ComponentTypeEnum componentType) {
1448 // get all components marked for delete
1449 Map<GraphPropertyEnum, Object> props = new EnumMap<>(GraphPropertyEnum.class);
1450 props.put(GraphPropertyEnum.IS_DELETED, true);
1451 props.put(GraphPropertyEnum.COMPONENT_TYPE, componentType.name());
1452 Either<List<GraphVertex>, JanusGraphOperationStatus> componentsToDelete = janusGraphDao.getByCriteria(null, props, JsonParseFlagEnum.NoParse);
1453 if (componentsToDelete.isRight()) {
1454 JanusGraphOperationStatus error = componentsToDelete.right().value();
1455 if (error.equals(JanusGraphOperationStatus.NOT_FOUND)) {
1456 log.trace("no components to delete");
1457 return Either.left(new ArrayList<>());
1459 log.info("failed to find components to delete. error : {}", error.name());
1460 return Either.right(DaoStatusConverter.convertJanusGraphStatusToStorageStatus(error));
1463 return Either.left(componentsToDelete.left().value());
1466 protected JanusGraphOperationStatus setAdditionalInformationFromGraph(GraphVertex componentV, ToscaElement toscaElement) {
1467 Either<Map<String, AdditionalInfoParameterDataDefinition>, JanusGraphOperationStatus> result = getDataFromGraph(componentV,
1468 EdgeLabelEnum.ADDITIONAL_INFORMATION);
1469 if (result.isLeft()) {
1470 toscaElement.setAdditionalInformation(result.left().value());
1472 if (result.right().value() != JanusGraphOperationStatus.NOT_FOUND) {
1473 return result.right().value();
1476 return JanusGraphOperationStatus.OK;
1479 // --------------------------------------------
1480 public abstract <T extends ToscaElement> Either<T, StorageOperationStatus> getToscaElement(String uniqueId,
1481 ComponentParametersView componentParametersView);
1483 public abstract <T extends ToscaElement> Either<T, StorageOperationStatus> getToscaElement(GraphVertex toscaElementVertex,
1484 ComponentParametersView componentParametersView);
1486 public abstract <T extends ToscaElement> Either<T, StorageOperationStatus> deleteToscaElement(GraphVertex toscaElementVertex);
1488 public abstract <T extends ToscaElement> Either<T, StorageOperationStatus> createToscaElement(ToscaElement toscaElement);
1490 protected abstract <T extends ToscaElement> JanusGraphOperationStatus setCategoriesFromGraph(GraphVertex vertexComponent, T toscaElement);
1492 protected abstract <T extends ToscaElement> JanusGraphOperationStatus setCapabilitiesFromGraph(GraphVertex componentV, T toscaElement);
1494 protected abstract <T extends ToscaElement> JanusGraphOperationStatus setRequirementsFromGraph(GraphVertex componentV, T toscaElement);
1496 protected abstract <T extends ToscaElement> StorageOperationStatus validateCategories(T toscaElementToUpdate, GraphVertex elementV);
1498 protected abstract <T extends ToscaElement> StorageOperationStatus updateDerived(T toscaElementToUpdate, GraphVertex updateElementV);
1500 public abstract <T extends ToscaElement> void fillToscaElementVertexData(GraphVertex elementV, T toscaElementToUpdate, JsonParseFlagEnum flag);