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.getChildVertex(vertex, EdgeLabelEnum.CATEGORY);
1025 if (childVertex.isRight()) {
1026 log.debug(FAILED_TO_FETCH_FOR_TOSCA_ELEMENT_WITH_ID_ERROR, EdgeLabelEnum.CATEGORY, catalogComponent.getUniqueId(),
1027 childVertex.right().value());
1028 return childVertex.right().value();
1030 Vertex subCategoryV = childVertex.left().value();
1031 String subCategoryNormalizedName = (String) subCategoryV.property(GraphPropertyEnum.NORMALIZED_NAME.getProperty()).value();
1032 catalogComponent.setSubCategoryNormalizedName(subCategoryNormalizedName);
1033 subcategory = new SubCategoryDefinition();
1034 subcategory.setUniqueId((String) subCategoryV.property(GraphPropertyEnum.UNIQUE_ID.getProperty()).value());
1035 subcategory.setNormalizedName(subCategoryNormalizedName);
1036 subcategory.setName((String) subCategoryV.property(GraphPropertyEnum.NAME.getProperty()).value());
1037 Type listTypeSubcat = new TypeToken<List<MetadataKeyDataDefinition>>() {
1039 List<MetadataKeyDataDefinition> metadataKeys = subCategoryV.property(GraphPropertyEnum.METADATA_KEYS.getProperty()).isPresent() ? getGson()
1040 .fromJson((String) subCategoryV.property(GraphPropertyEnum.METADATA_KEYS.getProperty()).value(), listTypeSubcat)
1041 : Collections.emptyList();
1042 subcategory.setMetadataKeys(metadataKeys);
1043 Either<Vertex, JanusGraphOperationStatus> parentVertex = janusGraphDao.getParentVertex(subCategoryV, EdgeLabelEnum.SUB_CATEGORY);
1044 Vertex categoryV = parentVertex.left().value();
1045 String categoryNormalizedName = (String) categoryV.property(GraphPropertyEnum.NORMALIZED_NAME.getProperty()).value();
1046 catalogComponent.setCategoryNormalizedName(categoryNormalizedName);
1047 CategoryDefinition category = new CategoryDefinition();
1048 category.setUniqueId((String) categoryV.property(GraphPropertyEnum.UNIQUE_ID.getProperty()).value());
1049 category.setNormalizedName(categoryNormalizedName);
1050 category.setName((String) categoryV.property(GraphPropertyEnum.NAME.getProperty()).value());
1051 category.addSubCategory(subcategory);
1052 categories.add(category);
1053 catalogComponent.setCategories(categories);
1054 return JanusGraphOperationStatus.OK;
1057 protected JanusGraphOperationStatus setServiceCategoryFromGraphV(Vertex vertex, CatalogComponent catalogComponent) {
1058 List<CategoryDefinition> categories = new ArrayList<>();
1059 Either<Vertex, JanusGraphOperationStatus> childVertex = janusGraphDao.getChildVertex(vertex, EdgeLabelEnum.CATEGORY);
1060 if (childVertex.isRight()) {
1061 log.debug(FAILED_TO_FETCH_FOR_TOSCA_ELEMENT_WITH_ID_ERROR, EdgeLabelEnum.CATEGORY, catalogComponent.getUniqueId(),
1062 childVertex.right().value());
1063 return childVertex.right().value();
1065 Vertex categoryV = childVertex.left().value();
1066 String categoryNormalizedName = (String) categoryV.property(GraphPropertyEnum.NORMALIZED_NAME.getProperty()).value();
1067 catalogComponent.setCategoryNormalizedName(categoryNormalizedName);
1068 CategoryDefinition category = new CategoryDefinition();
1069 category.setUniqueId((String) categoryV.property(GraphPropertyEnum.UNIQUE_ID.getProperty()).value());
1070 category.setNormalizedName(categoryNormalizedName);
1071 category.setModels(categoryV.property(GraphPropertyEnum.MODEL.getProperty()).isPresent() ? getGson()
1072 .fromJson((String) categoryV.property(GraphPropertyEnum.MODEL.getProperty()).value(), new TypeToken<List<String>>() {
1073 }.getType()) : Collections.emptyList());
1074 category.setName((String) categoryV.property(GraphPropertyEnum.NAME.getProperty()).value());
1075 category.setUseServiceSubstitutionForNestedServices(
1076 (Boolean) categoryV.property(GraphPropertyEnum.USE_SUBSTITUTION_FOR_NESTED_SERVICES.getProperty()).orElse(false));
1077 Type listTypeCat = new TypeToken<List<MetadataKeyDataDefinition>>() {
1079 List<MetadataKeyDataDefinition> metadataKeys = categoryV.property(GraphPropertyEnum.METADATA_KEYS.getProperty()).isPresent() ? getGson()
1080 .fromJson((String) categoryV.property(GraphPropertyEnum.METADATA_KEYS.getProperty()).value(), listTypeCat) : Collections.emptyList();
1081 category.setMetadataKeys(metadataKeys);
1082 categories.add(category);
1083 catalogComponent.setCategories(categories);
1084 return JanusGraphOperationStatus.OK;
1087 protected JanusGraphOperationStatus setResourceCategoryFromGraph(GraphVertex componentV, ToscaElement toscaElement) {
1088 List<CategoryDefinition> categories = new ArrayList<>();
1089 SubCategoryDefinition subcategory;
1090 Either<GraphVertex, JanusGraphOperationStatus> childVertex = janusGraphDao
1091 .getChildVertex(componentV, EdgeLabelEnum.CATEGORY, JsonParseFlagEnum.NoParse);
1092 if (childVertex.isRight()) {
1093 log.debug(FAILED_TO_FETCH_FOR_TOSCA_ELEMENT_WITH_ID_ERROR, EdgeLabelEnum.CATEGORY, componentV.getUniqueId(), childVertex.right().value());
1094 return childVertex.right().value();
1096 GraphVertex subCategoryV = childVertex.left().value();
1097 Map<GraphPropertyEnum, Object> metadataProperties = subCategoryV.getMetadataProperties();
1098 subcategory = new SubCategoryDefinition();
1099 subcategory.setUniqueId(subCategoryV.getUniqueId());
1100 subcategory.setNormalizedName((String) metadataProperties.get(GraphPropertyEnum.NORMALIZED_NAME));
1101 subcategory.setName((String) metadataProperties.get(GraphPropertyEnum.NAME));
1102 Type listTypeSubcat = new TypeToken<List<String>>() {
1104 List<String> iconsfromJsonSubcat = getGson().fromJson((String) metadataProperties.get(GraphPropertyEnum.ICONS), listTypeSubcat);
1105 subcategory.setIcons(iconsfromJsonSubcat);
1106 final Type metadataKeysTypeCat = new TypeToken<List<MetadataKeyDataDefinition>>() {
1108 final List<MetadataKeyDataDefinition> metadataKeysfromJsonCat = getGson()
1109 .fromJson((String) metadataProperties.get(GraphPropertyEnum.METADATA_KEYS), metadataKeysTypeCat);
1110 subcategory.setMetadataKeys(metadataKeysfromJsonCat);
1111 Either<GraphVertex, JanusGraphOperationStatus> parentVertex = janusGraphDao
1112 .getParentVertex(subCategoryV, EdgeLabelEnum.SUB_CATEGORY, JsonParseFlagEnum.NoParse);
1113 if (parentVertex.isRight()) {
1114 log.debug("failed to fetch {} for category with id {}, error {}", EdgeLabelEnum.SUB_CATEGORY, subCategoryV.getUniqueId(),
1115 parentVertex.right().value());
1116 return childVertex.right().value();
1118 GraphVertex categoryV = parentVertex.left().value();
1119 metadataProperties = categoryV.getMetadataProperties();
1120 CategoryDefinition category = new CategoryDefinition();
1121 category.setUniqueId(categoryV.getUniqueId());
1122 category.setNormalizedName((String) metadataProperties.get(GraphPropertyEnum.NORMALIZED_NAME));
1123 category.setName((String) metadataProperties.get(GraphPropertyEnum.NAME));
1124 Type listTypeCat = new TypeToken<List<String>>() {
1126 List<String> iconsfromJsonCat = getGson().fromJson((String) metadataProperties.get(GraphPropertyEnum.ICONS), listTypeCat);
1127 category.setIcons(iconsfromJsonCat);
1128 category.addSubCategory(subcategory);
1129 categories.add(category);
1130 toscaElement.setCategories(categories);
1131 return JanusGraphOperationStatus.OK;
1134 public <T extends ToscaElement> Either<T, StorageOperationStatus> updateToscaElement(T toscaElementToUpdate, GraphVertex elementV,
1135 ComponentParametersView filterResult) {
1136 Either<T, StorageOperationStatus> result = null;
1137 log.debug("In updateToscaElement. received component uid = {}", (toscaElementToUpdate == null ? null : toscaElementToUpdate.getUniqueId()));
1138 if (toscaElementToUpdate == null) {
1139 log.error("Service object is null");
1140 result = Either.right(StorageOperationStatus.BAD_REQUEST);
1143 String modifierUserId = toscaElementToUpdate.getLastUpdaterUserId();
1144 if (modifierUserId == null || modifierUserId.isEmpty()) {
1145 log.error("UserId is missing in the request.");
1146 result = Either.right(StorageOperationStatus.BAD_REQUEST);
1149 Either<GraphVertex, JanusGraphOperationStatus> findUser = findUserVertex(modifierUserId);
1150 if (findUser.isRight()) {
1151 JanusGraphOperationStatus status = findUser.right().value();
1152 log.error(CANNOT_FIND_USER_IN_THE_GRAPH_STATUS_IS, modifierUserId, status);
1155 GraphVertex modifierV = findUser.left().value();
1156 String toscaElementId = toscaElementToUpdate.getUniqueId();
1157 Either<GraphVertex, JanusGraphOperationStatus> parentVertex = janusGraphDao
1158 .getParentVertex(elementV, EdgeLabelEnum.LAST_MODIFIER, JsonParseFlagEnum.NoParse);
1159 if (parentVertex.isRight()) {
1160 log.debug("Failed to fetch last modifier for tosca element with id {} error {}", toscaElementId, parentVertex.right().value());
1161 return Either.right(DaoStatusConverter.convertJanusGraphStatusToStorageStatus(parentVertex.right().value()));
1163 GraphVertex userV = parentVertex.left().value();
1164 String currentModifier = (String) userV.getMetadataProperty(GraphPropertyEnum.USERID);
1165 String prevSystemName = (String) elementV.getMetadataProperty(GraphPropertyEnum.SYSTEM_NAME);
1166 if (currentModifier.equals(modifierUserId)) {
1167 log.debug("Graph LAST MODIFIER edge should not be changed since the modifier is the same as the last modifier.");
1169 log.debug("Going to update the last modifier user of the resource from {} to {}", currentModifier, modifierUserId);
1170 StorageOperationStatus status = moveLastModifierEdge(elementV, modifierV);
1171 log.debug("Finish to update the last modifier user of the resource from {} to {}. status is {}", currentModifier, modifierUserId, status);
1172 if (status != StorageOperationStatus.OK) {
1173 result = Either.right(status);
1177 final long currentTimeMillis = System.currentTimeMillis();
1178 log.debug("Going to update the last Update Date of the resource from {} to {}",
1179 elementV.getJsonMetadataField(JsonPresentationFields.LAST_UPDATE_DATE), currentTimeMillis);
1180 elementV.setJsonMetadataField(JsonPresentationFields.LAST_UPDATE_DATE, currentTimeMillis);
1181 StorageOperationStatus checkCategories = validateCategories(toscaElementToUpdate, elementV);
1182 if (checkCategories != StorageOperationStatus.OK) {
1183 result = Either.right(checkCategories);
1186 // update all data on vertex
1187 fillToscaElementVertexData(elementV, toscaElementToUpdate, JsonParseFlagEnum.ParseMetadata);
1188 Either<GraphVertex, JanusGraphOperationStatus> updateElement = janusGraphDao.updateVertex(elementV);
1189 if (updateElement.isRight()) {
1190 log.error("Failed to update resource {}. status is {}", toscaElementId, updateElement.right().value());
1191 result = Either.right(DaoStatusConverter.convertJanusGraphStatusToStorageStatus(updateElement.right().value()));
1194 GraphVertex updateElementV = updateElement.left().value();
1195 // DE230195 in case resource name changed update TOSCA artifacts
1197 // file names accordingly
1198 String newSystemName = (String) updateElementV.getMetadataProperty(GraphPropertyEnum.SYSTEM_NAME);
1199 if (newSystemName != null && !newSystemName.equals(prevSystemName)) {
1200 Either<Map<String, ArtifactDataDefinition>, JanusGraphOperationStatus> resultToscaArt = getDataFromGraph(updateElementV,
1201 EdgeLabelEnum.TOSCA_ARTIFACTS);
1202 if (resultToscaArt.isRight()) {
1203 log.debug("Failed to get tosca artifact from graph for tosca element {} error {}", toscaElementId, resultToscaArt.right().value());
1204 return Either.right(DaoStatusConverter.convertJanusGraphStatusToStorageStatus(resultToscaArt.right().value()));
1206 Map<String, ArtifactDataDefinition> toscaArtifacts = resultToscaArt.left().value();
1207 if (toscaArtifacts != null) {
1208 for (Entry<String, ArtifactDataDefinition> artifact : toscaArtifacts.entrySet()) {
1209 generateNewToscaFileName(toscaElementToUpdate.getComponentType().getValue().toLowerCase(), newSystemName, artifact.getValue());
1211 // TODO call to new Artifact operation in order to update list of artifacts
1214 if (toscaElementToUpdate.getComponentType() == ComponentTypeEnum.RESOURCE) {
1215 StorageOperationStatus resultDerived = updateDerived(toscaElementToUpdate, updateElementV);
1216 if (resultDerived != StorageOperationStatus.OK) {
1217 log.debug("Failed to update from derived data for element {} error {}", toscaElementId, resultDerived);
1218 return Either.right(resultDerived);
1221 Either<T, StorageOperationStatus> updatedResource = getToscaElement(updateElementV, filterResult);
1222 if (updatedResource.isRight()) {
1223 log.error("Failed to fetch tosca element {} after update , error {}", toscaElementId, updatedResource.right().value());
1224 result = Either.right(StorageOperationStatus.BAD_REQUEST);
1227 T updatedResourceValue = updatedResource.left().value();
1228 result = Either.left(updatedResourceValue);
1232 protected StorageOperationStatus moveLastModifierEdge(GraphVertex elementV, GraphVertex modifierV) {
1233 return DaoStatusConverter
1234 .convertJanusGraphStatusToStorageStatus(janusGraphDao.moveEdge(elementV, modifierV, EdgeLabelEnum.LAST_MODIFIER, Direction.IN));
1237 protected StorageOperationStatus moveCategoryEdge(GraphVertex elementV, GraphVertex categoryV) {
1238 return DaoStatusConverter
1239 .convertJanusGraphStatusToStorageStatus(janusGraphDao.moveEdge(elementV, categoryV, EdgeLabelEnum.CATEGORY, Direction.OUT));
1242 private void generateNewToscaFileName(String componentType, String componentName, ArtifactDataDefinition artifactInfo) {
1243 Optional<Entry<String, Object>> oConfig = ConfigurationManager.getConfigurationManager().getConfiguration().getToscaArtifacts()
1244 .entrySet().stream().filter(p -> p.getKey().equalsIgnoreCase(artifactInfo.getArtifactLabel())).findAny();
1245 if (oConfig.isPresent()) {
1246 artifactInfo.setArtifactName(componentType + "-" + componentName + ((Map<String, Object>)oConfig.get().getValue()).get("artifactName"));
1249 artifactInfo.setArtifactName(componentType + "-" + componentName);
1253 protected <T extends ToscaElement> StorageOperationStatus validateResourceCategory(T toscaElementToUpdate, GraphVertex elementV) {
1254 StorageOperationStatus status = StorageOperationStatus.OK;
1255 List<CategoryDefinition> newCategoryList = toscaElementToUpdate.getCategories();
1256 CategoryDefinition newCategory = newCategoryList.get(0);
1257 Either<GraphVertex, JanusGraphOperationStatus> childVertex = janusGraphDao
1258 .getChildVertex(elementV, EdgeLabelEnum.CATEGORY, JsonParseFlagEnum.NoParse);
1259 if (childVertex.isRight()) {
1260 log.debug(FAILED_TO_FETCH_FOR_TOSCA_ELEMENT_WITH_ID_ERROR, EdgeLabelEnum.CATEGORY, elementV.getUniqueId(), childVertex.right().value());
1261 return DaoStatusConverter.convertJanusGraphStatusToStorageStatus(childVertex.right().value());
1263 GraphVertex subCategoryV = childVertex.left().value();
1264 Map<GraphPropertyEnum, Object> metadataProperties = subCategoryV.getMetadataProperties();
1265 String subCategoryNameCurrent = (String) metadataProperties.get(GraphPropertyEnum.NAME);
1266 Either<GraphVertex, JanusGraphOperationStatus> parentVertex = janusGraphDao
1267 .getParentVertex(subCategoryV, EdgeLabelEnum.SUB_CATEGORY, JsonParseFlagEnum.NoParse);
1268 if (parentVertex.isRight()) {
1269 log.debug("failed to fetch {} for category with id {}, error {}", EdgeLabelEnum.SUB_CATEGORY, subCategoryV.getUniqueId(),
1270 parentVertex.right().value());
1271 return DaoStatusConverter.convertJanusGraphStatusToStorageStatus(childVertex.right().value());
1273 GraphVertex categoryV = parentVertex.left().value();
1274 metadataProperties = categoryV.getMetadataProperties();
1275 String categoryNameCurrent = (String) metadataProperties.get(GraphPropertyEnum.NAME);
1276 boolean categoryWasChanged = false;
1277 String newCategoryName = newCategory.getName();
1278 SubCategoryDefinition newSubcategory = newCategory.getSubcategories().get(0);
1279 String newSubCategoryName = newSubcategory.getName();
1280 if (newCategoryName != null && !newCategoryName.equals(categoryNameCurrent)) {
1281 // the category was changed
1282 categoryWasChanged = true;
1284 // the sub-category was changed
1285 if (newSubCategoryName != null && !newSubCategoryName.equals(subCategoryNameCurrent)) {
1286 log.debug("Going to update the category of the resource from {} to {}", categoryNameCurrent, newCategory);
1287 categoryWasChanged = true;
1290 if (categoryWasChanged) {
1291 Either<GraphVertex, StorageOperationStatus> getCategoryVertex = getResourceCategoryVertex(elementV.getUniqueId(), newSubCategoryName,
1293 if (getCategoryVertex.isRight()) {
1294 return getCategoryVertex.right().value();
1296 GraphVertex newCategoryV = getCategoryVertex.left().value();
1297 status = moveCategoryEdge(elementV, newCategoryV);
1298 log.debug("Going to update the category of the resource from {} to {}. status is {}", categoryNameCurrent, newCategory, status);
1303 public <T extends ToscaElement> Either<List<T>, StorageOperationStatus> getElementCatalogData(ComponentTypeEnum componentType,
1304 List<ResourceTypeEnum> excludeTypes,
1305 boolean isHighestVersions) {
1306 Either<List<GraphVertex>, JanusGraphOperationStatus> listOfComponents;
1307 if (isHighestVersions) {
1308 listOfComponents = getListOfHighestComponents(componentType, excludeTypes, JsonParseFlagEnum.NoParse);
1310 listOfComponents = getListOfHighestAndAllCertifiedComponents(componentType, excludeTypes);
1312 if (listOfComponents.isRight() && listOfComponents.right().value() != JanusGraphOperationStatus.NOT_FOUND) {
1313 return Either.right(DaoStatusConverter.convertJanusGraphStatusToStorageStatus(listOfComponents.right().value()));
1315 List<T> result = new ArrayList<>();
1316 if (listOfComponents.isLeft()) {
1317 List<GraphVertex> highestAndAllCertified = listOfComponents.left().value();
1318 if (highestAndAllCertified != null && !highestAndAllCertified.isEmpty()) {
1319 for (GraphVertex vertexComponent : highestAndAllCertified) {
1320 Either<T, StorageOperationStatus> component = getLightComponent(vertexComponent, componentType,
1321 new ComponentParametersView(true));
1322 if (component.isRight()) {
1323 log.debug("Failed to fetch light element for {} error {}", vertexComponent.getUniqueId(), component.right().value());
1324 return Either.right(component.right().value());
1326 result.add(component.left().value());
1331 return Either.left(result);
1334 public Either<List<CatalogComponent>, StorageOperationStatus> getElementCatalogData(boolean isCatalog, List<ResourceTypeEnum> excludeTypes) {
1335 StopWatch stopWatch = new StopWatch();
1337 Map<String, CatalogComponent> existInCatalog = new HashMap<>();
1338 Either<Iterator<Vertex>, JanusGraphOperationStatus> verticesEither = janusGraphDao.getCatalogOrArchiveVertices(isCatalog);
1339 if (verticesEither.isRight()) {
1340 return Either.right(DaoStatusConverter.convertJanusGraphStatusToStorageStatus(verticesEither.right().value()));
1342 Iterator<Vertex> vertices = verticesEither.left().value();
1343 while (vertices.hasNext()) {
1344 handleCatalogComponent(existInCatalog, vertices.next(), excludeTypes);
1347 String timeToFetchElements = stopWatch.prettyPrint();
1348 log.info("time to fetch all catalog elements: {}", timeToFetchElements);
1349 return Either.left(existInCatalog.values().stream().collect(Collectors.toList()));
1352 private void handleCatalogComponent(Map<String, CatalogComponent> existInCatalog, Vertex vertex, List<ResourceTypeEnum> excludeTypes) {
1353 VertexProperty<Object> property = vertex.property(GraphPropertiesDictionary.METADATA.getProperty());
1354 String json = (String) property.value();
1355 Map<String, Object> metadatObj = JsonParserUtils.toMap(json);
1356 String uniqueId = (String) metadatObj.get(JsonPresentationFields.UNIQUE_ID.getPresentation());
1357 Boolean isDeleted = (Boolean) metadatObj.get(JsonPresentationFields.IS_DELETED.getPresentation());
1358 if (isAddToCatalog(excludeTypes, metadatObj) && (existInCatalog.get(uniqueId) == null && (isDeleted == null || !isDeleted.booleanValue()))) {
1359 CatalogComponent catalogComponent = new CatalogComponent();
1360 catalogComponent.setUniqueId(uniqueId);
1361 catalogComponent.setModel((String) metadatObj.get(JsonPresentationFields.MODEL.getPresentation()));
1363 .setComponentType(ComponentTypeEnum.valueOf((String) metadatObj.get(JsonPresentationFields.COMPONENT_TYPE.getPresentation())));
1364 catalogComponent.setVersion((String) metadatObj.get(JsonPresentationFields.VERSION.getPresentation()));
1365 catalogComponent.setName((String) metadatObj.get(JsonPresentationFields.NAME.getPresentation()));
1366 catalogComponent.setIcon((String) metadatObj.get(JsonPresentationFields.ICON.getPresentation()));
1367 catalogComponent.setLifecycleState((String) metadatObj.get(JsonPresentationFields.LIFECYCLE_STATE.getPresentation()));
1368 Object lastUpdateDate = metadatObj.get(JsonPresentationFields.LAST_UPDATE_DATE.getPresentation());
1369 catalogComponent.setLastUpdateDate((lastUpdateDate != null ? (Long) lastUpdateDate : 0L));
1370 catalogComponent.setDistributionStatus((String) metadatObj.get(JsonPresentationFields.DISTRIBUTION_STATUS.getPresentation()));
1371 catalogComponent.setDescription((String) metadatObj.get(JsonPresentationFields.DESCRIPTION.getPresentation()));
1372 catalogComponent.setTenant((String) metadatObj.get(JsonPresentationFields.TENANT.getPresentation()));
1373 catalogComponent.setSystemName((String) metadatObj.get(JsonPresentationFields.SYSTEM_NAME.getPresentation()));
1374 catalogComponent.setUuid((String) metadatObj.get(JsonPresentationFields.UUID.getPresentation()));
1375 catalogComponent.setInvariantUUID((String) metadatObj.get(JsonPresentationFields.INVARIANT_UUID.getPresentation()));
1376 catalogComponent.setIsHighestVersion((Boolean) metadatObj.get(JsonPresentationFields.HIGHEST_VERSION.getPresentation()));
1377 Iterator<Edge> edges = vertex.edges(Direction.IN, EdgeLabelEnum.STATE.name());
1378 if (edges.hasNext()) {
1380 .setLastUpdaterUserId((String) edges.next().outVertex().property(GraphPropertiesDictionary.USERID.getProperty()).value());
1382 Object resourceType = metadatObj.get(JsonPresentationFields.RESOURCE_TYPE.getPresentation());
1383 if (resourceType != null) {
1384 catalogComponent.setResourceType((String) resourceType);
1386 if (catalogComponent.getComponentType() == ComponentTypeEnum.SERVICE) {
1387 setServiceCategoryFromGraphV(vertex, catalogComponent);
1389 setResourceCategoryFromGraphV(vertex, catalogComponent);
1391 List<String> tags = (List<String>) metadatObj.get(JsonPresentationFields.TAGS.getPresentation());
1393 catalogComponent.setTags(tags);
1395 existInCatalog.put(uniqueId, catalogComponent);
1399 private boolean isAddToCatalog(List<ResourceTypeEnum> excludeTypes, Map<String, Object> metadatObj) {
1400 boolean isAddToCatalog = true;
1401 Object resourceTypeStr = metadatObj.get(JsonPresentationFields.RESOURCE_TYPE.getPresentation());
1402 if (resourceTypeStr != null) {
1403 ResourceTypeEnum resourceType = ResourceTypeEnum.getType((String) resourceTypeStr);
1404 if (!CollectionUtils.isEmpty(excludeTypes)) {
1405 Optional<ResourceTypeEnum> op = excludeTypes.stream().filter(rt -> rt == resourceType).findAny();
1406 if (op.isPresent()) {
1407 isAddToCatalog = false;
1411 return isAddToCatalog;
1414 public Either<List<GraphVertex>, JanusGraphOperationStatus> getListOfHighestComponents(ComponentTypeEnum componentType,
1415 List<ResourceTypeEnum> excludeTypes,
1416 JsonParseFlagEnum parseFlag) {
1417 Map<GraphPropertyEnum, Object> propertiesToMatch = new EnumMap<>(GraphPropertyEnum.class);
1418 Map<GraphPropertyEnum, Object> propertiesHasNotToMatch = new EnumMap<>(GraphPropertyEnum.class);
1419 propertiesToMatch.put(GraphPropertyEnum.COMPONENT_TYPE, componentType.name());
1420 propertiesToMatch.put(GraphPropertyEnum.IS_HIGHEST_VERSION, true);
1421 if (componentType == ComponentTypeEnum.RESOURCE) {
1422 propertiesToMatch.put(GraphPropertyEnum.IS_ABSTRACT, false);
1423 propertiesHasNotToMatch.put(GraphPropertyEnum.RESOURCE_TYPE, excludeTypes);
1425 propertiesHasNotToMatch.put(GraphPropertyEnum.IS_DELETED, true);
1426 propertiesHasNotToMatch.put(GraphPropertyEnum.IS_ARCHIVED, true); //US382674, US382683
1427 return janusGraphDao.getByCriteria(null, propertiesToMatch, propertiesHasNotToMatch, parseFlag);
1430 // highest + (certified && !highest)
1431 public Either<List<GraphVertex>, JanusGraphOperationStatus> getListOfHighestAndAllCertifiedComponents(ComponentTypeEnum componentType,
1432 List<ResourceTypeEnum> excludeTypes) {
1433 long startFetchAllStates = System.currentTimeMillis();
1434 Either<List<GraphVertex>, JanusGraphOperationStatus> highestNodes = getListOfHighestComponents(componentType, excludeTypes,
1435 JsonParseFlagEnum.ParseMetadata);
1436 Map<GraphPropertyEnum, Object> propertiesToMatchCertified = new EnumMap<>(GraphPropertyEnum.class);
1437 Map<GraphPropertyEnum, Object> propertiesHasNotToMatchCertified = new EnumMap<>(GraphPropertyEnum.class);
1438 propertiesToMatchCertified.put(GraphPropertyEnum.STATE, LifecycleStateEnum.CERTIFIED.name());
1439 propertiesToMatchCertified.put(GraphPropertyEnum.COMPONENT_TYPE, componentType.name());
1440 if (componentType == ComponentTypeEnum.RESOURCE) {
1441 propertiesToMatchCertified.put(GraphPropertyEnum.IS_ABSTRACT, false);
1442 propertiesHasNotToMatchCertified.put(GraphPropertyEnum.RESOURCE_TYPE, excludeTypes);
1444 propertiesHasNotToMatchCertified.put(GraphPropertyEnum.IS_DELETED, true);
1445 propertiesHasNotToMatchCertified.put(GraphPropertyEnum.IS_ARCHIVED, true); //US382674, US382683
1446 propertiesHasNotToMatchCertified.put(GraphPropertyEnum.IS_HIGHEST_VERSION, true);
1447 Either<List<GraphVertex>, JanusGraphOperationStatus> certifiedNotHighestNodes = janusGraphDao
1448 .getByCriteria(null, propertiesToMatchCertified, propertiesHasNotToMatchCertified, JsonParseFlagEnum.ParseMetadata);
1449 if (certifiedNotHighestNodes.isRight() && certifiedNotHighestNodes.right().value() != JanusGraphOperationStatus.NOT_FOUND) {
1450 return Either.right(certifiedNotHighestNodes.right().value());
1452 long endFetchAllStates = System.currentTimeMillis();
1453 List<GraphVertex> allNodes = new ArrayList<>();
1454 if (certifiedNotHighestNodes.isLeft()) {
1455 allNodes.addAll(certifiedNotHighestNodes.left().value());
1457 if (highestNodes.isLeft()) {
1458 allNodes.addAll(highestNodes.left().value());
1460 log.debug("Fetch catalog {}s all states from graph took {} ms", componentType, endFetchAllStates - startFetchAllStates);
1461 return Either.left(allNodes);
1464 protected Either<List<GraphVertex>, StorageOperationStatus> getAllComponentsMarkedForDeletion(ComponentTypeEnum componentType) {
1465 // get all components marked for delete
1466 Map<GraphPropertyEnum, Object> props = new EnumMap<>(GraphPropertyEnum.class);
1467 props.put(GraphPropertyEnum.IS_DELETED, true);
1468 props.put(GraphPropertyEnum.COMPONENT_TYPE, componentType.name());
1469 Either<List<GraphVertex>, JanusGraphOperationStatus> componentsToDelete = janusGraphDao.getByCriteria(null, props, JsonParseFlagEnum.NoParse);
1470 if (componentsToDelete.isRight()) {
1471 JanusGraphOperationStatus error = componentsToDelete.right().value();
1472 if (error.equals(JanusGraphOperationStatus.NOT_FOUND)) {
1473 log.trace("no components to delete");
1474 return Either.left(new ArrayList<>());
1476 log.info("failed to find components to delete. error : {}", error.name());
1477 return Either.right(DaoStatusConverter.convertJanusGraphStatusToStorageStatus(error));
1480 return Either.left(componentsToDelete.left().value());
1483 protected JanusGraphOperationStatus setAdditionalInformationFromGraph(GraphVertex componentV, ToscaElement toscaElement) {
1484 Either<Map<String, AdditionalInfoParameterDataDefinition>, JanusGraphOperationStatus> result = getDataFromGraph(componentV,
1485 EdgeLabelEnum.ADDITIONAL_INFORMATION);
1486 if (result.isLeft()) {
1487 toscaElement.setAdditionalInformation(result.left().value());
1489 if (result.right().value() != JanusGraphOperationStatus.NOT_FOUND) {
1490 return result.right().value();
1493 return JanusGraphOperationStatus.OK;
1496 // --------------------------------------------
1497 public abstract <T extends ToscaElement> Either<T, StorageOperationStatus> getToscaElement(String uniqueId,
1498 ComponentParametersView componentParametersView);
1500 public abstract <T extends ToscaElement> Either<T, StorageOperationStatus> getToscaElement(GraphVertex toscaElementVertex,
1501 ComponentParametersView componentParametersView);
1503 public abstract <T extends ToscaElement> Either<T, StorageOperationStatus> deleteToscaElement(GraphVertex toscaElementVertex);
1505 public abstract <T extends ToscaElement> Either<T, StorageOperationStatus> createToscaElement(ToscaElement toscaElement);
1507 protected abstract <T extends ToscaElement> JanusGraphOperationStatus setCategoriesFromGraph(GraphVertex vertexComponent, T toscaElement);
1509 protected abstract <T extends ToscaElement> JanusGraphOperationStatus setCapabilitiesFromGraph(GraphVertex componentV, T toscaElement);
1511 protected abstract <T extends ToscaElement> JanusGraphOperationStatus setRequirementsFromGraph(GraphVertex componentV, T toscaElement);
1513 protected abstract <T extends ToscaElement> StorageOperationStatus validateCategories(T toscaElementToUpdate, GraphVertex elementV);
1515 protected abstract <T extends ToscaElement> StorageOperationStatus updateDerived(T toscaElementToUpdate, GraphVertex updateElementV);
1517 public abstract <T extends ToscaElement> void fillToscaElementVertexData(GraphVertex elementV, T toscaElementToUpdate, JsonParseFlagEnum flag);