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 protected GraphVertex getHighestVersionFrom(GraphVertex v) {
154 Either<GraphVertex, JanusGraphOperationStatus> childVertexE = janusGraphDao
155 .getChildVertex(v, EdgeLabelEnum.VERSION, JsonParseFlagEnum.NoParse);
156 GraphVertex highestVersionVertex = v;
157 while (childVertexE.isLeft()) {
158 highestVersionVertex = childVertexE.left().value();
159 childVertexE = janusGraphDao.getChildVertex(highestVersionVertex, EdgeLabelEnum.VERSION, JsonParseFlagEnum.NoParse);
161 return highestVersionVertex;
164 public Either<ToscaElement, StorageOperationStatus> getToscaElement(String uniqueId) {
165 return getToscaElement(uniqueId, new ComponentParametersView());
168 public Either<GraphVertex, StorageOperationStatus> markComponentToDelete(GraphVertex componentToDelete) {
169 Boolean isDeleted = (Boolean) componentToDelete.getMetadataProperty(GraphPropertyEnum.IS_DELETED);
170 if (isDeleted != null && isDeleted && !(Boolean) componentToDelete.getMetadataProperty(GraphPropertyEnum.IS_HIGHEST_VERSION)) {
171 // component already marked for delete
173 componentToDelete.addMetadataProperty(GraphPropertyEnum.IS_DELETED, Boolean.TRUE);
174 componentToDelete.setJsonMetadataField(JsonPresentationFields.LAST_UPDATE_DATE, System.currentTimeMillis());
175 Either<GraphVertex, JanusGraphOperationStatus> updateNode = janusGraphDao.updateVertex(componentToDelete);
176 StorageOperationStatus updateComponent;
177 if (updateNode.isRight()) {
178 log.debug("Failed to update component {}. status is {}", componentToDelete.getUniqueId(), updateNode.right().value());
179 updateComponent = DaoStatusConverter.convertJanusGraphStatusToStorageStatus(updateNode.right().value());
180 return Either.right(updateComponent);
183 return Either.left(componentToDelete);
187 * Performs a shadow clone of previousToscaElement
189 * @param previousToscaElement
190 * @param nextToscaElement
194 public Either<GraphVertex, StorageOperationStatus> cloneToscaElement(GraphVertex previousToscaElement, GraphVertex nextToscaElement,
196 Either<GraphVertex, StorageOperationStatus> result = null;
197 GraphVertex createdToscaElementVertex = null;
198 JanusGraphOperationStatus status;
199 Either<GraphVertex, JanusGraphOperationStatus> createNextVersionRes = janusGraphDao.createVertex(nextToscaElement);
200 if (createNextVersionRes.isRight()) {
201 status = createNextVersionRes.right().value();
202 CommonUtility.addRecordToLog(log, LogLevelEnum.DEBUG, "Failed to create tosca element vertex {} with version {} on graph. Status is {}. ",
203 previousToscaElement.getMetadataProperty(GraphPropertyEnum.NORMALIZED_NAME),
204 previousToscaElement.getMetadataProperty(GraphPropertyEnum.VERSION), status);
205 result = Either.right(DaoStatusConverter.convertJanusGraphStatusToStorageStatus(status));
207 if (result == null) {
208 createdToscaElementVertex = createNextVersionRes.left().value();
209 final Map<EdgePropertyEnum, Object> properties = new EnumMap<>(EdgePropertyEnum.class);
210 properties.put(EdgePropertyEnum.STATE, createdToscaElementVertex.getMetadataProperty(GraphPropertyEnum.STATE));
211 status = janusGraphDao.createEdge(user.getVertex(), createdToscaElementVertex.getVertex(), EdgeLabelEnum.STATE, properties);
212 if (status != JanusGraphOperationStatus.OK) {
213 CommonUtility.addRecordToLog(log, LogLevelEnum.DEBUG,
214 FAILED_TO_CREATE_EDGE_WITH_LABEL_FROM_USER_VERTEX_TO_TOSCA_ELEMENT_VERTEX_ON_GRAPH_STATUS_IS, EdgeLabelEnum.STATE,
215 user.getUniqueId(), previousToscaElement.getMetadataProperty(GraphPropertyEnum.NORMALIZED_NAME), status);
216 result = Either.right(DaoStatusConverter.convertJanusGraphStatusToStorageStatus(status));
219 if (result == null) {
221 VertexTypeEnum.TOPOLOGY_TEMPLATE.equals(previousToscaElement.getLabel())
222 ? createModelEdge(previousToscaElement, nextToscaElement, user, createdToscaElementVertex, EdgeLabelEnum.MODEL)
223 : createModelEdge(previousToscaElement, nextToscaElement, user, createdToscaElementVertex, EdgeLabelEnum.MODEL_ELEMENT);
225 if (result == null) {
226 status = janusGraphDao.createEdge(user.getVertex(), createdToscaElementVertex.getVertex(), EdgeLabelEnum.LAST_MODIFIER, new HashMap<>());
227 if (status != JanusGraphOperationStatus.OK) {
228 CommonUtility.addRecordToLog(log, LogLevelEnum.DEBUG,
229 FAILED_TO_CREATE_EDGE_WITH_LABEL_FROM_USER_VERTEX_TO_TOSCA_ELEMENT_VERTEX_ON_GRAPH_STATUS_IS, EdgeLabelEnum.LAST_MODIFIER,
230 user.getUniqueId(), nextToscaElement.getMetadataProperty(GraphPropertyEnum.NORMALIZED_NAME), status);
231 result = Either.right(DaoStatusConverter.convertJanusGraphStatusToStorageStatus(status));
234 if (result == null) {
235 Either<GraphVertex, JanusGraphOperationStatus> creatorVertexRes = janusGraphDao
236 .getParentVertex(previousToscaElement, EdgeLabelEnum.CREATOR, JsonParseFlagEnum.NoParse);
237 if (creatorVertexRes.isRight()) {
238 status = creatorVertexRes.right().value();
239 CommonUtility.addRecordToLog(log, LogLevelEnum.DEBUG, FAILED_TO_GET_CREATOR_VERTEX_OF_TOSCA_ELEMENT_VERTEX_ON_GRAPH_STATUS_IS,
240 EdgeLabelEnum.CREATOR, nextToscaElement.getMetadataProperty(GraphPropertyEnum.NORMALIZED_NAME), status);
241 result = Either.right(DaoStatusConverter.convertJanusGraphStatusToStorageStatus(status));
243 status = janusGraphDao
244 .createEdge(creatorVertexRes.left().value().getVertex(), createdToscaElementVertex.getVertex(), EdgeLabelEnum.CREATOR,
246 if (status != JanusGraphOperationStatus.OK) {
247 CommonUtility.addRecordToLog(log, LogLevelEnum.DEBUG,
248 FAILED_TO_CREATE_EDGE_WITH_LABEL_FROM_USER_VERTEX_TO_TOSCA_ELEMENT_VERTEX_ON_GRAPH_STATUS_IS, EdgeLabelEnum.CREATOR,
249 user.getUniqueId(), nextToscaElement.getMetadataProperty(GraphPropertyEnum.NORMALIZED_NAME), status);
250 result = Either.right(DaoStatusConverter.convertJanusGraphStatusToStorageStatus(status));
253 if (result == null) {
254 Iterator<Edge> edgesToCopyIter = previousToscaElement.getVertex().edges(Direction.OUT);
255 while (edgesToCopyIter.hasNext()) {
256 Edge currEdge = edgesToCopyIter.next();
257 Vertex currVertex = currEdge.inVertex();
258 status = janusGraphDao
259 .createEdge(createdToscaElementVertex.getVertex(), currVertex, EdgeLabelEnum.getEdgeLabelEnum(currEdge.label()), currEdge);
260 if (status != JanusGraphOperationStatus.OK) {
261 CommonUtility.addRecordToLog(log, LogLevelEnum.DEBUG,
262 "Failed to create edge with label {} from tosca element vertex {} to vertex with label {} on graph. Status is {}. ",
263 currEdge.label(), createdToscaElementVertex.getUniqueId(), currVertex.property(GraphPropertyEnum.LABEL.getProperty()),
265 result = Either.right(DaoStatusConverter.convertJanusGraphStatusToStorageStatus(status));
270 if (result == null) {
271 result = Either.left(createdToscaElementVertex);
274 .addRecordToLog(log, LogLevelEnum.DEBUG, "Failed to clone tosca element {} with the name {}. ", previousToscaElement.getUniqueId(),
275 previousToscaElement.getMetadataProperty(GraphPropertyEnum.NORMALIZED_NAME));
281 * Creates the MODEL in case it exits on the previous version
282 * @param previousToscaElement previous element version
283 * @param nextToscaElement latest element version
285 * @param createdToscaElementVertex created tosca element
286 * @param edgeLabelEnum
289 private Either<GraphVertex, StorageOperationStatus> createModelEdge(final GraphVertex previousToscaElement,
290 final GraphVertex nextToscaElement, GraphVertex user,
291 final GraphVertex createdToscaElementVertex,
292 final EdgeLabelEnum edgeLabelEnum) {
293 Either<GraphVertex, StorageOperationStatus> result = null;
294 final Either<GraphVertex, JanusGraphOperationStatus> modelElementVertexResponse = janusGraphDao
295 .getParentVertex(previousToscaElement, edgeLabelEnum, JsonParseFlagEnum.NoParse);
296 if (modelElementVertexResponse.isLeft()) {
297 final JanusGraphOperationStatus status = janusGraphDao
298 .createEdge(modelElementVertexResponse.left().value().getVertex(), createdToscaElementVertex.getVertex(), edgeLabelEnum,
300 if (JanusGraphOperationStatus.OK != status) {
301 CommonUtility.addRecordToLog(log, LogLevelEnum.DEBUG,
302 FAILED_TO_CREATE_EDGE_WITH_LABEL_FROM_USER_VERTEX_TO_TOSCA_ELEMENT_VERTEX_ON_GRAPH_STATUS_IS, edgeLabelEnum,
303 user.getUniqueId(), nextToscaElement.getMetadataProperty(GraphPropertyEnum.NORMALIZED_NAME), status);
304 result = Either.right(DaoStatusConverter.convertJanusGraphStatusToStorageStatus(status));
310 protected JanusGraphOperationStatus setLastModifierFromGraph(GraphVertex componentV, ToscaElement toscaElement) {
311 Either<GraphVertex, JanusGraphOperationStatus> parentVertex = janusGraphDao
312 .getParentVertex(componentV, EdgeLabelEnum.LAST_MODIFIER, JsonParseFlagEnum.NoParse);
313 if (parentVertex.isRight()) {
314 log.debug("Failed to fetch last modifier for tosca element with id {} error {}", componentV.getUniqueId(), parentVertex.right().value());
315 return parentVertex.right().value();
317 GraphVertex userV = parentVertex.left().value();
318 String userId = (String) userV.getMetadataProperty(GraphPropertyEnum.USERID);
319 toscaElement.setLastUpdaterUserId(userId);
320 toscaElement.setLastUpdaterFullName(buildFullName(userV));
321 return JanusGraphOperationStatus.OK;
324 public String buildFullName(GraphVertex userV) {
325 String fullName = (String) userV.getMetadataProperty(GraphPropertyEnum.FIRST_NAME);
326 if (fullName == null) {
329 fullName = fullName + " ";
331 String lastName = (String) userV.getMetadataProperty(GraphPropertyEnum.LAST_NAME);
332 if (lastName != null) {
333 fullName += lastName;
338 protected JanusGraphOperationStatus setCreatorFromGraph(GraphVertex componentV, ToscaElement toscaElement) {
339 Either<GraphVertex, JanusGraphOperationStatus> parentVertex = janusGraphDao
340 .getParentVertex(componentV, EdgeLabelEnum.CREATOR, JsonParseFlagEnum.NoParse);
341 if (parentVertex.isRight()) {
342 log.debug("Failed to fetch creator for tosca element with id {} error {}", componentV.getUniqueId(), parentVertex.right().value());
343 return parentVertex.right().value();
345 GraphVertex userV = parentVertex.left().value();
346 String creatorUserId = (String) userV.getMetadataProperty(GraphPropertyEnum.USERID);
347 toscaElement.setCreatorUserId(creatorUserId);
348 toscaElement.setCreatorFullName(buildFullName(userV));
349 return JanusGraphOperationStatus.OK;
352 protected <T extends ToscaElement> T getResourceMetaDataFromResource(T toscaElement) {
353 if (toscaElement.getNormalizedName() == null || toscaElement.getNormalizedName().isEmpty()) {
354 toscaElement.setNormalizedName(ValidationUtils.normaliseComponentName(toscaElement.getName()));
356 if (toscaElement.getSystemName() == null || toscaElement.getSystemName().isEmpty()) {
357 toscaElement.setSystemName(ValidationUtils.convertToSystemName(toscaElement.getName()));
359 LifecycleStateEnum lifecycleStateEnum = toscaElement.getLifecycleState();
360 if (lifecycleStateEnum == null) {
361 toscaElement.setLifecycleState(LifecycleStateEnum.NOT_CERTIFIED_CHECKOUT);
363 long currentDate = System.currentTimeMillis();
364 if (toscaElement.getCreationDate() == null) {
365 toscaElement.setCreationDate(currentDate);
367 toscaElement.setLastUpdateDate(currentDate);
371 protected void fillCommonMetadata(GraphVertex nodeTypeVertex, ToscaElement toscaElement) {
372 if (toscaElement.isHighestVersion() == null) {
373 toscaElement.setHighestVersion(true);
375 nodeTypeVertex.addMetadataProperty(GraphPropertyEnum.IS_DELETED, toscaElement.getMetadataValue(JsonPresentationFields.IS_DELETED));
376 nodeTypeVertex.addMetadataProperty(GraphPropertyEnum.IS_HIGHEST_VERSION,
377 toscaElement.getMetadataValueOrDefault(JsonPresentationFields.HIGHEST_VERSION, Boolean.TRUE));
378 nodeTypeVertex.addMetadataProperty(GraphPropertyEnum.STATE, toscaElement.getMetadataValue(JsonPresentationFields.LIFECYCLE_STATE));
379 nodeTypeVertex.addMetadataProperty(GraphPropertyEnum.RESOURCE_TYPE, toscaElement.getMetadataValue(JsonPresentationFields.RESOURCE_TYPE));
380 nodeTypeVertex.addMetadataProperty(GraphPropertyEnum.VERSION, toscaElement.getMetadataValue(JsonPresentationFields.VERSION));
381 nodeTypeVertex.addMetadataProperty(GraphPropertyEnum.NORMALIZED_NAME, toscaElement.getMetadataValue(JsonPresentationFields.NORMALIZED_NAME));
382 nodeTypeVertex.addMetadataProperty(GraphPropertyEnum.UNIQUE_ID, toscaElement.getMetadataValue(JsonPresentationFields.UNIQUE_ID));
384 .addMetadataProperty(GraphPropertyEnum.TOSCA_RESOURCE_NAME, toscaElement.getMetadataValue(JsonPresentationFields.TOSCA_RESOURCE_NAME));
385 nodeTypeVertex.addMetadataProperty(GraphPropertyEnum.UUID, toscaElement.getMetadataValue(JsonPresentationFields.UUID));
386 nodeTypeVertex.addMetadataProperty(GraphPropertyEnum.IS_ABSTRACT, toscaElement.getMetadataValue(JsonPresentationFields.IS_ABSTRACT));
387 nodeTypeVertex.addMetadataProperty(GraphPropertyEnum.INVARIANT_UUID, toscaElement.getMetadataValue(JsonPresentationFields.INVARIANT_UUID));
388 nodeTypeVertex.addMetadataProperty(GraphPropertyEnum.NAME, toscaElement.getMetadataValue(JsonPresentationFields.NAME));
389 nodeTypeVertex.addMetadataProperty(GraphPropertyEnum.SYSTEM_NAME, toscaElement.getMetadataValue(JsonPresentationFields.SYSTEM_NAME));
390 nodeTypeVertex.addMetadataProperty(GraphPropertyEnum.IS_ARCHIVED, toscaElement.getMetadataValue(JsonPresentationFields.IS_ARCHIVED));
391 nodeTypeVertex.addMetadataProperty(GraphPropertyEnum.ARCHIVE_TIME, toscaElement.getMetadataValue(JsonPresentationFields.ARCHIVE_TIME));
392 nodeTypeVertex.addMetadataProperty(GraphPropertyEnum.IS_VSP_ARCHIVED, toscaElement.getMetadataValue(JsonPresentationFields.IS_VSP_ARCHIVED));
393 nodeTypeVertex.addMetadataProperty(GraphPropertyEnum.MODEL, toscaElement.getMetadataValue(JsonPresentationFields.MODEL));
394 toscaElement.getMetadata().entrySet().stream().filter(e -> e.getValue() != null)
395 .forEach(e -> nodeTypeVertex.setJsonMetadataField(e.getKey(), e.getValue()));
396 nodeTypeVertex.setUniqueId(toscaElement.getUniqueId());
397 nodeTypeVertex.setType(toscaElement.getComponentType());
398 final String toscaVersion = toscaElement.getToscaVersion();
399 if (toscaVersion != null) {
400 nodeTypeVertex.setJsonMetadataField(JsonPresentationFields.TOSCA_DEFINITIONS_VERSION, toscaVersion);
402 final Map<String, DataTypeDataDefinition> dataTypes = toscaElement.getDataTypes();
403 if (MapUtils.isNotEmpty(dataTypes)) {
404 nodeTypeVertex.setJsonMetadataField(JsonPresentationFields.DATA_TYPES, dataTypes);
408 protected StorageOperationStatus assosiateToUsers(GraphVertex nodeTypeVertex, ToscaElement toscaElement) {
410 String userId = toscaElement.getCreatorUserId();
411 Either<GraphVertex, JanusGraphOperationStatus> findUser = findUserVertex(userId);
412 if (findUser.isRight()) {
413 JanusGraphOperationStatus status = findUser.right().value();
414 log.error(CANNOT_FIND_USER_IN_THE_GRAPH_STATUS_IS, userId, status);
415 return DaoStatusConverter.convertJanusGraphStatusToStorageStatus(status);
417 GraphVertex creatorVertex = findUser.left().value();
418 GraphVertex updaterVertex = creatorVertex;
419 String updaterId = toscaElement.getLastUpdaterUserId();
420 if (updaterId != null && !updaterId.equals(userId)) {
421 findUser = findUserVertex(updaterId);
422 if (findUser.isRight()) {
423 JanusGraphOperationStatus status = findUser.right().value();
424 log.error(CANNOT_FIND_USER_IN_THE_GRAPH_STATUS_IS, userId, status);
425 return DaoStatusConverter.convertJanusGraphStatusToStorageStatus(status);
427 updaterVertex = findUser.left().value();
430 Map<EdgePropertyEnum, Object> props = new EnumMap<>(EdgePropertyEnum.class);
431 props.put(EdgePropertyEnum.STATE, (String) toscaElement.getMetadataValue(JsonPresentationFields.LIFECYCLE_STATE));
432 JanusGraphOperationStatus result = janusGraphDao.createEdge(updaterVertex, nodeTypeVertex, EdgeLabelEnum.STATE, props);
433 log.debug("After associating user {} to resource {}. Edge type is {}", updaterVertex, nodeTypeVertex.getUniqueId(), EdgeLabelEnum.STATE);
434 if (JanusGraphOperationStatus.OK != result) {
435 return DaoStatusConverter.convertJanusGraphStatusToStorageStatus(result);
437 result = janusGraphDao.createEdge(updaterVertex, nodeTypeVertex, EdgeLabelEnum.LAST_MODIFIER, null);
438 log.debug("After associating user {} to resource {}. Edge type is {}", updaterVertex, nodeTypeVertex.getUniqueId(),
439 EdgeLabelEnum.LAST_MODIFIER);
440 if (!result.equals(JanusGraphOperationStatus.OK)) {
441 log.error("Failed to associate user {} to resource {}. Edge type is {}", updaterVertex, nodeTypeVertex.getUniqueId(),
442 EdgeLabelEnum.LAST_MODIFIER);
443 return DaoStatusConverter.convertJanusGraphStatusToStorageStatus(result);
445 toscaElement.setLastUpdaterUserId(toscaElement.getCreatorUserId());
446 toscaElement.setLastUpdaterFullName(toscaElement.getCreatorFullName());
447 result = janusGraphDao.createEdge(creatorVertex, nodeTypeVertex, EdgeLabelEnum.CREATOR, null);
448 log.debug("After associating user {} to resource {}. Edge type is {} ", creatorVertex, nodeTypeVertex.getUniqueId(), EdgeLabelEnum.CREATOR);
449 if (!result.equals(JanusGraphOperationStatus.OK)) {
450 log.error("Failed to associate user {} to resource {}. Edge type is {} ", creatorVertex, nodeTypeVertex.getUniqueId(),
451 EdgeLabelEnum.CREATOR);
452 return DaoStatusConverter.convertJanusGraphStatusToStorageStatus(result);
454 return StorageOperationStatus.OK;
457 protected StorageOperationStatus assosiateResourceMetadataToCategory(GraphVertex nodeTypeVertex, ToscaElement nodeType) {
458 String subcategoryName = nodeType.getCategories().get(0).getSubcategories().get(0).getName();
459 String categoryName = nodeType.getCategories().get(0).getName();
460 Either<GraphVertex, StorageOperationStatus> getCategoryVertex = getResourceCategoryVertex(nodeType.getUniqueId(), subcategoryName,
462 if (getCategoryVertex.isRight()) {
463 return getCategoryVertex.right().value();
465 GraphVertex subCategoryV = getCategoryVertex.left().value();
466 JanusGraphOperationStatus createEdge = janusGraphDao.createEdge(nodeTypeVertex, subCategoryV, EdgeLabelEnum.CATEGORY, new HashMap<>());
467 if (createEdge != JanusGraphOperationStatus.OK) {
468 log.trace("Failed to associate resource {} to category {} with id {}", nodeType.getUniqueId(), subcategoryName,
469 subCategoryV.getUniqueId());
470 return DaoStatusConverter.convertJanusGraphStatusToStorageStatus(createEdge);
472 return StorageOperationStatus.OK;
475 protected StorageOperationStatus associateComponentToModel(final GraphVertex nodeTypeVertex, final ToscaElement nodeType,
476 final EdgeLabelEnum edgeLabelEnum) {
477 if (nodeType.getMetadataValue(JsonPresentationFields.MODEL) == null) {
478 return StorageOperationStatus.OK;
480 final String model = ((String) nodeType.getMetadataValue(JsonPresentationFields.MODEL));
481 final JanusGraphOperationStatus createEdge = janusGraphDao.createEdge(getModelVertex(model), nodeTypeVertex, edgeLabelEnum, new HashMap<>());
482 if (createEdge != JanusGraphOperationStatus.OK) {
483 log.trace("Failed to associate resource {} to model {}", nodeType.getUniqueId(), model);
484 return DaoStatusConverter.convertJanusGraphStatusToStorageStatus(createEdge);
486 return StorageOperationStatus.OK;
489 private GraphVertex getModelVertex(final String modelName) {
490 log.debug("getModelVertex: fetching model {}", modelName);
491 final Optional<GraphVertex> modelVertexByNameOptional = modelOperation.findModelVertexByName(modelName);
492 if (modelVertexByNameOptional.isEmpty()) {
493 throw ModelOperationExceptionSupplier.invalidModel(modelName).get();
495 return modelVertexByNameOptional.get();
498 protected Either<GraphVertex, StorageOperationStatus> getResourceCategoryVertex(String elementId, String subcategoryName, String categoryName) {
499 Either<GraphVertex, StorageOperationStatus> category = categoryOperation.getCategory(categoryName, VertexTypeEnum.RESOURCE_CATEGORY);
500 if (category.isRight()) {
501 log.trace("Failed to fetch category {} for resource {} error {}", categoryName, elementId, category.right().value());
502 return Either.right(category.right().value());
504 GraphVertex categoryV = category.left().value();
505 if (subcategoryName != null) {
506 Either<GraphVertex, StorageOperationStatus> subCategory = categoryOperation.getSubCategoryForCategory(categoryV, subcategoryName);
507 if (subCategory.isRight()) {
508 log.trace("Failed to fetch subcategory {} of category for resource {} error {}", subcategoryName, categoryName, elementId,
509 subCategory.right().value());
510 return Either.right(subCategory.right().value());
512 GraphVertex subCategoryV = subCategory.left().value();
513 return Either.left(subCategoryV);
515 return Either.left(categoryV);
518 private StorageOperationStatus associateArtifactsToResource(GraphVertex nodeTypeVertex, ToscaElement toscaElement) {
519 Map<String, ArtifactDataDefinition> artifacts = toscaElement.getArtifacts();
520 Either<GraphVertex, StorageOperationStatus> status;
521 if (artifacts != null) {
522 artifacts.values().stream().filter(a -> a.getUniqueId() == null).forEach(a -> {
523 String uniqueId = UniqueIdBuilder
524 .buildPropertyUniqueId(nodeTypeVertex.getUniqueId().toLowerCase(), a.getArtifactLabel().toLowerCase());
525 a.setUniqueId(uniqueId);
527 status = associateElementToData(nodeTypeVertex, VertexTypeEnum.ARTIFACTS, EdgeLabelEnum.ARTIFACTS, artifacts);
528 if (status.isRight()) {
529 return status.right().value();
532 Map<String, ArtifactDataDefinition> toscaArtifacts = toscaElement.getToscaArtifacts();
533 if (toscaArtifacts != null) {
534 toscaArtifacts.values().stream().filter(a -> a.getUniqueId() == null).forEach(a -> {
535 String uniqueId = UniqueIdBuilder
536 .buildPropertyUniqueId(nodeTypeVertex.getUniqueId().toLowerCase(), a.getArtifactLabel().toLowerCase());
537 a.setUniqueId(uniqueId);
539 status = associateElementToData(nodeTypeVertex, VertexTypeEnum.TOSCA_ARTIFACTS, EdgeLabelEnum.TOSCA_ARTIFACTS, toscaArtifacts);
540 if (status.isRight()) {
541 return status.right().value();
544 Map<String, ArtifactDataDefinition> deploymentArtifacts = toscaElement.getDeploymentArtifacts();
545 if (deploymentArtifacts != null) {
546 deploymentArtifacts.values().stream().filter(a -> a.getUniqueId() == null).forEach(a -> {
547 String uniqueId = UniqueIdBuilder
548 .buildPropertyUniqueId(nodeTypeVertex.getUniqueId().toLowerCase(), a.getArtifactLabel().toLowerCase());
549 a.setUniqueId(uniqueId);
551 status = associateElementToData(nodeTypeVertex, VertexTypeEnum.DEPLOYMENT_ARTIFACTS, EdgeLabelEnum.DEPLOYMENT_ARTIFACTS,
552 deploymentArtifacts);
553 if (status.isRight()) {
554 return status.right().value();
557 return StorageOperationStatus.OK;
560 protected JanusGraphOperationStatus disassociateAndDeleteCommonElements(GraphVertex toscaElementVertex) {
561 JanusGraphOperationStatus status = janusGraphDao.disassociateAndDeleteLast(toscaElementVertex, Direction.OUT, EdgeLabelEnum.ARTIFACTS);
562 if (status != JanusGraphOperationStatus.OK) {
563 log.debug("Failed to disaccociate artifact for {} error {}", toscaElementVertex.getUniqueId(), status);
566 status = janusGraphDao.disassociateAndDeleteLast(toscaElementVertex, Direction.OUT, EdgeLabelEnum.TOSCA_ARTIFACTS);
567 if (status != JanusGraphOperationStatus.OK) {
568 log.debug("Failed to disaccociate tosca artifact for {} error {}", toscaElementVertex.getUniqueId(), status);
571 status = janusGraphDao.disassociateAndDeleteLast(toscaElementVertex, Direction.OUT, EdgeLabelEnum.DEPLOYMENT_ARTIFACTS);
572 if (status != JanusGraphOperationStatus.OK) {
573 log.debug("Failed to deployment artifact for {} error {}", toscaElementVertex.getUniqueId(), status);
576 status = janusGraphDao.disassociateAndDeleteLast(toscaElementVertex, Direction.OUT, EdgeLabelEnum.PROPERTIES);
577 if (status != JanusGraphOperationStatus.OK) {
578 log.debug("Failed to disaccociate properties for {} error {}", toscaElementVertex.getUniqueId(), status);
581 status = janusGraphDao.disassociateAndDeleteLast(toscaElementVertex, Direction.OUT, EdgeLabelEnum.ATTRIBUTES);
582 if (status != JanusGraphOperationStatus.OK) {
583 log.debug("Failed to disaccociate attributes for {} error {}", toscaElementVertex.getUniqueId(), status);
586 status = janusGraphDao.disassociateAndDeleteLast(toscaElementVertex, Direction.OUT, EdgeLabelEnum.ADDITIONAL_INFORMATION);
587 if (status != JanusGraphOperationStatus.OK) {
588 log.debug("Failed to disaccociate additional information for {} error {}", toscaElementVertex.getUniqueId(), status);
591 status = janusGraphDao.disassociateAndDeleteLast(toscaElementVertex, Direction.OUT, EdgeLabelEnum.CAPABILITIES);
592 if (status != JanusGraphOperationStatus.OK) {
593 log.debug("Failed to disaccociate capabilities for {} error {}", toscaElementVertex.getUniqueId(), status);
596 status = janusGraphDao.disassociateAndDeleteLast(toscaElementVertex, Direction.OUT, EdgeLabelEnum.REQUIREMENTS);
597 if (status != JanusGraphOperationStatus.OK) {
598 log.debug("Failed to disaccociate requirements for {} error {}", toscaElementVertex.getUniqueId(), status);
601 status = janusGraphDao.disassociateAndDeleteLast(toscaElementVertex, Direction.OUT, EdgeLabelEnum.FORWARDING_PATH);
602 if (status != JanusGraphOperationStatus.OK) {
603 log.debug("Failed to disaccociate requirements for {} error {}", toscaElementVertex.getUniqueId(), status);
606 return JanusGraphOperationStatus.OK;
609 protected StorageOperationStatus assosiateCommonForToscaElement(GraphVertex nodeTypeVertex, ToscaElement toscaElement) {
610 return assosiateCommonForToscaElement(nodeTypeVertex, toscaElement, null);
613 protected StorageOperationStatus assosiateCommonForToscaElement(GraphVertex nodeTypeVertex, ToscaElement toscaElement,
614 List<GraphVertex> derivedResources) {
615 StorageOperationStatus associateUsers = assosiateToUsers(nodeTypeVertex, toscaElement);
616 if (associateUsers != StorageOperationStatus.OK) {
617 return associateUsers;
619 StorageOperationStatus associateArtifacts = associateArtifactsToResource(nodeTypeVertex, toscaElement);
620 if (associateArtifacts != StorageOperationStatus.OK) {
621 return associateArtifacts;
623 StorageOperationStatus associateProperties = associatePropertiesToResource(nodeTypeVertex, toscaElement, derivedResources);
624 if (associateProperties != StorageOperationStatus.OK) {
625 return associateProperties;
627 StorageOperationStatus associateAdditionaInfo = associateAdditionalInfoToResource(nodeTypeVertex, toscaElement);
628 if (associateAdditionaInfo != StorageOperationStatus.OK) {
629 return associateAdditionaInfo;
631 if (needConnectToCatalog(toscaElement)) {
632 StorageOperationStatus associateToCatalog = associateToCatalogRoot(nodeTypeVertex);
633 if (associateToCatalog != StorageOperationStatus.OK) {
634 return associateToCatalog;
637 return StorageOperationStatus.OK;
640 private boolean needConnectToCatalog(ToscaElement toscaElement) {
641 Boolean isAbstract = (Boolean) toscaElement.getMetadataValue(JsonPresentationFields.IS_ABSTRACT);
642 if (isAbstract != null && isAbstract) {
645 return toscaElement.isHighestVersion();
648 private StorageOperationStatus associateToCatalogRoot(GraphVertex nodeTypeVertex) {
649 Either<GraphVertex, JanusGraphOperationStatus> catalog = janusGraphDao.getVertexByLabel(VertexTypeEnum.CATALOG_ROOT);
650 if (catalog.isRight()) {
651 log.debug("Failed to fetch catalog vertex. error {}", catalog.right().value());
652 return DaoStatusConverter.convertJanusGraphStatusToStorageStatus(catalog.right().value());
654 JanusGraphOperationStatus createEdge = janusGraphDao.createEdge(catalog.left().value(), nodeTypeVertex, EdgeLabelEnum.CATALOG_ELEMENT, null);
655 return DaoStatusConverter.convertJanusGraphStatusToStorageStatus(createEdge);
658 protected StorageOperationStatus associatePropertiesToResource(GraphVertex nodeTypeVertex, ToscaElement nodeType,
659 List<GraphVertex> derivedResources) {
660 // Note : currently only one derived supported!!!!
661 Either<Map<String, PropertyDataDefinition>, StorageOperationStatus> dataFromDerived = getDataFromDerived(derivedResources,
662 EdgeLabelEnum.PROPERTIES);
663 if (dataFromDerived.isRight()) {
664 return dataFromDerived.right().value();
666 Map<String, PropertyDataDefinition> propertiesAll = dataFromDerived.left().value();
667 Map<String, PropertyDataDefinition> properties = nodeType.getProperties();
668 if (properties != null) {
669 properties.values().stream().filter(p -> p.getUniqueId() == null).forEach(p -> {
670 String uid = UniqueIdBuilder.buildPropertyUniqueId(nodeTypeVertex.getUniqueId(), p.getName());
673 Either<Map<String, PropertyDataDefinition>, String> eitherMerged = ToscaDataDefinition.mergeDataMaps(propertiesAll, properties);
674 if (eitherMerged.isRight()) {
675 // TODO re-factor error handling - moving BL to operation resulted in loss of info about the invalid property
676 log.debug("property {} cannot be overriden", eitherMerged.right().value());
677 return StorageOperationStatus.INVALID_PROPERTY;
680 if (!propertiesAll.isEmpty()) {
681 Either<GraphVertex, StorageOperationStatus> assosiateElementToData = associateElementToData(nodeTypeVertex, VertexTypeEnum.PROPERTIES,
682 EdgeLabelEnum.PROPERTIES, propertiesAll);
683 if (assosiateElementToData.isRight()) {
684 return assosiateElementToData.right().value();
687 return StorageOperationStatus.OK;
690 private StorageOperationStatus associateAdditionalInfoToResource(GraphVertex nodeTypeVertex, ToscaElement nodeType) {
691 Map<String, AdditionalInfoParameterDataDefinition> additionalInformation = nodeType.getAdditionalInformation();
692 if (additionalInformation != null) {
693 Either<GraphVertex, StorageOperationStatus> assosiateElementToData = associateElementToData(nodeTypeVertex,
694 VertexTypeEnum.ADDITIONAL_INFORMATION, EdgeLabelEnum.ADDITIONAL_INFORMATION, additionalInformation);
695 if (assosiateElementToData.isRight()) {
696 return assosiateElementToData.right().value();
699 return StorageOperationStatus.OK;
702 protected <T extends ToscaDataDefinition> Either<Map<String, T>, StorageOperationStatus> getDataFromDerived(List<GraphVertex> derivedResources,
703 EdgeLabelEnum edge) {
704 Map<String, T> propertiesAll = new HashMap<>();
705 if (derivedResources != null && !derivedResources.isEmpty()) {
706 for (GraphVertex derived : derivedResources) {
707 Either<List<GraphVertex>, JanusGraphOperationStatus> derivedProperties = janusGraphDao
708 .getChildrenVertices(derived, edge, JsonParseFlagEnum.ParseJson);
709 if (derivedProperties.isRight()) {
710 if (derivedProperties.right().value() != JanusGraphOperationStatus.NOT_FOUND) {
711 log.debug("Failed to get properties for derived from {} error {}", derived.getUniqueId(), derivedProperties.right().value());
712 return Either.right(DaoStatusConverter.convertJanusGraphStatusToStorageStatus(derivedProperties.right().value()));
717 List<GraphVertex> propList = derivedProperties.left().value();
718 for (GraphVertex propV : propList) {
719 Map<String, T> propertiesFromDerived = (Map<String, T>) propV.getJson();
720 if (propertiesFromDerived != null) {
721 propertiesFromDerived.entrySet().forEach(x -> x.getValue().setOwnerIdIfEmpty(derived.getUniqueId()));
722 propertiesAll.putAll(propertiesFromDerived);
727 return Either.left(propertiesAll);
730 protected JanusGraphOperationStatus setArtifactsFromGraph(GraphVertex componentV, ToscaElement toscaElement) {
731 Either<Map<String, ArtifactDataDefinition>, JanusGraphOperationStatus> result = getDataFromGraph(componentV, EdgeLabelEnum.ARTIFACTS);
732 if (result.isLeft()) {
733 toscaElement.setArtifacts(result.left().value());
735 if (result.right().value() != JanusGraphOperationStatus.NOT_FOUND) {
736 return result.right().value();
739 result = getDataFromGraph(componentV, EdgeLabelEnum.DEPLOYMENT_ARTIFACTS);
740 if (result.isLeft()) {
741 toscaElement.setDeploymentArtifacts(result.left().value());
743 if (result.right().value() != JanusGraphOperationStatus.NOT_FOUND) {
744 return result.right().value();
747 result = getDataFromGraph(componentV, EdgeLabelEnum.TOSCA_ARTIFACTS);
748 if (result.isLeft()) {
749 toscaElement.setToscaArtifacts(result.left().value());
751 if (result.right().value() != JanusGraphOperationStatus.NOT_FOUND) {
752 return result.right().value();
755 return JanusGraphOperationStatus.OK;
758 protected JanusGraphOperationStatus setAllVersions(GraphVertex componentV, ToscaElement toscaElement) {
759 Map<String, String> allVersion = new HashMap<>();
760 allVersion.put((String) componentV.getMetadataProperty(GraphPropertyEnum.VERSION), componentV.getUniqueId());
761 ArrayList<GraphVertex> allChildrenAndParants = new ArrayList<>();
762 Either<GraphVertex, JanusGraphOperationStatus> childResourceRes = janusGraphDao
763 .getChildVertex(componentV, EdgeLabelEnum.VERSION, JsonParseFlagEnum.NoParse);
764 while (childResourceRes.isLeft()) {
765 GraphVertex child = childResourceRes.left().value();
766 allChildrenAndParants.add(child);
767 childResourceRes = janusGraphDao.getChildVertex(child, EdgeLabelEnum.VERSION, JsonParseFlagEnum.NoParse);
769 JanusGraphOperationStatus operationStatus = childResourceRes.right().value();
770 if (operationStatus != JanusGraphOperationStatus.NOT_FOUND) {
771 return operationStatus;
773 Either<GraphVertex, JanusGraphOperationStatus> parentResourceRes = janusGraphDao
774 .getParentVertex(componentV, EdgeLabelEnum.VERSION, JsonParseFlagEnum.NoParse);
775 while (parentResourceRes.isLeft()) {
776 GraphVertex parent = parentResourceRes.left().value();
777 allChildrenAndParants.add(parent);
778 parentResourceRes = janusGraphDao.getParentVertex(parent, EdgeLabelEnum.VERSION, JsonParseFlagEnum.NoParse);
780 operationStatus = parentResourceRes.right().value();
781 if (operationStatus != JanusGraphOperationStatus.NOT_FOUND) {
782 return operationStatus;
784 allChildrenAndParants.stream().filter(vertex -> {
785 Boolean isDeleted = (Boolean) vertex.getMetadataProperty(GraphPropertyEnum.IS_DELETED);
786 return (isDeleted == null || !isDeleted);
787 }).forEach(vertex -> allVersion.put((String) vertex.getMetadataProperty(GraphPropertyEnum.VERSION), vertex.getUniqueId()));
788 toscaElement.setAllVersions(allVersion);
789 return JanusGraphOperationStatus.OK;
794 protected <T extends ToscaElement> Either<List<T>, StorageOperationStatus> getFollowedComponent(String userId,
795 Set<LifecycleStateEnum> lifecycleStates,
796 Set<LifecycleStateEnum> lastStateStates,
797 ComponentTypeEnum neededType) {
798 Map<GraphPropertyEnum, Object> props = null;
799 if (userId != null) {
800 props = new EnumMap<>(GraphPropertyEnum.class);
801 // for Designer retrieve specific user
802 props.put(GraphPropertyEnum.USERID, userId);
804 // in case of user id == null -> get all users by label
806 // for Tester and Admin retrieve all users
807 Either<List<GraphVertex>, JanusGraphOperationStatus> usersByCriteria = janusGraphDao
808 .getByCriteria(VertexTypeEnum.USER, props, JsonParseFlagEnum.NoParse);
809 if (usersByCriteria.isRight()) {
810 log.debug("Failed to fetch users by criteria {} error {}", props, usersByCriteria.right().value());
811 return Either.right(DaoStatusConverter.convertJanusGraphStatusToStorageStatus(usersByCriteria.right().value()));
813 GraphVertex userV = usersByCriteria.left().value().get(0);
814 List<T> components = new ArrayList<>();
815 List<T> componentsPerUser;
816 final Set<String> ids = new HashSet<>();
817 Either<List<GraphVertex>, JanusGraphOperationStatus> childrenVertecies = janusGraphDao
818 .getChildrenVertices(userV, EdgeLabelEnum.STATE, JsonParseFlagEnum.NoParse);
819 if (childrenVertecies.isRight() && childrenVertecies.right().value() != JanusGraphOperationStatus.NOT_FOUND) {
820 log.debug("Failed to fetch children vertices for user {} by edge {} error {}", userV.getMetadataProperty(GraphPropertyEnum.USERID),
821 EdgeLabelEnum.STATE, childrenVertecies.right().value());
822 return Either.right(DaoStatusConverter.convertJanusGraphStatusToStorageStatus(childrenVertecies.right().value()));
824 // get all resource with current state
825 if (childrenVertecies.isLeft()) {
826 componentsPerUser = fetchComponents(userId, lifecycleStates, childrenVertecies.left().value(), neededType, EdgeLabelEnum.STATE);
827 if (componentsPerUser != null) {
828 for (T comp : componentsPerUser) {
829 ids.add(comp.getUniqueId());
830 components.add(comp);
833 if (lastStateStates != null && !lastStateStates.isEmpty()) {
834 // get all resource with last state
835 childrenVertecies = janusGraphDao.getChildrenVertices(userV, EdgeLabelEnum.LAST_STATE, JsonParseFlagEnum.NoParse);
836 if (childrenVertecies.isRight() && childrenVertecies.right().value() != JanusGraphOperationStatus.NOT_FOUND) {
837 log.debug("Failed to fetch children vertices for user {} by edge {} error {}",
838 userV.getMetadataProperty(GraphPropertyEnum.USERID), EdgeLabelEnum.LAST_STATE, childrenVertecies.right().value());
839 return Either.right(DaoStatusConverter.convertJanusGraphStatusToStorageStatus(childrenVertecies.right().value()));
841 if (childrenVertecies.isLeft()) {
843 componentsPerUser = fetchComponents(userId, lastStateStates, childrenVertecies.left().value(), neededType,
844 EdgeLabelEnum.LAST_STATE);
845 if (componentsPerUser != null) {
846 for (T comp : componentsPerUser) {
848 if (ids.contains(comp.getUniqueId())) {
852 components.add(comp);
859 return Either.left(components);
862 private <T extends ToscaElement> List<T> fetchComponents(String userId, Set<LifecycleStateEnum> lifecycleStates, List<GraphVertex> vertices,
863 ComponentTypeEnum neededType, EdgeLabelEnum edgelabel) {
864 List<T> components = new ArrayList<>();
865 for (GraphVertex node : vertices) {
866 Iterator<Edge> edges = node.getVertex().edges(Direction.IN, edgelabel.name());
867 while (edges.hasNext()) {
868 Edge edge = edges.next();
869 String stateStr = (String) janusGraphDao.getProperty(edge, EdgePropertyEnum.STATE);
870 LifecycleStateEnum nodeState = LifecycleStateEnum.findState(stateStr);
871 if (nodeState == null) {
872 log.debug("no supported STATE {} for element {}", stateStr, node.getUniqueId());
875 //get user from edge and compare to user from followed request
876 JanusGraphVertex userVertex = (JanusGraphVertex) edge.outVertex();
877 String userIdFromEdge = (String) janusGraphDao.getProperty(userVertex, GraphPropertyEnum.USERID.getProperty());
878 if (lifecycleStates != null && lifecycleStates.contains(nodeState) && (userIdFromEdge.equals(userId))) {
879 Boolean isDeleted = (Boolean) node.getMetadataProperty(GraphPropertyEnum.IS_DELETED);
880 Boolean isArchived = (Boolean) node.getMetadataProperty(GraphPropertyEnum.IS_ARCHIVED);
881 if (isDeleted != null && isDeleted || isArchived != null && isArchived) {
882 log.trace("Deleted/Archived element {}, discard", node.getUniqueId());
885 Boolean isHighest = (Boolean) node.getMetadataProperty(GraphPropertyEnum.IS_HIGHEST_VERSION);
887 ComponentTypeEnum componentType = node.getType();
888 // get only latest versions
889 if (componentType == null) {
890 log.debug("No supported type {} for vertex {}", componentType, node.getUniqueId());
893 if (neededType == componentType) {
894 switch (componentType) {
897 handleNode(components, node, componentType);
900 Boolean isAbtract = (Boolean) node.getMetadataProperty(GraphPropertyEnum.IS_ABSTRACT);
901 if (isAbtract == null || !isAbtract) {
902 handleNode(components, node, componentType);
906 log.debug("not supported node type {}", componentType);
920 protected <T extends ToscaElement> void handleNode(List<T> components, GraphVertex vertexComponent, ComponentTypeEnum nodeType) {
921 Either<T, StorageOperationStatus> component = getLightComponent(vertexComponent, nodeType, new ComponentParametersView(true));
922 if (component.isRight()) {
923 log.debug("Failed to get component for id = {} error : {} skip resource", vertexComponent.getUniqueId(), component.right().value());
925 components.add(component.left().value());
929 protected <T extends ToscaElement> Either<T, StorageOperationStatus> getLightComponent(String componentUid, ComponentTypeEnum nodeType,
930 ComponentParametersView parametersFilter) {
931 Either<GraphVertex, JanusGraphOperationStatus> getVertexRes = janusGraphDao.getVertexById(componentUid);
932 if (getVertexRes.isRight()) {
933 return Either.right(DaoStatusConverter.convertJanusGraphStatusToStorageStatus(getVertexRes.right().value()));
935 return getLightComponent(getVertexRes.left().value(), nodeType, parametersFilter);
938 protected <T extends ToscaElement> Either<T, StorageOperationStatus> getLightComponent(GraphVertex vertexComponent, ComponentTypeEnum nodeType,
939 ComponentParametersView parametersFilter) {
940 log.trace("Starting to build light component of type {}, id {}", nodeType, vertexComponent.getUniqueId());
941 janusGraphDao.parseVertexProperties(vertexComponent, JsonParseFlagEnum.ParseMetadata);
942 T toscaElement = convertToComponent(vertexComponent);
943 JanusGraphOperationStatus status = setCreatorFromGraph(vertexComponent, toscaElement);
944 if (status != JanusGraphOperationStatus.OK) {
945 return Either.right(DaoStatusConverter.convertJanusGraphStatusToStorageStatus(status));
947 status = setLastModifierFromGraph(vertexComponent, toscaElement);
948 if (status != JanusGraphOperationStatus.OK) {
949 return Either.right(DaoStatusConverter.convertJanusGraphStatusToStorageStatus(status));
951 status = setCategoriesFromGraph(vertexComponent, toscaElement);
952 if (status != JanusGraphOperationStatus.OK) {
953 return Either.right(DaoStatusConverter.convertJanusGraphStatusToStorageStatus(status));
955 if (!parametersFilter.isIgnoreAllVersions()) {
956 status = setAllVersions(vertexComponent, toscaElement);
957 if (status != JanusGraphOperationStatus.OK) {
958 return Either.right(DaoStatusConverter.convertJanusGraphStatusToStorageStatus(status));
961 if (!parametersFilter.isIgnoreCapabilities()) {
962 status = setCapabilitiesFromGraph(vertexComponent, toscaElement);
963 if (status != JanusGraphOperationStatus.OK) {
964 return Either.right(DaoStatusConverter.convertJanusGraphStatusToStorageStatus(status));
967 if (!parametersFilter.isIgnoreRequirements()) {
968 status = setRequirementsFromGraph(vertexComponent, toscaElement);
969 if (status != JanusGraphOperationStatus.OK) {
970 return Either.right(DaoStatusConverter.convertJanusGraphStatusToStorageStatus(status));
973 log.debug("Ended to build light component of type {}, id {}", nodeType, vertexComponent.getUniqueId());
974 return Either.left(toscaElement);
977 @SuppressWarnings("unchecked")
978 protected <T extends ToscaElement> T convertToComponent(GraphVertex componentV) {
979 ToscaElement toscaElement = null;
980 VertexTypeEnum label = componentV.getLabel();
983 toscaElement = new NodeType();
985 case TOPOLOGY_TEMPLATE:
986 toscaElement = new TopologyTemplate();
989 log.debug("Not supported tosca type {}", label);
992 if (toscaElement != null) {
993 final Map<String, Object> jsonMetada = componentV.getMetadataJson();
994 if (MapUtils.isNotEmpty(jsonMetada)) {
995 toscaElement.setMetadata(jsonMetada);
996 final Object toscaVersion = jsonMetada.get(ToscaTagNamesEnum.TOSCA_VERSION.getElementName());
997 if (toscaVersion != null) {
998 toscaElement.setToscaVersion((String) toscaVersion);
1000 final Object dataTypes = jsonMetada.get(ToscaTagNamesEnum.DATA_TYPES.getElementName());
1001 if (dataTypes != null) {
1002 final Map<String, DataTypeDataDefinition> dataTypeDefinitionMap = new HashMap<>();
1003 final Map<String, Object> toscaAttributes = (Map<String, Object>) dataTypes;
1004 for (final Entry<String, Object> attributeNameValue : toscaAttributes.entrySet()) {
1005 final Object value = attributeNameValue.getValue();
1006 final String key = attributeNameValue.getKey();
1007 if (value instanceof Map) {
1008 final DataTypeDefinition dataTypeDefinition = createDataTypeDefinitionWithName(attributeNameValue);
1009 dataTypeDefinitionMap.put(dataTypeDefinition.getName(), dataTypeDefinition);
1011 dataTypeDefinitionMap.put(key, createDataType(String.valueOf(value)));
1014 toscaElement.setDataTypes(dataTypeDefinitionMap);
1018 return (T) toscaElement;
1021 protected JanusGraphOperationStatus setResourceCategoryFromGraphV(Vertex vertex, CatalogComponent catalogComponent) {
1022 List<CategoryDefinition> categories = new ArrayList<>();
1023 SubCategoryDefinition subcategory;
1024 Either<Vertex, JanusGraphOperationStatus> childVertex = janusGraphDao
1025 .getChildVertex(vertex, EdgeLabelEnum.CATEGORY, JsonParseFlagEnum.NoParse);
1026 if (childVertex.isRight()) {
1027 log.debug(FAILED_TO_FETCH_FOR_TOSCA_ELEMENT_WITH_ID_ERROR, EdgeLabelEnum.CATEGORY, catalogComponent.getUniqueId(),
1028 childVertex.right().value());
1029 return childVertex.right().value();
1031 Vertex subCategoryV = childVertex.left().value();
1032 String subCategoryNormalizedName = (String) subCategoryV.property(GraphPropertyEnum.NORMALIZED_NAME.getProperty()).value();
1033 catalogComponent.setSubCategoryNormalizedName(subCategoryNormalizedName);
1034 subcategory = new SubCategoryDefinition();
1035 subcategory.setUniqueId((String) subCategoryV.property(GraphPropertyEnum.UNIQUE_ID.getProperty()).value());
1036 subcategory.setNormalizedName(subCategoryNormalizedName);
1037 subcategory.setName((String) subCategoryV.property(GraphPropertyEnum.NAME.getProperty()).value());
1038 Type listTypeSubcat = new TypeToken<List<MetadataKeyDataDefinition>>() {
1040 List<MetadataKeyDataDefinition> metadataKeys = subCategoryV.property(GraphPropertyEnum.METADATA_KEYS.getProperty()).isPresent() ? getGson()
1041 .fromJson((String) subCategoryV.property(GraphPropertyEnum.METADATA_KEYS.getProperty()).value(), listTypeSubcat)
1042 : Collections.emptyList();
1043 subcategory.setMetadataKeys(metadataKeys);
1044 Either<Vertex, JanusGraphOperationStatus> parentVertex = janusGraphDao
1045 .getParentVertex(subCategoryV, EdgeLabelEnum.SUB_CATEGORY, JsonParseFlagEnum.NoParse);
1046 Vertex categoryV = parentVertex.left().value();
1047 String categoryNormalizedName = (String) categoryV.property(GraphPropertyEnum.NORMALIZED_NAME.getProperty()).value();
1048 catalogComponent.setCategoryNormalizedName(categoryNormalizedName);
1049 CategoryDefinition category = new CategoryDefinition();
1050 category.setUniqueId((String) categoryV.property(GraphPropertyEnum.UNIQUE_ID.getProperty()).value());
1051 category.setNormalizedName(categoryNormalizedName);
1052 category.setName((String) categoryV.property(GraphPropertyEnum.NAME.getProperty()).value());
1053 category.addSubCategory(subcategory);
1054 categories.add(category);
1055 catalogComponent.setCategories(categories);
1056 return JanusGraphOperationStatus.OK;
1059 protected JanusGraphOperationStatus setServiceCategoryFromGraphV(Vertex vertex, CatalogComponent catalogComponent) {
1060 List<CategoryDefinition> categories = new ArrayList<>();
1061 Either<Vertex, JanusGraphOperationStatus> childVertex = janusGraphDao
1062 .getChildVertex(vertex, EdgeLabelEnum.CATEGORY, JsonParseFlagEnum.NoParse);
1063 if (childVertex.isRight()) {
1064 log.debug(FAILED_TO_FETCH_FOR_TOSCA_ELEMENT_WITH_ID_ERROR, EdgeLabelEnum.CATEGORY, catalogComponent.getUniqueId(),
1065 childVertex.right().value());
1066 return childVertex.right().value();
1068 Vertex categoryV = childVertex.left().value();
1069 String categoryNormalizedName = (String) categoryV.property(GraphPropertyEnum.NORMALIZED_NAME.getProperty()).value();
1070 catalogComponent.setCategoryNormalizedName(categoryNormalizedName);
1071 CategoryDefinition category = new CategoryDefinition();
1072 category.setUniqueId((String) categoryV.property(GraphPropertyEnum.UNIQUE_ID.getProperty()).value());
1073 category.setNormalizedName(categoryNormalizedName);
1074 category.setModels(categoryV.property(GraphPropertyEnum.MODEL.getProperty()).isPresent() ? getGson()
1075 .fromJson((String) categoryV.property(GraphPropertyEnum.MODEL.getProperty()).value(), new TypeToken<List<String>>() {
1076 }.getType()) : Collections.emptyList());
1077 category.setName((String) categoryV.property(GraphPropertyEnum.NAME.getProperty()).value());
1078 category.setUseServiceSubstitutionForNestedServices(
1079 (Boolean) categoryV.property(GraphPropertyEnum.USE_SUBSTITUTION_FOR_NESTED_SERVICES.getProperty()).orElse(false));
1080 Type listTypeCat = new TypeToken<List<MetadataKeyDataDefinition>>() {
1082 List<MetadataKeyDataDefinition> metadataKeys = categoryV.property(GraphPropertyEnum.METADATA_KEYS.getProperty()).isPresent() ? getGson()
1083 .fromJson((String) categoryV.property(GraphPropertyEnum.METADATA_KEYS.getProperty()).value(), listTypeCat) : Collections.emptyList();
1084 category.setMetadataKeys(metadataKeys);
1085 categories.add(category);
1086 catalogComponent.setCategories(categories);
1087 return JanusGraphOperationStatus.OK;
1090 protected JanusGraphOperationStatus setResourceCategoryFromGraph(GraphVertex componentV, ToscaElement toscaElement) {
1091 List<CategoryDefinition> categories = new ArrayList<>();
1092 SubCategoryDefinition subcategory;
1093 Either<GraphVertex, JanusGraphOperationStatus> childVertex = janusGraphDao
1094 .getChildVertex(componentV, EdgeLabelEnum.CATEGORY, JsonParseFlagEnum.NoParse);
1095 if (childVertex.isRight()) {
1096 log.debug(FAILED_TO_FETCH_FOR_TOSCA_ELEMENT_WITH_ID_ERROR, EdgeLabelEnum.CATEGORY, componentV.getUniqueId(), childVertex.right().value());
1097 return childVertex.right().value();
1099 GraphVertex subCategoryV = childVertex.left().value();
1100 Map<GraphPropertyEnum, Object> metadataProperties = subCategoryV.getMetadataProperties();
1101 subcategory = new SubCategoryDefinition();
1102 subcategory.setUniqueId(subCategoryV.getUniqueId());
1103 subcategory.setNormalizedName((String) metadataProperties.get(GraphPropertyEnum.NORMALIZED_NAME));
1104 subcategory.setName((String) metadataProperties.get(GraphPropertyEnum.NAME));
1105 Type listTypeSubcat = new TypeToken<List<String>>() {
1107 List<String> iconsfromJsonSubcat = getGson().fromJson((String) metadataProperties.get(GraphPropertyEnum.ICONS), listTypeSubcat);
1108 subcategory.setIcons(iconsfromJsonSubcat);
1109 final Type metadataKeysTypeCat = new TypeToken<List<MetadataKeyDataDefinition>>() {
1111 final List<MetadataKeyDataDefinition> metadataKeysfromJsonCat = getGson()
1112 .fromJson((String) metadataProperties.get(GraphPropertyEnum.METADATA_KEYS), metadataKeysTypeCat);
1113 subcategory.setMetadataKeys(metadataKeysfromJsonCat);
1114 Either<GraphVertex, JanusGraphOperationStatus> parentVertex = janusGraphDao
1115 .getParentVertex(subCategoryV, EdgeLabelEnum.SUB_CATEGORY, JsonParseFlagEnum.NoParse);
1116 if (parentVertex.isRight()) {
1117 log.debug("failed to fetch {} for category with id {}, error {}", EdgeLabelEnum.SUB_CATEGORY, subCategoryV.getUniqueId(),
1118 parentVertex.right().value());
1119 return childVertex.right().value();
1121 GraphVertex categoryV = parentVertex.left().value();
1122 metadataProperties = categoryV.getMetadataProperties();
1123 CategoryDefinition category = new CategoryDefinition();
1124 category.setUniqueId(categoryV.getUniqueId());
1125 category.setNormalizedName((String) metadataProperties.get(GraphPropertyEnum.NORMALIZED_NAME));
1126 category.setName((String) metadataProperties.get(GraphPropertyEnum.NAME));
1127 Type listTypeCat = new TypeToken<List<String>>() {
1129 List<String> iconsfromJsonCat = getGson().fromJson((String) metadataProperties.get(GraphPropertyEnum.ICONS), listTypeCat);
1130 category.setIcons(iconsfromJsonCat);
1131 category.addSubCategory(subcategory);
1132 categories.add(category);
1133 toscaElement.setCategories(categories);
1134 return JanusGraphOperationStatus.OK;
1137 public <T extends ToscaElement> Either<T, StorageOperationStatus> updateToscaElement(T toscaElementToUpdate, GraphVertex elementV,
1138 ComponentParametersView filterResult) {
1139 Either<T, StorageOperationStatus> result = null;
1140 log.debug("In updateToscaElement. received component uid = {}", (toscaElementToUpdate == null ? null : toscaElementToUpdate.getUniqueId()));
1141 if (toscaElementToUpdate == null) {
1142 log.error("Service object is null");
1143 result = Either.right(StorageOperationStatus.BAD_REQUEST);
1146 String modifierUserId = toscaElementToUpdate.getLastUpdaterUserId();
1147 if (modifierUserId == null || modifierUserId.isEmpty()) {
1148 log.error("UserId is missing in the request.");
1149 result = Either.right(StorageOperationStatus.BAD_REQUEST);
1152 Either<GraphVertex, JanusGraphOperationStatus> findUser = findUserVertex(modifierUserId);
1153 if (findUser.isRight()) {
1154 JanusGraphOperationStatus status = findUser.right().value();
1155 log.error(CANNOT_FIND_USER_IN_THE_GRAPH_STATUS_IS, modifierUserId, status);
1158 GraphVertex modifierV = findUser.left().value();
1159 String toscaElementId = toscaElementToUpdate.getUniqueId();
1160 Either<GraphVertex, JanusGraphOperationStatus> parentVertex = janusGraphDao
1161 .getParentVertex(elementV, EdgeLabelEnum.LAST_MODIFIER, JsonParseFlagEnum.NoParse);
1162 if (parentVertex.isRight()) {
1163 log.debug("Failed to fetch last modifier for tosca element with id {} error {}", toscaElementId, parentVertex.right().value());
1164 return Either.right(DaoStatusConverter.convertJanusGraphStatusToStorageStatus(parentVertex.right().value()));
1166 GraphVertex userV = parentVertex.left().value();
1167 String currentModifier = (String) userV.getMetadataProperty(GraphPropertyEnum.USERID);
1168 String prevSystemName = (String) elementV.getMetadataProperty(GraphPropertyEnum.SYSTEM_NAME);
1169 if (currentModifier.equals(modifierUserId)) {
1170 log.debug("Graph LAST MODIFIER edge should not be changed since the modifier is the same as the last modifier.");
1172 log.debug("Going to update the last modifier user of the resource from {} to {}", currentModifier, modifierUserId);
1173 StorageOperationStatus status = moveLastModifierEdge(elementV, modifierV);
1174 log.debug("Finish to update the last modifier user of the resource from {} to {}. status is {}", currentModifier, modifierUserId, status);
1175 if (status != StorageOperationStatus.OK) {
1176 result = Either.right(status);
1180 final long currentTimeMillis = System.currentTimeMillis();
1181 log.debug("Going to update the last Update Date of the resource from {} to {}",
1182 elementV.getJsonMetadataField(JsonPresentationFields.LAST_UPDATE_DATE), currentTimeMillis);
1183 elementV.setJsonMetadataField(JsonPresentationFields.LAST_UPDATE_DATE, currentTimeMillis);
1184 StorageOperationStatus checkCategories = validateCategories(toscaElementToUpdate, elementV);
1185 if (checkCategories != StorageOperationStatus.OK) {
1186 result = Either.right(checkCategories);
1189 // update all data on vertex
1190 fillToscaElementVertexData(elementV, toscaElementToUpdate, JsonParseFlagEnum.ParseMetadata);
1191 Either<GraphVertex, JanusGraphOperationStatus> updateElement = janusGraphDao.updateVertex(elementV);
1192 if (updateElement.isRight()) {
1193 log.error("Failed to update resource {}. status is {}", toscaElementId, updateElement.right().value());
1194 result = Either.right(DaoStatusConverter.convertJanusGraphStatusToStorageStatus(updateElement.right().value()));
1197 GraphVertex updateElementV = updateElement.left().value();
1198 // DE230195 in case resource name changed update TOSCA artifacts
1200 // file names accordingly
1201 String newSystemName = (String) updateElementV.getMetadataProperty(GraphPropertyEnum.SYSTEM_NAME);
1202 if (newSystemName != null && !newSystemName.equals(prevSystemName)) {
1203 Either<Map<String, ArtifactDataDefinition>, JanusGraphOperationStatus> resultToscaArt = getDataFromGraph(updateElementV,
1204 EdgeLabelEnum.TOSCA_ARTIFACTS);
1205 if (resultToscaArt.isRight()) {
1206 log.debug("Failed to get tosca artifact from graph for tosca element {} error {}", toscaElementId, resultToscaArt.right().value());
1207 return Either.right(DaoStatusConverter.convertJanusGraphStatusToStorageStatus(resultToscaArt.right().value()));
1209 Map<String, ArtifactDataDefinition> toscaArtifacts = resultToscaArt.left().value();
1210 if (toscaArtifacts != null) {
1211 for (Entry<String, ArtifactDataDefinition> artifact : toscaArtifacts.entrySet()) {
1212 generateNewToscaFileName(toscaElementToUpdate.getComponentType().getValue().toLowerCase(), newSystemName, artifact.getValue());
1214 // TODO call to new Artifact operation in order to update list of artifacts
1217 if (toscaElementToUpdate.getComponentType() == ComponentTypeEnum.RESOURCE) {
1218 StorageOperationStatus resultDerived = updateDerived(toscaElementToUpdate, updateElementV);
1219 if (resultDerived != StorageOperationStatus.OK) {
1220 log.debug("Failed to update from derived data for element {} error {}", toscaElementId, resultDerived);
1221 return Either.right(resultDerived);
1224 Either<T, StorageOperationStatus> updatedResource = getToscaElement(updateElementV, filterResult);
1225 if (updatedResource.isRight()) {
1226 log.error("Failed to fetch tosca element {} after update , error {}", toscaElementId, updatedResource.right().value());
1227 result = Either.right(StorageOperationStatus.BAD_REQUEST);
1230 T updatedResourceValue = updatedResource.left().value();
1231 result = Either.left(updatedResourceValue);
1235 protected StorageOperationStatus moveLastModifierEdge(GraphVertex elementV, GraphVertex modifierV) {
1236 return DaoStatusConverter
1237 .convertJanusGraphStatusToStorageStatus(janusGraphDao.moveEdge(elementV, modifierV, EdgeLabelEnum.LAST_MODIFIER, Direction.IN));
1240 protected StorageOperationStatus moveCategoryEdge(GraphVertex elementV, GraphVertex categoryV) {
1241 return DaoStatusConverter
1242 .convertJanusGraphStatusToStorageStatus(janusGraphDao.moveEdge(elementV, categoryV, EdgeLabelEnum.CATEGORY, Direction.OUT));
1245 private void generateNewToscaFileName(String componentType, String componentName, ArtifactDataDefinition artifactInfo) {
1246 Optional<Entry<String, Object>> oConfig = ConfigurationManager.getConfigurationManager().getConfiguration().getToscaArtifacts()
1247 .entrySet().stream().filter(p -> p.getKey().equalsIgnoreCase(artifactInfo.getArtifactLabel())).findAny();
1248 if (oConfig.isPresent()) {
1249 artifactInfo.setArtifactName(componentType + "-" + componentName + ((Map<String, Object>)oConfig.get().getValue()).get("artifactName"));
1252 artifactInfo.setArtifactName(componentType + "-" + componentName);
1256 protected <T extends ToscaElement> StorageOperationStatus validateResourceCategory(T toscaElementToUpdate, GraphVertex elementV) {
1257 StorageOperationStatus status = StorageOperationStatus.OK;
1258 List<CategoryDefinition> newCategoryList = toscaElementToUpdate.getCategories();
1259 CategoryDefinition newCategory = newCategoryList.get(0);
1260 Either<GraphVertex, JanusGraphOperationStatus> childVertex = janusGraphDao
1261 .getChildVertex(elementV, EdgeLabelEnum.CATEGORY, JsonParseFlagEnum.NoParse);
1262 if (childVertex.isRight()) {
1263 log.debug(FAILED_TO_FETCH_FOR_TOSCA_ELEMENT_WITH_ID_ERROR, EdgeLabelEnum.CATEGORY, elementV.getUniqueId(), childVertex.right().value());
1264 return DaoStatusConverter.convertJanusGraphStatusToStorageStatus(childVertex.right().value());
1266 GraphVertex subCategoryV = childVertex.left().value();
1267 Map<GraphPropertyEnum, Object> metadataProperties = subCategoryV.getMetadataProperties();
1268 String subCategoryNameCurrent = (String) metadataProperties.get(GraphPropertyEnum.NAME);
1269 Either<GraphVertex, JanusGraphOperationStatus> parentVertex = janusGraphDao
1270 .getParentVertex(subCategoryV, EdgeLabelEnum.SUB_CATEGORY, JsonParseFlagEnum.NoParse);
1271 if (parentVertex.isRight()) {
1272 log.debug("failed to fetch {} for category with id {}, error {}", EdgeLabelEnum.SUB_CATEGORY, subCategoryV.getUniqueId(),
1273 parentVertex.right().value());
1274 return DaoStatusConverter.convertJanusGraphStatusToStorageStatus(childVertex.right().value());
1276 GraphVertex categoryV = parentVertex.left().value();
1277 metadataProperties = categoryV.getMetadataProperties();
1278 String categoryNameCurrent = (String) metadataProperties.get(GraphPropertyEnum.NAME);
1279 boolean categoryWasChanged = false;
1280 String newCategoryName = newCategory.getName();
1281 SubCategoryDefinition newSubcategory = newCategory.getSubcategories().get(0);
1282 String newSubCategoryName = newSubcategory.getName();
1283 if (newCategoryName != null && !newCategoryName.equals(categoryNameCurrent)) {
1284 // the category was changed
1285 categoryWasChanged = true;
1287 // the sub-category was changed
1288 if (newSubCategoryName != null && !newSubCategoryName.equals(subCategoryNameCurrent)) {
1289 log.debug("Going to update the category of the resource from {} to {}", categoryNameCurrent, newCategory);
1290 categoryWasChanged = true;
1293 if (categoryWasChanged) {
1294 Either<GraphVertex, StorageOperationStatus> getCategoryVertex = getResourceCategoryVertex(elementV.getUniqueId(), newSubCategoryName,
1296 if (getCategoryVertex.isRight()) {
1297 return getCategoryVertex.right().value();
1299 GraphVertex newCategoryV = getCategoryVertex.left().value();
1300 status = moveCategoryEdge(elementV, newCategoryV);
1301 log.debug("Going to update the category of the resource from {} to {}. status is {}", categoryNameCurrent, newCategory, status);
1306 public <T extends ToscaElement> Either<List<T>, StorageOperationStatus> getElementCatalogData(ComponentTypeEnum componentType,
1307 List<ResourceTypeEnum> excludeTypes,
1308 boolean isHighestVersions) {
1309 Either<List<GraphVertex>, JanusGraphOperationStatus> listOfComponents;
1310 if (isHighestVersions) {
1311 listOfComponents = getListOfHighestComponents(componentType, excludeTypes, JsonParseFlagEnum.NoParse);
1313 listOfComponents = getListOfHighestAndAllCertifiedComponents(componentType, excludeTypes);
1315 if (listOfComponents.isRight() && listOfComponents.right().value() != JanusGraphOperationStatus.NOT_FOUND) {
1316 return Either.right(DaoStatusConverter.convertJanusGraphStatusToStorageStatus(listOfComponents.right().value()));
1318 List<T> result = new ArrayList<>();
1319 if (listOfComponents.isLeft()) {
1320 List<GraphVertex> highestAndAllCertified = listOfComponents.left().value();
1321 if (highestAndAllCertified != null && !highestAndAllCertified.isEmpty()) {
1322 for (GraphVertex vertexComponent : highestAndAllCertified) {
1323 Either<T, StorageOperationStatus> component = getLightComponent(vertexComponent, componentType,
1324 new ComponentParametersView(true));
1325 if (component.isRight()) {
1326 log.debug("Failed to fetch light element for {} error {}", vertexComponent.getUniqueId(), component.right().value());
1327 return Either.right(component.right().value());
1329 result.add(component.left().value());
1334 return Either.left(result);
1337 public Either<List<CatalogComponent>, StorageOperationStatus> getElementCatalogData(boolean isCatalog, List<ResourceTypeEnum> excludeTypes) {
1338 StopWatch stopWatch = new StopWatch();
1340 Map<String, CatalogComponent> existInCatalog = new HashMap<>();
1341 Either<Iterator<Vertex>, JanusGraphOperationStatus> verticesEither = janusGraphDao.getCatalogOrArchiveVerticies(isCatalog);
1342 if (verticesEither.isRight()) {
1343 return Either.right(DaoStatusConverter.convertJanusGraphStatusToStorageStatus(verticesEither.right().value()));
1345 Iterator<Vertex> vertices = verticesEither.left().value();
1346 while (vertices.hasNext()) {
1347 handleCatalogComponent(existInCatalog, vertices.next(), excludeTypes);
1350 String timeToFetchElements = stopWatch.prettyPrint();
1351 log.info("time to fetch all catalog elements: {}", timeToFetchElements);
1352 return Either.left(existInCatalog.values().stream().collect(Collectors.toList()));
1355 private void handleCatalogComponent(Map<String, CatalogComponent> existInCatalog, Vertex vertex, List<ResourceTypeEnum> excludeTypes) {
1356 VertexProperty<Object> property = vertex.property(GraphPropertiesDictionary.METADATA.getProperty());
1357 String json = (String) property.value();
1358 Map<String, Object> metadatObj = JsonParserUtils.toMap(json);
1359 String uniqueId = (String) metadatObj.get(JsonPresentationFields.UNIQUE_ID.getPresentation());
1360 Boolean isDeleted = (Boolean) metadatObj.get(JsonPresentationFields.IS_DELETED.getPresentation());
1361 if (isAddToCatalog(excludeTypes, metadatObj) && (existInCatalog.get(uniqueId) == null && (isDeleted == null || !isDeleted.booleanValue()))) {
1362 CatalogComponent catalogComponent = new CatalogComponent();
1363 catalogComponent.setUniqueId(uniqueId);
1364 catalogComponent.setModel((String) metadatObj.get(JsonPresentationFields.MODEL.getPresentation()));
1366 .setComponentType(ComponentTypeEnum.valueOf((String) metadatObj.get(JsonPresentationFields.COMPONENT_TYPE.getPresentation())));
1367 catalogComponent.setVersion((String) metadatObj.get(JsonPresentationFields.VERSION.getPresentation()));
1368 catalogComponent.setName((String) metadatObj.get(JsonPresentationFields.NAME.getPresentation()));
1369 catalogComponent.setIcon((String) metadatObj.get(JsonPresentationFields.ICON.getPresentation()));
1370 catalogComponent.setLifecycleState((String) metadatObj.get(JsonPresentationFields.LIFECYCLE_STATE.getPresentation()));
1371 Object lastUpdateDate = metadatObj.get(JsonPresentationFields.LAST_UPDATE_DATE.getPresentation());
1372 catalogComponent.setLastUpdateDate((lastUpdateDate != null ? (Long) lastUpdateDate : 0L));
1373 catalogComponent.setDistributionStatus((String) metadatObj.get(JsonPresentationFields.DISTRIBUTION_STATUS.getPresentation()));
1374 catalogComponent.setDescription((String) metadatObj.get(JsonPresentationFields.DESCRIPTION.getPresentation()));
1375 catalogComponent.setTenant((String) metadatObj.get(JsonPresentationFields.TENANT.getPresentation()));
1376 catalogComponent.setSystemName((String) metadatObj.get(JsonPresentationFields.SYSTEM_NAME.getPresentation()));
1377 catalogComponent.setUuid((String) metadatObj.get(JsonPresentationFields.UUID.getPresentation()));
1378 catalogComponent.setInvariantUUID((String) metadatObj.get(JsonPresentationFields.INVARIANT_UUID.getPresentation()));
1379 catalogComponent.setIsHighestVersion((Boolean) metadatObj.get(JsonPresentationFields.HIGHEST_VERSION.getPresentation()));
1380 Iterator<Edge> edges = vertex.edges(Direction.IN, EdgeLabelEnum.STATE.name());
1381 if (edges.hasNext()) {
1383 .setLastUpdaterUserId((String) edges.next().outVertex().property(GraphPropertiesDictionary.USERID.getProperty()).value());
1385 Object resourceType = metadatObj.get(JsonPresentationFields.RESOURCE_TYPE.getPresentation());
1386 if (resourceType != null) {
1387 catalogComponent.setResourceType((String) resourceType);
1389 if (catalogComponent.getComponentType() == ComponentTypeEnum.SERVICE) {
1390 setServiceCategoryFromGraphV(vertex, catalogComponent);
1392 setResourceCategoryFromGraphV(vertex, catalogComponent);
1394 List<String> tags = (List<String>) metadatObj.get(JsonPresentationFields.TAGS.getPresentation());
1396 catalogComponent.setTags(tags);
1398 existInCatalog.put(uniqueId, catalogComponent);
1402 private boolean isAddToCatalog(List<ResourceTypeEnum> excludeTypes, Map<String, Object> metadatObj) {
1403 boolean isAddToCatalog = true;
1404 Object resourceTypeStr = metadatObj.get(JsonPresentationFields.RESOURCE_TYPE.getPresentation());
1405 if (resourceTypeStr != null) {
1406 ResourceTypeEnum resourceType = ResourceTypeEnum.getType((String) resourceTypeStr);
1407 if (!CollectionUtils.isEmpty(excludeTypes)) {
1408 Optional<ResourceTypeEnum> op = excludeTypes.stream().filter(rt -> rt == resourceType).findAny();
1409 if (op.isPresent()) {
1410 isAddToCatalog = false;
1414 return isAddToCatalog;
1417 public Either<List<GraphVertex>, JanusGraphOperationStatus> getListOfHighestComponents(ComponentTypeEnum componentType,
1418 List<ResourceTypeEnum> excludeTypes,
1419 JsonParseFlagEnum parseFlag) {
1420 Map<GraphPropertyEnum, Object> propertiesToMatch = new EnumMap<>(GraphPropertyEnum.class);
1421 Map<GraphPropertyEnum, Object> propertiesHasNotToMatch = new EnumMap<>(GraphPropertyEnum.class);
1422 propertiesToMatch.put(GraphPropertyEnum.COMPONENT_TYPE, componentType.name());
1423 propertiesToMatch.put(GraphPropertyEnum.IS_HIGHEST_VERSION, true);
1424 if (componentType == ComponentTypeEnum.RESOURCE) {
1425 propertiesToMatch.put(GraphPropertyEnum.IS_ABSTRACT, false);
1426 propertiesHasNotToMatch.put(GraphPropertyEnum.RESOURCE_TYPE, excludeTypes);
1428 propertiesHasNotToMatch.put(GraphPropertyEnum.IS_DELETED, true);
1429 propertiesHasNotToMatch.put(GraphPropertyEnum.IS_ARCHIVED, true); //US382674, US382683
1430 return janusGraphDao.getByCriteria(null, propertiesToMatch, propertiesHasNotToMatch, parseFlag);
1433 // highest + (certified && !highest)
1434 public Either<List<GraphVertex>, JanusGraphOperationStatus> getListOfHighestAndAllCertifiedComponents(ComponentTypeEnum componentType,
1435 List<ResourceTypeEnum> excludeTypes) {
1436 long startFetchAllStates = System.currentTimeMillis();
1437 Either<List<GraphVertex>, JanusGraphOperationStatus> highestNodes = getListOfHighestComponents(componentType, excludeTypes,
1438 JsonParseFlagEnum.ParseMetadata);
1439 Map<GraphPropertyEnum, Object> propertiesToMatchCertified = new EnumMap<>(GraphPropertyEnum.class);
1440 Map<GraphPropertyEnum, Object> propertiesHasNotToMatchCertified = new EnumMap<>(GraphPropertyEnum.class);
1441 propertiesToMatchCertified.put(GraphPropertyEnum.STATE, LifecycleStateEnum.CERTIFIED.name());
1442 propertiesToMatchCertified.put(GraphPropertyEnum.COMPONENT_TYPE, componentType.name());
1443 if (componentType == ComponentTypeEnum.RESOURCE) {
1444 propertiesToMatchCertified.put(GraphPropertyEnum.IS_ABSTRACT, false);
1445 propertiesHasNotToMatchCertified.put(GraphPropertyEnum.RESOURCE_TYPE, excludeTypes);
1447 propertiesHasNotToMatchCertified.put(GraphPropertyEnum.IS_DELETED, true);
1448 propertiesHasNotToMatchCertified.put(GraphPropertyEnum.IS_ARCHIVED, true); //US382674, US382683
1449 propertiesHasNotToMatchCertified.put(GraphPropertyEnum.IS_HIGHEST_VERSION, true);
1450 Either<List<GraphVertex>, JanusGraphOperationStatus> certifiedNotHighestNodes = janusGraphDao
1451 .getByCriteria(null, propertiesToMatchCertified, propertiesHasNotToMatchCertified, JsonParseFlagEnum.ParseMetadata);
1452 if (certifiedNotHighestNodes.isRight() && certifiedNotHighestNodes.right().value() != JanusGraphOperationStatus.NOT_FOUND) {
1453 return Either.right(certifiedNotHighestNodes.right().value());
1455 long endFetchAllStates = System.currentTimeMillis();
1456 List<GraphVertex> allNodes = new ArrayList<>();
1457 if (certifiedNotHighestNodes.isLeft()) {
1458 allNodes.addAll(certifiedNotHighestNodes.left().value());
1460 if (highestNodes.isLeft()) {
1461 allNodes.addAll(highestNodes.left().value());
1463 log.debug("Fetch catalog {}s all states from graph took {} ms", componentType, endFetchAllStates - startFetchAllStates);
1464 return Either.left(allNodes);
1467 protected Either<List<GraphVertex>, StorageOperationStatus> getAllComponentsMarkedForDeletion(ComponentTypeEnum componentType) {
1468 // get all components marked for delete
1469 Map<GraphPropertyEnum, Object> props = new EnumMap<>(GraphPropertyEnum.class);
1470 props.put(GraphPropertyEnum.IS_DELETED, true);
1471 props.put(GraphPropertyEnum.COMPONENT_TYPE, componentType.name());
1472 Either<List<GraphVertex>, JanusGraphOperationStatus> componentsToDelete = janusGraphDao.getByCriteria(null, props, JsonParseFlagEnum.NoParse);
1473 if (componentsToDelete.isRight()) {
1474 JanusGraphOperationStatus error = componentsToDelete.right().value();
1475 if (error.equals(JanusGraphOperationStatus.NOT_FOUND)) {
1476 log.trace("no components to delete");
1477 return Either.left(new ArrayList<>());
1479 log.info("failed to find components to delete. error : {}", error.name());
1480 return Either.right(DaoStatusConverter.convertJanusGraphStatusToStorageStatus(error));
1483 return Either.left(componentsToDelete.left().value());
1486 protected JanusGraphOperationStatus setAdditionalInformationFromGraph(GraphVertex componentV, ToscaElement toscaElement) {
1487 Either<Map<String, AdditionalInfoParameterDataDefinition>, JanusGraphOperationStatus> result = getDataFromGraph(componentV,
1488 EdgeLabelEnum.ADDITIONAL_INFORMATION);
1489 if (result.isLeft()) {
1490 toscaElement.setAdditionalInformation(result.left().value());
1492 if (result.right().value() != JanusGraphOperationStatus.NOT_FOUND) {
1493 return result.right().value();
1496 return JanusGraphOperationStatus.OK;
1499 // --------------------------------------------
1500 public abstract <T extends ToscaElement> Either<T, StorageOperationStatus> getToscaElement(String uniqueId,
1501 ComponentParametersView componentParametersView);
1503 public abstract <T extends ToscaElement> Either<T, StorageOperationStatus> getToscaElement(GraphVertex toscaElementVertex,
1504 ComponentParametersView componentParametersView);
1506 public abstract <T extends ToscaElement> Either<T, StorageOperationStatus> deleteToscaElement(GraphVertex toscaElementVertex);
1508 public abstract <T extends ToscaElement> Either<T, StorageOperationStatus> createToscaElement(ToscaElement toscaElement);
1510 protected abstract <T extends ToscaElement> JanusGraphOperationStatus setCategoriesFromGraph(GraphVertex vertexComponent, T toscaElement);
1512 protected abstract <T extends ToscaElement> JanusGraphOperationStatus setCapabilitiesFromGraph(GraphVertex componentV, T toscaElement);
1514 protected abstract <T extends ToscaElement> JanusGraphOperationStatus setRequirementsFromGraph(GraphVertex componentV, T toscaElement);
1516 protected abstract <T extends ToscaElement> StorageOperationStatus validateCategories(T toscaElementToUpdate, GraphVertex elementV);
1518 protected abstract <T extends ToscaElement> StorageOperationStatus updateDerived(T toscaElementToUpdate, GraphVertex updateElementV);
1520 public abstract <T extends ToscaElement> void fillToscaElementVertexData(GraphVertex elementV, T toscaElementToUpdate, JsonParseFlagEnum flag);