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.operations.impl;
22 import static org.openecomp.sdc.common.log.enums.EcompLoggerErrorCode.BUSINESS_PROCESS_ERROR;
24 import com.fasterxml.jackson.core.ObjectCodec;
25 import com.fasterxml.jackson.databind.DeserializationContext;
26 import com.fasterxml.jackson.databind.JsonNode;
27 import com.google.common.collect.Maps;
28 import com.google.gson.JsonArray;
29 import com.google.gson.JsonDeserializationContext;
30 import com.google.gson.JsonDeserializer;
31 import com.google.gson.JsonElement;
32 import com.google.gson.JsonObject;
33 import com.google.gson.JsonParseException;
34 import com.google.gson.JsonParser;
35 import com.google.gson.JsonSerializationContext;
36 import com.google.gson.JsonSerializer;
37 import fj.data.Either;
38 import java.io.IOException;
39 import java.lang.reflect.Type;
40 import java.util.ArrayList;
41 import java.util.Collection;
42 import java.util.Collections;
43 import java.util.HashMap;
44 import java.util.List;
46 import java.util.Map.Entry;
48 import java.util.StringJoiner;
49 import java.util.function.Consumer;
50 import java.util.regex.Matcher;
51 import java.util.regex.Pattern;
52 import java.util.stream.Collectors;
53 import org.apache.commons.collections.CollectionUtils;
54 import org.apache.commons.collections.MapUtils;
55 import org.apache.commons.lang3.StringUtils;
56 import org.apache.commons.lang3.tuple.ImmutablePair;
57 import org.apache.tinkerpop.gremlin.structure.Edge;
58 import org.apache.tinkerpop.gremlin.structure.Vertex;
59 import org.apache.tinkerpop.gremlin.structure.VertexProperty;
60 import org.janusgraph.core.JanusGraph;
61 import org.janusgraph.core.JanusGraphVertex;
62 import org.janusgraph.core.JanusGraphVertexProperty;
63 import org.openecomp.sdc.be.config.BeEcompErrorManager;
64 import org.openecomp.sdc.be.config.BeEcompErrorManager.ErrorSeverity;
65 import org.openecomp.sdc.be.dao.graph.GraphElementFactory;
66 import org.openecomp.sdc.be.dao.graph.datatype.GraphEdge;
67 import org.openecomp.sdc.be.dao.graph.datatype.GraphElementTypeEnum;
68 import org.openecomp.sdc.be.dao.graph.datatype.GraphNode;
69 import org.openecomp.sdc.be.dao.graph.datatype.GraphRelation;
70 import org.openecomp.sdc.be.dao.janusgraph.HealingJanusGraphGenericDao;
71 import org.openecomp.sdc.be.dao.janusgraph.JanusGraphGenericDao;
72 import org.openecomp.sdc.be.dao.janusgraph.JanusGraphOperationStatus;
73 import org.openecomp.sdc.be.dao.neo4j.GraphEdgeLabels;
74 import org.openecomp.sdc.be.dao.neo4j.GraphPropertiesDictionary;
75 import org.openecomp.sdc.be.datatypes.elements.PropertyDataDefinition;
76 import org.openecomp.sdc.be.datatypes.elements.PropertyRule;
77 import org.openecomp.sdc.be.datatypes.elements.SchemaDefinition;
78 import org.openecomp.sdc.be.datatypes.enums.NodeTypeEnum;
79 import org.openecomp.sdc.be.model.Component;
80 import org.openecomp.sdc.be.model.ComponentInstanceProperty;
81 import org.openecomp.sdc.be.model.DataTypeDefinition;
82 import org.openecomp.sdc.be.model.IComplexDefaultValue;
83 import org.openecomp.sdc.be.model.PropertyConstraint;
84 import org.openecomp.sdc.be.model.PropertyDefinition;
85 import org.openecomp.sdc.be.model.operations.api.DerivedFromOperation;
86 import org.openecomp.sdc.be.model.operations.api.IPropertyOperation;
87 import org.openecomp.sdc.be.model.operations.api.StorageOperationStatus;
88 import org.openecomp.sdc.be.model.tosca.ToscaPropertyType;
89 import org.openecomp.sdc.be.datatypes.enums.ConstraintType;
90 import org.openecomp.sdc.be.model.tosca.constraints.GreaterOrEqualConstraint;
91 import org.openecomp.sdc.be.model.tosca.constraints.GreaterThanConstraint;
92 import org.openecomp.sdc.be.model.tosca.constraints.InRangeConstraint;
93 import org.openecomp.sdc.be.model.tosca.constraints.LessOrEqualConstraint;
94 import org.openecomp.sdc.be.model.tosca.constraints.LessThanConstraint;
95 import org.openecomp.sdc.be.model.tosca.constraints.MinLengthConstraint;
96 import org.openecomp.sdc.be.model.tosca.constraints.ValidValuesConstraint;
97 import org.openecomp.sdc.be.model.tosca.converters.PropertyValueConverter;
98 import org.openecomp.sdc.be.model.validation.ToscaFunctionValidator;
99 import org.openecomp.sdc.be.resources.data.ComponentInstanceData;
100 import org.openecomp.sdc.be.resources.data.DataTypeData;
101 import org.openecomp.sdc.be.resources.data.ModelData;
102 import org.openecomp.sdc.be.resources.data.PropertyData;
103 import org.openecomp.sdc.be.resources.data.PropertyValueData;
104 import org.openecomp.sdc.be.resources.data.ResourceMetadataData;
105 import org.openecomp.sdc.be.resources.data.UniqueIdData;
106 import org.openecomp.sdc.common.log.wrappers.Logger;
107 import org.springframework.beans.factory.annotation.Autowired;
109 @org.springframework.stereotype.Component("property-operation")
110 public class PropertyOperation extends AbstractOperation implements IPropertyOperation {
112 private static final String AFTER_RETRIEVING_DERIVED_FROM_NODE_OF_STATUS_IS = "After retrieving DERIVED_FROM node of {}. status is {}";
113 private static final String FAILED_TO_FETCH_PROPERTIES_OF_DATA_TYPE = "Failed to fetch properties of data type {}";
114 private static final String DATA_TYPE_CANNOT_BE_FOUND_IN_GRAPH_STATUS_IS = "Data type {} cannot be found in graph. status is {}";
115 private static final String GOING_TO_EXECUTE_COMMIT_ON_GRAPH = "Going to execute commit on graph.";
116 private static final String GOING_TO_EXECUTE_ROLLBACK_ON_GRAPH = "Going to execute rollback on graph.";
117 private static final String FAILED_TO_ASSOCIATE_RESOURCE_TO_PROPERTY_IN_GRAPH_STATUS_IS = "Failed to associate resource {} to property {} in graph. status is {}";
118 private static final String AFTER_ADDING_PROPERTY_TO_GRAPH = "After adding property to graph {}";
119 private static final String BEFORE_ADDING_PROPERTY_TO_GRAPH = "Before adding property to graph {}";
120 private static final String THE_VALUE_OF_PROPERTY_FROM_TYPE_IS_INVALID = "The value {} of property from type {} is invalid";
121 private static final String PROPERTY = "Property";
122 private static final String UPDATE_DATA_TYPE = "UpdateDataType";
123 private static final Logger log = Logger.getLogger(PropertyOperation.class.getName());
124 private final DerivedFromOperation derivedFromOperation;
125 private ToscaFunctionValidator toscaFunctionValidator;
126 private DataTypeOperation dataTypeOperation;
129 public PropertyOperation(final HealingJanusGraphGenericDao janusGraphGenericDao, final DerivedFromOperation derivedFromOperation) {
130 this.janusGraphGenericDao = janusGraphGenericDao;
131 this.derivedFromOperation = derivedFromOperation;
135 public void setToscaFunctionValidator(final ToscaFunctionValidator toscaFunctionValidator) {
136 this.toscaFunctionValidator = toscaFunctionValidator;
139 //circular dependency DataTypeOperation->ModelOperation->ModelElementOperation->PropertyOperation
141 public void setDataTypeOperation(DataTypeOperation dataTypeOperation) {
142 this.dataTypeOperation = dataTypeOperation;
145 public PropertyDefinition convertPropertyDataToPropertyDefinition(PropertyData propertyDataResult, String propertyName, String resourceId) {
146 log.debug("The object returned after create property is {}", propertyDataResult);
147 PropertyDefinition propertyDefResult = new PropertyDefinition(propertyDataResult.getPropertyDataDefinition());
148 propertyDefResult.setConstraints(convertConstraints(propertyDataResult.getConstraints()));
149 propertyDefResult.setName(propertyName);
150 return propertyDefResult;
153 public Either<PropertyData, StorageOperationStatus> addProperty(String propertyName, PropertyDefinition propertyDefinition, String resourceId) {
154 Either<PropertyData, JanusGraphOperationStatus> either = addPropertyToGraph(propertyName, propertyDefinition, resourceId);
155 if (either.isRight()) {
156 StorageOperationStatus storageStatus = DaoStatusConverter.convertJanusGraphStatusToStorageStatus(either.right().value());
157 return Either.right(storageStatus);
159 return Either.left(either.left().value());
163 * @param propertyDefinition
167 public StorageOperationStatus validateAndUpdateProperty(IComplexDefaultValue propertyDefinition, Map<String, DataTypeDefinition> dataTypes) {
168 log.trace("Going to validate property type and value. {}", propertyDefinition);
169 String propertyType = propertyDefinition.getType();
170 String value = propertyDefinition.getDefaultValue();
171 ToscaPropertyType type = getType(propertyType);
173 DataTypeDefinition dataTypeDefinition = dataTypes.get(propertyType);
174 if (dataTypeDefinition == null) {
175 log.debug("The type {} of property cannot be found.", propertyType);
176 return StorageOperationStatus.INVALID_TYPE;
178 return validateAndUpdateComplexValue(propertyDefinition, propertyType, value, dataTypeDefinition, dataTypes);
180 String innerType = null;
181 Either<String, JanusGraphOperationStatus> checkInnerType = getInnerType(type, propertyDefinition::getSchema);
182 if (checkInnerType.isRight()) {
183 return StorageOperationStatus.INVALID_TYPE;
185 innerType = checkInnerType.left().value();
186 log.trace("After validating property type {}", propertyType);
187 boolean isValidProperty = isValidValue(type, value, innerType, dataTypes);
188 if (!isValidProperty) {
189 log.info(THE_VALUE_OF_PROPERTY_FROM_TYPE_IS_INVALID, value, type);
190 return StorageOperationStatus.INVALID_VALUE;
192 PropertyValueConverter converter = type.getConverter();
193 if (isEmptyValue(value)) {
194 log.debug("Default value was not sent for property {}. Set default value to {}", propertyDefinition.getName(), EMPTY_VALUE);
195 propertyDefinition.setDefaultValue(EMPTY_VALUE);
196 } else if (!isEmptyValue(value)) {
197 String convertedValue = converter.convert(value, innerType, dataTypes);
198 propertyDefinition.setDefaultValue(convertedValue);
200 return StorageOperationStatus.OK;
203 public Either<PropertyData, JanusGraphOperationStatus> addPropertyToGraph(String propertyName, PropertyDefinition propertyDefinition,
205 ResourceMetadataData resourceData = new ResourceMetadataData();
206 resourceData.getMetadataDataDefinition().setUniqueId(resourceId);
207 List<PropertyConstraint> constraints = propertyDefinition.getConstraints();
208 propertyDefinition.setUniqueId(UniqueIdBuilder.buildComponentPropertyUniqueId(resourceId, propertyName));
209 PropertyData propertyData = new PropertyData(propertyDefinition, convertConstraintsToString(constraints));
210 log.debug(BEFORE_ADDING_PROPERTY_TO_GRAPH, propertyData);
211 Either<PropertyData, JanusGraphOperationStatus> createNodeResult = janusGraphGenericDao.createNode(propertyData, PropertyData.class);
212 log.debug(AFTER_ADDING_PROPERTY_TO_GRAPH, propertyData);
213 if (createNodeResult.isRight()) {
214 JanusGraphOperationStatus operationStatus = createNodeResult.right().value();
215 log.error("Failed to add property {} to graph. status is {}", propertyName, operationStatus);
216 return Either.right(operationStatus);
218 Map<String, Object> props = new HashMap<>();
219 props.put(GraphPropertiesDictionary.NAME.getProperty(), propertyName);
220 Either<GraphRelation, JanusGraphOperationStatus> createRelResult = janusGraphGenericDao
221 .createRelation(resourceData, propertyData, GraphEdgeLabels.PROPERTY, props);
222 if (createRelResult.isRight()) {
223 JanusGraphOperationStatus operationStatus = createNodeResult.right().value();
224 log.error(FAILED_TO_ASSOCIATE_RESOURCE_TO_PROPERTY_IN_GRAPH_STATUS_IS, resourceId, propertyName, operationStatus);
225 return Either.right(operationStatus);
227 return Either.left(createNodeResult.left().value());
230 public JanusGraphOperationStatus addPropertyToGraphByVertex(JanusGraphVertex metadataVertex, String propertyName,
231 PropertyDefinition propertyDefinition, String resourceId) {
232 List<PropertyConstraint> constraints = propertyDefinition.getConstraints();
233 propertyDefinition.setUniqueId(UniqueIdBuilder.buildComponentPropertyUniqueId(resourceId, propertyName));
234 PropertyData propertyData = new PropertyData(propertyDefinition, convertConstraintsToString(constraints));
235 log.debug(BEFORE_ADDING_PROPERTY_TO_GRAPH, propertyData);
236 Either<JanusGraphVertex, JanusGraphOperationStatus> createNodeResult = janusGraphGenericDao.createNode(propertyData);
237 log.debug(AFTER_ADDING_PROPERTY_TO_GRAPH, propertyData);
238 if (createNodeResult.isRight()) {
239 JanusGraphOperationStatus operationStatus = createNodeResult.right().value();
240 log.error("Failed to add property {} to graph. status is ", propertyName, operationStatus);
241 return operationStatus;
243 Map<String, Object> props = new HashMap<>();
244 props.put(GraphPropertiesDictionary.NAME.getProperty(), propertyName);
245 JanusGraphVertex propertyVertex = createNodeResult.left().value();
246 JanusGraphOperationStatus createRelResult = janusGraphGenericDao.createEdge(metadataVertex, propertyVertex, GraphEdgeLabels.PROPERTY, props);
247 if (!createRelResult.equals(JanusGraphOperationStatus.OK)) {
248 log.error(FAILED_TO_ASSOCIATE_RESOURCE_TO_PROPERTY_IN_GRAPH_STATUS_IS, resourceId, propertyName, createRelResult);
249 return createRelResult;
251 return createRelResult;
254 public JanusGraphGenericDao getJanusGraphGenericDao() {
255 return janusGraphGenericDao;
261 * @param janusGraphGenericDao
263 public void setJanusGraphGenericDao(HealingJanusGraphGenericDao janusGraphGenericDao) {
264 this.janusGraphGenericDao = janusGraphGenericDao;
267 public Either<PropertyData, JanusGraphOperationStatus> deletePropertyFromGraph(String propertyId) {
268 log.debug("Before deleting property from graph {}", propertyId);
269 return janusGraphGenericDao.deleteNode(UniqueIdBuilder.getKeyByNodeType(NodeTypeEnum.Property), propertyId, PropertyData.class);
272 public Either<PropertyData, StorageOperationStatus> updateProperty(String propertyId, PropertyDefinition newPropertyDefinition,
273 Map<String, DataTypeDefinition> dataTypes) {
274 StorageOperationStatus validateAndUpdateProperty = validateAndUpdateProperty(newPropertyDefinition, dataTypes);
275 if (validateAndUpdateProperty != StorageOperationStatus.OK) {
276 return Either.right(validateAndUpdateProperty);
278 Either<PropertyData, JanusGraphOperationStatus> either = updatePropertyFromGraph(propertyId, newPropertyDefinition);
279 if (either.isRight()) {
280 StorageOperationStatus storageStatus = DaoStatusConverter.convertJanusGraphStatusToStorageStatus(either.right().value());
281 return Either.right(storageStatus);
283 return Either.left(either.left().value());
286 public Either<PropertyData, JanusGraphOperationStatus> updatePropertyFromGraph(String propertyId, PropertyDefinition propertyDefinition) {
287 if (log.isDebugEnabled()) {
288 log.debug("Before updating property on graph {}", propertyId);
290 // get the original property data
291 Either<PropertyData, JanusGraphOperationStatus> statusProperty = janusGraphGenericDao
292 .getNode(UniqueIdBuilder.getKeyByNodeType(NodeTypeEnum.Property), propertyId, PropertyData.class);
293 if (statusProperty.isRight()) {
294 log.debug("Problem while get property with id {}. Reason - {}", propertyId, statusProperty.right().value().name());
295 return Either.right(statusProperty.right().value());
297 PropertyData orgPropertyData = statusProperty.left().value();
298 PropertyDataDefinition orgPropertyDataDefinition = orgPropertyData.getPropertyDataDefinition();
299 // create new property data to update
300 PropertyData newPropertyData = new PropertyData();
301 newPropertyData.setPropertyDataDefinition(propertyDefinition);
302 PropertyDataDefinition newPropertyDataDefinition = newPropertyData.getPropertyDataDefinition();
303 // update the original property data with new values
304 if (orgPropertyDataDefinition.getDefaultValue() == null) {
305 orgPropertyDataDefinition.setDefaultValue(newPropertyDataDefinition.getDefaultValue());
307 if (!orgPropertyDataDefinition.getDefaultValue().equals(newPropertyDataDefinition.getDefaultValue())) {
308 orgPropertyDataDefinition.setDefaultValue(newPropertyDataDefinition.getDefaultValue());
311 if (orgPropertyDataDefinition.getDescription() == null) {
312 orgPropertyDataDefinition.setDescription(newPropertyDataDefinition.getDescription());
314 if (!orgPropertyDataDefinition.getDescription().equals(newPropertyDataDefinition.getDescription())) {
315 orgPropertyDataDefinition.setDescription(newPropertyDataDefinition.getDescription());
318 if (!orgPropertyDataDefinition.getType().equals(newPropertyDataDefinition.getType())) {
319 orgPropertyDataDefinition.setType(newPropertyDataDefinition.getType());
321 if (newPropertyData.getConstraints() != null) {
322 orgPropertyData.setConstraints(newPropertyData.getConstraints());
324 orgPropertyDataDefinition.setSchema(newPropertyDataDefinition.getSchema());
325 return janusGraphGenericDao.updateNode(orgPropertyData, PropertyData.class);
328 public Either<PropertyData, JanusGraphOperationStatus> addPropertyToNodeType(String propertyName, PropertyDefinition propertyDefinition,
329 NodeTypeEnum nodeType, String uniqueId) {
330 List<PropertyConstraint> constraints = propertyDefinition.getConstraints();
331 propertyDefinition.setUniqueId(UniqueIdBuilder.buildPropertyUniqueId(uniqueId, propertyName));
332 PropertyData propertyData = new PropertyData(propertyDefinition, convertConstraintsToString(constraints));
333 if (log.isDebugEnabled()) {
334 log.debug(BEFORE_ADDING_PROPERTY_TO_GRAPH, propertyData);
336 Either<PropertyData, JanusGraphOperationStatus> createNodeResult = janusGraphGenericDao.createNode(propertyData, PropertyData.class);
337 if (log.isDebugEnabled()) {
338 log.debug(AFTER_ADDING_PROPERTY_TO_GRAPH, propertyData);
340 if (createNodeResult.isRight()) {
341 JanusGraphOperationStatus operationStatus = createNodeResult.right().value();
342 log.error("Failed to add property {} to graph. status is {}", propertyName, operationStatus);
343 return Either.right(operationStatus);
345 Map<String, Object> props = new HashMap<>();
346 props.put(GraphPropertiesDictionary.NAME.getProperty(), propertyName);
347 UniqueIdData uniqueIdData = new UniqueIdData(nodeType, uniqueId);
348 log.debug("Before associating {} to property {}", uniqueIdData, propertyName);
349 Either<GraphRelation, JanusGraphOperationStatus> createRelResult = janusGraphGenericDao
350 .createRelation(uniqueIdData, propertyData, GraphEdgeLabels.PROPERTY, props);
351 if (createRelResult.isRight()) {
352 JanusGraphOperationStatus operationStatus = createNodeResult.right().value();
353 log.error(FAILED_TO_ASSOCIATE_RESOURCE_TO_PROPERTY_IN_GRAPH_STATUS_IS, uniqueId, propertyName, operationStatus);
354 return Either.right(operationStatus);
356 return Either.left(createNodeResult.left().value());
359 public Either<Map<String, PropertyDefinition>, JanusGraphOperationStatus> findPropertiesOfNode(NodeTypeEnum nodeType, String uniqueId) {
360 Map<String, PropertyDefinition> resourceProps = new HashMap<>();
361 Either<List<ImmutablePair<PropertyData, GraphEdge>>, JanusGraphOperationStatus> childrenNodes = janusGraphGenericDao
362 .getChildrenNodes(UniqueIdBuilder.getKeyByNodeType(nodeType), uniqueId, GraphEdgeLabels.PROPERTY, NodeTypeEnum.Property,
364 if (childrenNodes.isRight()) {
365 JanusGraphOperationStatus operationStatus = childrenNodes.right().value();
366 return Either.right(operationStatus);
368 List<ImmutablePair<PropertyData, GraphEdge>> values = childrenNodes.left().value();
369 if (values != null) {
370 for (ImmutablePair<PropertyData, GraphEdge> immutablePair : values) {
371 GraphEdge edge = immutablePair.getValue();
372 String propertyName = (String) edge.getProperties().get(GraphPropertiesDictionary.NAME.getProperty());
373 log.debug("Property {} is associated to node {}", propertyName, uniqueId);
374 PropertyData propertyData = immutablePair.getKey();
375 PropertyDefinition propertyDefinition = this.convertPropertyDataToPropertyDefinition(propertyData, propertyName, uniqueId);
376 resourceProps.put(propertyName, propertyDefinition);
379 log.debug("The properties associated to node {} are {}", uniqueId, resourceProps);
380 return Either.left(resourceProps);
383 public Either<Map<String, PropertyDefinition>, StorageOperationStatus> deletePropertiesAssociatedToNode(NodeTypeEnum nodeType, String uniqueId) {
384 return deleteAllPropertiesAssociatedToNode(nodeType, uniqueId).right()
385 .bind(err -> err == StorageOperationStatus.OK ? Either.left(Collections.emptyMap()) : Either.right(err));
388 public Either<Map<String, PropertyData>, JanusGraphOperationStatus> mergePropertiesAssociatedToNode(NodeTypeEnum nodeType, String uniqueId,
389 Map<String, PropertyDefinition> newProperties) {
390 Either<Map<String, PropertyDefinition>, JanusGraphOperationStatus> oldPropertiesRes = findPropertiesOfNode(nodeType, uniqueId);
391 Map<String, PropertyDefinition> reallyNewProperties;
392 Map<String, PropertyData> unchangedPropsData;
393 if (oldPropertiesRes.isRight()) {
394 JanusGraphOperationStatus err = oldPropertiesRes.right().value();
395 if (err == JanusGraphOperationStatus.NOT_FOUND) {
396 reallyNewProperties = newProperties;
397 unchangedPropsData = Collections.emptyMap();
399 return Either.right(err);
402 Map<String, PropertyDefinition> oldProperties = oldPropertiesRes.left().value();
403 reallyNewProperties = collectReallyNewProperties(newProperties, oldProperties);
404 for (Entry<String, PropertyDefinition> oldEntry : oldProperties.entrySet()) {
405 String key = oldEntry.getKey();
406 PropertyDefinition newPropDef = newProperties != null ? newProperties.get(key) : null;
407 PropertyDefinition oldPropDef = oldEntry.getValue();
408 JanusGraphOperationStatus status = updateOldProperty(newPropDef, oldPropDef);
409 if (status != JanusGraphOperationStatus.OK) {
410 return Either.right(status);
413 unchangedPropsData = oldProperties.entrySet().stream()
414 .collect(Collectors.toMap(Entry::getKey, e -> new PropertyData(e.getValue(), null)));
416 // add other properties
417 return addPropertiesToElementType(nodeType, uniqueId, reallyNewProperties, unchangedPropsData);
421 * @param newProperties
422 * @param oldProperties
425 private Map<String, PropertyDefinition> collectReallyNewProperties(Map<String, PropertyDefinition> newProperties,
426 Map<String, PropertyDefinition> oldProperties) {
427 return newProperties != null ? newProperties.entrySet().stream().filter(entry -> !oldProperties.containsKey(entry.getKey()))
428 .collect(Collectors.toMap(Entry::getKey, Entry::getValue)) : null;
435 private JanusGraphOperationStatus updateOldProperty(PropertyDefinition newPropDef, PropertyDefinition oldPropDef) {
436 if (!isUpdateAllowed(newPropDef, oldPropDef)) {
437 return JanusGraphOperationStatus.MATCH_NOT_FOUND;
439 if (isUpdateRequired(newPropDef, oldPropDef)) {
440 modifyOldPropByNewOne(newPropDef, oldPropDef);
441 List<PropertyConstraint> constraints = oldPropDef.getConstraints();
442 PropertyData node = new PropertyData(oldPropDef, convertConstraintsToString(constraints));
443 Either<PropertyData, JanusGraphOperationStatus> updateResult = janusGraphGenericDao.updateNode(node, PropertyData.class);
444 if (updateResult.isRight()) {
445 return updateResult.right().value();
448 return JanusGraphOperationStatus.OK;
455 private boolean isUpdateAllowed(PropertyDefinition newPropDef, PropertyDefinition oldPropDef) {
456 if (newPropDef == null) {
457 log.error("#mergePropertiesAssociatedToNode - Failed due attempt to delete the property with id {}", oldPropDef.getUniqueId());
460 // If the property type is missing it's something that we could want to fix
461 if (oldPropDef.getType() != null && !oldPropDef.getType().equals(newPropDef.getType())) {
462 log.error("#mergePropertiesAssociatedToNode - Failed due attempt to change type of the property with id {}", oldPropDef.getUniqueId());
469 * Update only fields which modification is permitted.
474 private void modifyOldPropByNewOne(PropertyDefinition newPropDef, PropertyDefinition oldPropDef) {
475 oldPropDef.setDefaultValue(newPropDef.getDefaultValue());
476 oldPropDef.setDescription(newPropDef.getDescription());
477 oldPropDef.setRequired(newPropDef.isRequired());
478 // Type is updated to fix possible null type issue in janusGraph DB
479 oldPropDef.setType(newPropDef.getType());
482 private boolean isUpdateRequired(PropertyDefinition newPropDef, PropertyDefinition oldPropDef) {
483 return !StringUtils.equals(oldPropDef.getDefaultValue(), newPropDef.getDefaultValue()) || !StringUtils
484 .equals(oldPropDef.getDescription(), newPropDef.getDescription()) || oldPropDef.isRequired() != newPropDef.isRequired();
488 * Adds newProperties and returns in case of success (left part of Either) map of all properties i. e. added ones and contained in
493 * @param newProperties
494 * @param unchangedPropsData
497 private Either<Map<String, PropertyData>, JanusGraphOperationStatus> addPropertiesToElementType(NodeTypeEnum nodeType, String uniqueId,
498 Map<String, PropertyDefinition> newProperties,
499 Map<String, PropertyData> unchangedPropsData) {
500 return addPropertiesToElementType(uniqueId, nodeType, newProperties).left().map(m -> {
501 m.putAll(unchangedPropsData);
506 public Either<Map<String, PropertyDefinition>, StorageOperationStatus> deleteAllPropertiesAssociatedToNode(NodeTypeEnum nodeType,
508 Either<Map<String, PropertyDefinition>, JanusGraphOperationStatus> propertiesOfNodeRes = findPropertiesOfNode(nodeType, uniqueId);
509 if (propertiesOfNodeRes.isRight()) {
510 JanusGraphOperationStatus status = propertiesOfNodeRes.right().value();
511 if (status == JanusGraphOperationStatus.NOT_FOUND) {
512 return Either.right(StorageOperationStatus.OK);
514 return Either.right(DaoStatusConverter.convertJanusGraphStatusToStorageStatus(status));
516 Map<String, PropertyDefinition> value = propertiesOfNodeRes.left().value();
517 for (PropertyDefinition propertyDefinition : value.values()) {
518 String propertyUid = propertyDefinition.getUniqueId();
519 Either<PropertyData, JanusGraphOperationStatus> deletePropertyRes = deletePropertyFromGraph(propertyUid);
520 if (deletePropertyRes.isRight()) {
521 log.error("Failed to delete property with id {}", propertyUid);
522 JanusGraphOperationStatus status = deletePropertyRes.right().value();
523 if (status == JanusGraphOperationStatus.NOT_FOUND) {
524 status = JanusGraphOperationStatus.INVALID_ID;
526 return Either.right(DaoStatusConverter.convertJanusGraphStatusToStorageStatus(status));
529 log.debug("The properties deleted from node {} are {}", uniqueId, value);
530 return Either.left(value);
534 * Checks existence of a property with the same name belonging to the same resource or existence of property with the same name and different type
535 * (including derived from hierarchy)
539 * @param propertyName
540 * @param propertyType
543 public boolean isPropertyExist(List<PropertyDefinition> properties, String resourceUid, String propertyName, String propertyType) {
544 boolean result = false;
545 if (!CollectionUtils.isEmpty(properties)) {
546 for (PropertyDefinition propertyDefinition : properties) {
547 if (propertyDefinition.getName().equals(propertyName) && (propertyDefinition.getParentUniqueId().equals(resourceUid)
548 || !propertyDefinition.getType().equals(propertyType))) {
557 public ImmutablePair<String, Boolean> validateAndUpdateRules(String propertyType, List<PropertyRule> rules, String innerType,
558 Map<String, DataTypeDefinition> dataTypes, boolean isValidate) {
559 if (rules == null || rules.isEmpty()) {
560 return new ImmutablePair<>(null, true);
562 for (PropertyRule rule : rules) {
563 String value = rule.getValue();
564 Either<Object, Boolean> updateResult = validateAndUpdatePropertyValue(propertyType, value, isValidate, innerType, dataTypes);
565 if (updateResult.isRight()) {
566 Boolean status = updateResult.right().value();
568 return new ImmutablePair<>(value, status);
571 String newValue = null;
572 Object object = updateResult.left().value();
573 if (object != null) {
574 newValue = object.toString();
576 rule.setValue(newValue);
579 return new ImmutablePair<>(null, true);
582 public void addRulesToNewPropertyValue(PropertyValueData propertyValueData, ComponentInstanceProperty resourceInstanceProperty,
583 String resourceInstanceId) {
584 List<PropertyRule> rules = resourceInstanceProperty.getRules();
586 PropertyRule propertyRule = buildRuleFromPath(propertyValueData, resourceInstanceProperty, resourceInstanceId);
587 rules = new ArrayList<>();
588 rules.add(propertyRule);
590 rules = sortRules(rules);
592 propertyValueData.setRules(rules);
595 private PropertyRule buildRuleFromPath(PropertyValueData propertyValueData, ComponentInstanceProperty resourceInstanceProperty,
596 String resourceInstanceId) {
597 List<String> path = resourceInstanceProperty.getPath();
598 // FOR BC. Since old Property values on VFC/VF does not have rules on
602 // Update could be done on one level only, thus we can use this
604 // operation to avoid migration.
605 if (path == null || path.isEmpty()) {
606 path = new ArrayList<>();
607 path.add(resourceInstanceId);
609 PropertyRule propertyRule = new PropertyRule();
610 propertyRule.setRule(path);
611 propertyRule.setValue(propertyValueData.getValue());
615 private List<PropertyRule> sortRules(List<PropertyRule> rules) {
616 // TODO: sort the rules by size and binary representation.
618 // (x, y, .+) --> 110 6 priority 1
620 // (x, .+, z) --> 101 5 priority 2
624 public ImmutablePair<JanusGraphOperationStatus, String> findPropertyValue(String resourceInstanceId, String propertyId) {
625 log.debug("Going to check whether the property {} already added to resource instance {}", propertyId, resourceInstanceId);
626 Either<List<ComponentInstanceProperty>, JanusGraphOperationStatus> getAllRes = this
627 .getAllPropertiesOfResourceInstanceOnlyPropertyDefId(resourceInstanceId);
628 if (getAllRes.isRight()) {
629 JanusGraphOperationStatus status = getAllRes.right().value();
630 log.trace("After fetching all properties of resource instance {}. Status is {}", resourceInstanceId, status);
631 return new ImmutablePair<>(status, null);
633 List<ComponentInstanceProperty> list = getAllRes.left().value();
635 for (ComponentInstanceProperty instanceProperty : list) {
636 String propertyUniqueId = instanceProperty.getUniqueId();
637 String valueUniqueUid = instanceProperty.getValueUniqueUid();
638 log.trace("Go over property {} under resource instance {}. valueUniqueId = {}", propertyUniqueId, resourceInstanceId, valueUniqueUid);
639 if (propertyId.equals(propertyUniqueId) && valueUniqueUid != null) {
640 log.debug("The property {} already created under resource instance {}", propertyId, resourceInstanceId);
641 return new ImmutablePair<>(JanusGraphOperationStatus.ALREADY_EXIST, valueUniqueUid);
645 return new ImmutablePair<>(JanusGraphOperationStatus.NOT_FOUND, null);
648 public void updateRulesInPropertyValue(PropertyValueData propertyValueData, ComponentInstanceProperty resourceInstanceProperty,
649 String resourceInstanceId) {
650 List<PropertyRule> currentRules = propertyValueData.getRules();
651 List<PropertyRule> rules = resourceInstanceProperty.getRules();
652 // if rules are not supported.
654 PropertyRule propertyRule = buildRuleFromPath(propertyValueData, resourceInstanceProperty, resourceInstanceId);
655 rules = new ArrayList<>();
656 rules.add(propertyRule);
657 if (currentRules != null) {
658 rules = mergeRules(currentRules, rules);
661 // Full mode. all rules are sent in update operation.
662 rules = sortRules(rules);
664 propertyValueData.setRules(rules);
667 private List<PropertyRule> mergeRules(List<PropertyRule> currentRules, List<PropertyRule> newRules) {
668 List<PropertyRule> mergedRules = new ArrayList<>();
669 if (newRules == null || newRules.isEmpty()) {
672 for (PropertyRule rule : currentRules) {
673 PropertyRule propertyRule = new PropertyRule(rule.getRule(), rule.getValue());
674 mergedRules.add(propertyRule);
676 for (PropertyRule rule : newRules) {
677 PropertyRule foundRule = findRuleInList(rule, mergedRules);
678 if (foundRule != null) {
679 foundRule.setValue(rule.getValue());
681 mergedRules.add(rule);
687 private PropertyRule findRuleInList(PropertyRule rule, List<PropertyRule> rules) {
688 if (rules == null || rules.isEmpty() || rule.getRule() == null || rule.getRule().isEmpty()) {
691 PropertyRule foundRule = null;
692 for (PropertyRule propertyRule : rules) {
693 if (rule.getRuleSize() != propertyRule.getRuleSize()) {
696 boolean equals = propertyRule.compareRule(rule);
698 foundRule = propertyRule;
706 * return all properties associated to resource instance. The result does contains the property unique id but not its type, default value...
708 * @param resourceInstanceUid
711 public Either<List<ComponentInstanceProperty>, JanusGraphOperationStatus> getAllPropertiesOfResourceInstanceOnlyPropertyDefId(
712 String resourceInstanceUid) {
713 return getAllPropertiesOfResourceInstanceOnlyPropertyDefId(resourceInstanceUid, NodeTypeEnum.ResourceInstance);
716 public Either<PropertyValueData, JanusGraphOperationStatus> removePropertyOfResourceInstance(String propertyValueUid, String resourceInstanceId) {
717 Either<ComponentInstanceData, JanusGraphOperationStatus> findResInstanceRes = janusGraphGenericDao
718 .getNode(UniqueIdBuilder.getKeyByNodeType(NodeTypeEnum.ResourceInstance), resourceInstanceId, ComponentInstanceData.class);
719 if (findResInstanceRes.isRight()) {
720 JanusGraphOperationStatus status = findResInstanceRes.right().value();
721 if (status == JanusGraphOperationStatus.NOT_FOUND) {
722 status = JanusGraphOperationStatus.INVALID_ID;
724 return Either.right(status);
726 Either<PropertyValueData, JanusGraphOperationStatus> findPropertyDefRes = janusGraphGenericDao
727 .getNode(UniqueIdBuilder.getKeyByNodeType(NodeTypeEnum.PropertyValue), propertyValueUid, PropertyValueData.class);
728 if (findPropertyDefRes.isRight()) {
729 JanusGraphOperationStatus status = findPropertyDefRes.right().value();
730 if (status == JanusGraphOperationStatus.NOT_FOUND) {
731 status = JanusGraphOperationStatus.INVALID_ID;
733 return Either.right(status);
735 Either<GraphRelation, JanusGraphOperationStatus> relation = janusGraphGenericDao
736 .getRelation(findResInstanceRes.left().value(), findPropertyDefRes.left().value(), GraphEdgeLabels.PROPERTY_VALUE);
737 if (relation.isRight()) {
738 // TODO: add error in case of error
739 JanusGraphOperationStatus status = relation.right().value();
740 if (status == JanusGraphOperationStatus.NOT_FOUND) {
741 status = JanusGraphOperationStatus.INVALID_ID;
743 return Either.right(status);
745 Either<PropertyValueData, JanusGraphOperationStatus> deleteNode = janusGraphGenericDao
746 .deleteNode(findPropertyDefRes.left().value(), PropertyValueData.class);
747 if (deleteNode.isRight()) {
748 return Either.right(deleteNode.right().value());
750 PropertyValueData value = deleteNode.left().value();
751 return Either.left(value);
754 public Either<ComponentInstanceProperty, StorageOperationStatus> removePropertyValueFromResourceInstance(String propertyValueUid,
755 String resourceInstanceId,
756 boolean inTransaction) {
757 Either<ComponentInstanceProperty, StorageOperationStatus> result = null;
759 Either<PropertyValueData, JanusGraphOperationStatus> eitherStatus = this
760 .removePropertyOfResourceInstance(propertyValueUid, resourceInstanceId);
761 if (eitherStatus.isRight()) {
762 log.error("Failed to remove property value {} from resource instance {} in Graph. status is {}", propertyValueUid, resourceInstanceId,
763 eitherStatus.right().value().name());
764 result = Either.right(DaoStatusConverter.convertJanusGraphStatusToStorageStatus(eitherStatus.right().value()));
767 PropertyValueData propertyValueData = eitherStatus.left().value();
768 ComponentInstanceProperty propertyValueResult = new ComponentInstanceProperty();
769 propertyValueResult.setUniqueId(resourceInstanceId);
770 propertyValueResult.setValue(propertyValueData.getValue());
771 log.debug("The returned ResourceInstanceProperty is {}", propertyValueResult);
772 result = Either.left(propertyValueResult);
776 if (!inTransaction) {
777 if (result == null || result.isRight()) {
778 log.error(GOING_TO_EXECUTE_ROLLBACK_ON_GRAPH);
779 janusGraphGenericDao.rollback();
781 log.debug(GOING_TO_EXECUTE_COMMIT_ON_GRAPH);
782 janusGraphGenericDao.commit();
788 public ComponentInstanceProperty buildResourceInstanceProperty(PropertyValueData propertyValueData,
789 ComponentInstanceProperty resourceInstanceProperty) {
790 String value = propertyValueData.getValue();
791 String uid = propertyValueData.getUniqueId();
792 ComponentInstanceProperty instanceProperty = new ComponentInstanceProperty(resourceInstanceProperty, value, uid);
793 instanceProperty.setPath(resourceInstanceProperty.getPath());
794 return instanceProperty;
798 public boolean isPropertyDefaultValueValid(IComplexDefaultValue propertyDefinition, Map<String, DataTypeDefinition> dataTypes) {
799 if (propertyDefinition == null) {
802 String innerType = null;
803 String propertyType = propertyDefinition.getType();
804 ToscaPropertyType type = getType(propertyType);
805 if (type == ToscaPropertyType.LIST || type == ToscaPropertyType.MAP) {
806 SchemaDefinition def = propertyDefinition.getSchema();
810 PropertyDataDefinition propDef = def.getProperty();
811 if (propDef == null) {
814 innerType = propDef.getType();
816 String value = propertyDefinition.getDefaultValue();
818 return isValidValue(type, value, innerType, dataTypes);
820 log.trace("The given type {} is not a pre defined one.", propertyType);
821 DataTypeDefinition foundDt = dataTypes.get(propertyType);
822 if (foundDt != null) {
823 return isValidComplexValue(foundDt, value, dataTypes);
830 public boolean isPropertyTypeValid(final IComplexDefaultValue property, final String model) {
831 if (property == null) {
834 if (ToscaPropertyType.isValidType(property.getType()) == null) {
835 Either<Boolean, JanusGraphOperationStatus> definedInDataTypes = isDefinedInDataTypes(property.getType(), model);
836 if (definedInDataTypes.isRight()) {
839 Boolean isExist = definedInDataTypes.left().value();
840 return isExist.booleanValue();
846 public boolean isPropertyTypeValid(final IComplexDefaultValue property, final Map<String, DataTypeDefinition> dataTypes) {
847 if (property == null) {
850 return ToscaPropertyType.isValidType(property.getType()) != null || dataTypes.containsKey(property.getType());
854 public ImmutablePair<String, Boolean> isPropertyInnerTypeValid(IComplexDefaultValue property, Map<String, DataTypeDefinition> dataTypes) {
855 if (property == null) {
856 return new ImmutablePair<>(null, false);
858 SchemaDefinition schema;
859 PropertyDataDefinition innerProp;
860 String innerType = null;
861 if ((schema = property.getSchema()) != null) {
862 if ((innerProp = schema.getProperty()) != null) {
863 innerType = innerProp.getType();
866 ToscaPropertyType innerToscaType = ToscaPropertyType.isValidType(innerType);
867 if (innerToscaType == null) {
868 DataTypeDefinition dataTypeDefinition = dataTypes.get(innerType);
869 if (dataTypeDefinition == null) {
870 log.debug("The inner type {} is not a data type.", innerType);
871 return new ImmutablePair<>(innerType, false);
873 log.debug("The inner type {} is a data type. Data type definition is {}", innerType, dataTypeDefinition);
876 return new ImmutablePair<>(innerType, true);
879 private boolean isValidComplexValue(DataTypeDefinition foundDt, String value, Map<String, DataTypeDefinition> dataTypes) {
880 ImmutablePair<JsonElement, Boolean> validateAndUpdate = dataTypeValidatorConverter.validateAndUpdate(value, foundDt, dataTypes);
881 log.trace("The result after validating complex value of type {} is {}", foundDt.getName(), validateAndUpdate);
882 return validateAndUpdate.right.booleanValue();
885 public Either<List<ComponentInstanceProperty>, JanusGraphOperationStatus> getAllPropertiesOfResourceInstanceOnlyPropertyDefId(
886 String resourceInstanceUid, NodeTypeEnum instanceNodeType) {
887 Either<JanusGraphVertex, JanusGraphOperationStatus> findResInstanceRes = janusGraphGenericDao
888 .getVertexByProperty(UniqueIdBuilder.getKeyByNodeType(instanceNodeType), resourceInstanceUid);
889 if (findResInstanceRes.isRight()) {
890 JanusGraphOperationStatus status = findResInstanceRes.right().value();
891 if (status == JanusGraphOperationStatus.NOT_FOUND) {
892 status = JanusGraphOperationStatus.INVALID_ID;
894 return Either.right(status);
896 Either<List<ImmutablePair<JanusGraphVertex, Edge>>, JanusGraphOperationStatus> propertyImplNodes = janusGraphGenericDao
897 .getChildrenVertecies(UniqueIdBuilder.getKeyByNodeType(instanceNodeType), resourceInstanceUid, GraphEdgeLabels.PROPERTY_VALUE);
898 if (propertyImplNodes.isRight()) {
899 JanusGraphOperationStatus status = propertyImplNodes.right().value();
900 return Either.right(status);
902 List<ImmutablePair<JanusGraphVertex, Edge>> list = propertyImplNodes.left().value();
903 if (list == null || list.isEmpty()) {
904 return Either.right(JanusGraphOperationStatus.NOT_FOUND);
906 List<ComponentInstanceProperty> result = new ArrayList<>();
907 for (ImmutablePair<JanusGraphVertex, Edge> propertyValue : list) {
908 JanusGraphVertex propertyValueDataVertex = propertyValue.getLeft();
909 String propertyValueUid = (String) janusGraphGenericDao
910 .getProperty(propertyValueDataVertex, GraphPropertiesDictionary.UNIQUE_ID.getProperty());
911 String value = (String) janusGraphGenericDao.getProperty(propertyValueDataVertex, GraphPropertiesDictionary.VALUE.getProperty());
912 ImmutablePair<JanusGraphVertex, Edge> propertyDefPair = janusGraphGenericDao
913 .getChildVertex(propertyValueDataVertex, GraphEdgeLabels.PROPERTY_IMPL);
914 if (propertyDefPair == null) {
915 return Either.right(JanusGraphOperationStatus.NOT_FOUND);
917 Map<String, Object> properties = janusGraphGenericDao.getProperties(propertyValueDataVertex);
918 PropertyValueData propertyValueData = GraphElementFactory
919 .createElement(NodeTypeEnum.PropertyValue.getName(), GraphElementTypeEnum.Node, properties, PropertyValueData.class);
920 String propertyUniqueId = (String) janusGraphGenericDao
921 .getProperty(propertyDefPair.left, GraphPropertiesDictionary.UNIQUE_ID.getProperty());
922 ComponentInstanceProperty resourceInstanceProperty = new ComponentInstanceProperty();
923 // set property original unique id
924 resourceInstanceProperty.setUniqueId(propertyUniqueId);
927 // TODO: esofer add resource id
928 resourceInstanceProperty.setParentUniqueId(null);
930 resourceInstanceProperty.setValue(value);
931 // set property value unique id
932 resourceInstanceProperty.setValueUniqueUid(propertyValueUid);
934 resourceInstanceProperty.setRules(propertyValueData.getRules());
935 result.add(resourceInstanceProperty);
937 return Either.left(result);
941 * Find the default value from the list of component instances. Start the search from the second component instance
943 * @param pathOfComponentInstances
944 * @param propertyUniqueId
945 * @param defaultValue
948 public Either<String, JanusGraphOperationStatus> findDefaultValueFromSecondPosition(List<String> pathOfComponentInstances,
949 String propertyUniqueId, String defaultValue) {
950 log.trace("In find default value: path= {} propertyUniqId={} defaultValue= {}", pathOfComponentInstances, propertyUniqueId, defaultValue);
951 if (pathOfComponentInstances == null || pathOfComponentInstances.size() < 2) {
952 return Either.left(defaultValue);
954 String result = defaultValue;
955 for (int i = 1; i < pathOfComponentInstances.size(); i++) {
956 String compInstanceId = pathOfComponentInstances.get(i);
957 Either<List<ComponentInstanceProperty>, JanusGraphOperationStatus> propertyValuesResult = this
958 .getAllPropertiesOfResourceInstanceOnlyPropertyDefId(compInstanceId, NodeTypeEnum.ResourceInstance);
959 log.trace("After fetching properties values of component instance {}. {}", compInstanceId, propertyValuesResult);
960 if (propertyValuesResult.isRight()) {
961 JanusGraphOperationStatus status = propertyValuesResult.right().value();
962 if (status != JanusGraphOperationStatus.NOT_FOUND) {
963 return Either.right(status);
968 ComponentInstanceProperty foundCompInstanceProperty = fetchByPropertyUid(propertyValuesResult.left().value(), propertyUniqueId);
969 log.trace("After finding the component instance property on{} . {}", compInstanceId, foundCompInstanceProperty);
970 if (foundCompInstanceProperty == null) {
973 List<PropertyRule> rules = getOrBuildRulesIfNotExists(pathOfComponentInstances.size() - i, pathOfComponentInstances.get(i),
974 foundCompInstanceProperty.getRules(), foundCompInstanceProperty.getValue());
975 log.trace("Rules of property {} on component instance {} are {}", propertyUniqueId, compInstanceId, rules);
976 PropertyRule matchedRule = findMatchRule(pathOfComponentInstances, i, rules);
977 log.trace("Match rule is {}", matchedRule);
978 if (matchedRule != null) {
979 result = matchedRule.getValue();
983 return Either.left(result);
986 private ComponentInstanceProperty fetchByPropertyUid(List<ComponentInstanceProperty> list, String propertyUniqueId) {
987 ComponentInstanceProperty result = null;
991 for (ComponentInstanceProperty instProperty : list) {
992 if (instProperty.getUniqueId().equals(propertyUniqueId)) {
993 result = instProperty;
1000 private List<PropertyRule> getOrBuildRulesIfNotExists(int ruleSize, String compInstanceId, List<PropertyRule> rules, String value) {
1001 if (rules != null) {
1004 rules = buildDefaultRule(compInstanceId, ruleSize, value);
1008 private List<PropertyRule> getRulesOfPropertyValue(int size, String instanceId, ComponentInstanceProperty componentInstanceProperty) {
1009 List<PropertyRule> rules = componentInstanceProperty.getRules();
1010 if (rules == null) {
1011 rules = buildDefaultRule(instanceId, size, componentInstanceProperty.getValue());
1016 private List<PropertyRule> buildDefaultRule(String componentInstanceId, int size, String value) {
1017 List<PropertyRule> rules = new ArrayList<>();
1018 List<String> rule = new ArrayList<>();
1019 rule.add(componentInstanceId);
1020 for (int i = 0; i < size - 1; i++) {
1021 rule.add(PropertyRule.getRuleAnyMatch());
1023 PropertyRule propertyRule = new PropertyRule(rule, value);
1024 rules.add(propertyRule);
1028 private PropertyRule findMatchRule(List<String> pathOfInstances, int level, List<PropertyRule> rules) {
1029 PropertyRule propertyRule = null;
1030 String stringForMatch = buildStringForMatch(pathOfInstances, level);
1031 String firstCompInstance = pathOfInstances.get(level);
1032 if (rules != null) {
1033 for (PropertyRule rule : rules) {
1034 int ruleSize = rule.getRule().size();
1035 // check the length of the rule equals to the length of the
1038 if (ruleSize != pathOfInstances.size() - level) {
1041 // check that the rule starts with correct component instance id
1042 if (!checkFirstItem(firstCompInstance, rule.getFirstToken())) {
1045 String secondToken = rule.getToken(2);
1046 if (secondToken != null && (secondToken.equals(PropertyRule.getForceAll()) || secondToken.equals(PropertyRule.getALL()))) {
1047 propertyRule = rule;
1050 String patternStr = buildStringForMatch(rule.getRule(), 0);
1051 Pattern pattern = Pattern.compile(patternStr);
1052 Matcher matcher = pattern.matcher(stringForMatch);
1053 if (matcher.matches()) {
1054 if (log.isTraceEnabled()) {
1055 log.trace("{} matches the rule {}", stringForMatch, patternStr);
1057 propertyRule = rule;
1062 return propertyRule;
1065 private boolean checkFirstItem(String left, String right) {
1066 if (left != null && left.equals(right)) {
1072 private String buildStringForMatch(List<String> pathOfInstances, int level) {
1073 StringBuilder builder = new StringBuilder();
1074 for (int i = level; i < pathOfInstances.size(); i++) {
1075 builder.append(pathOfInstances.get(i));
1076 if (i < pathOfInstances.size() - 1) {
1077 builder.append("#");
1080 return builder.toString();
1083 public void updatePropertyByBestMatch(String propertyUniqueId, ComponentInstanceProperty instanceProperty,
1084 Map<String, ComponentInstanceProperty> instanceIdToValue) {
1085 List<String> pathOfInstances = instanceProperty.getPath();
1087 int size = pathOfInstances.size();
1088 int numberOfMatches = 0;
1089 for (String instanceId : pathOfInstances) {
1090 ComponentInstanceProperty componentInstanceProperty = instanceIdToValue.get(instanceId);
1091 if (componentInstanceProperty != null) {
1092 List<PropertyRule> rules = getRulesOfPropertyValue(size - level, instanceId, componentInstanceProperty);
1093 // If it is the first level instance, then update valueUniuqeId
1095 // parameter in order to know on update that
1097 // we should update and not create new node on graph.
1099 instanceProperty.setValueUniqueUid(componentInstanceProperty.getValueUniqueUid());
1100 instanceProperty.setRules(rules);
1102 PropertyRule rule = findMatchRule(pathOfInstances, level, rules);
1105 String value = rule.getValue();
1106 if (numberOfMatches == 1) {
1107 instanceProperty.setValue(value);
1108 if (log.isDebugEnabled()) {
1109 log.debug("Set the value of property {} {} on path {} to be {}", propertyUniqueId, instanceProperty.getName(),
1110 pathOfInstances, value);
1112 } else if (numberOfMatches == 2) {
1113 // In case of another property value match, then use the
1115 // value to be the default value of the property.
1116 instanceProperty.setDefaultValue(value);
1117 if (log.isDebugEnabled()) {
1118 log.debug("Set the default value of property {} {} on path {} to be {}", propertyUniqueId, instanceProperty.getName(),
1119 pathOfInstances, value);
1130 * Add data type to graph.
1132 * 1. Add data type node
1134 * 2. Add edge between the former node to its parent(if exists)
1136 * 3. Add property node and associate it to the node created at #1. (per property & if exists)
1138 * @param dataTypeDefinition
1141 private Either<DataTypeData, JanusGraphOperationStatus> addDataTypeToGraph(DataTypeDefinition dataTypeDefinition) {
1142 log.debug("Got data type {}", dataTypeDefinition);
1143 String dtUniqueId = UniqueIdBuilder.buildDataTypeUid(dataTypeDefinition.getModel(), dataTypeDefinition.getName());
1144 DataTypeData dataTypeData = buildDataTypeData(dataTypeDefinition, dtUniqueId);
1145 log.debug("Before adding data type to graph. dataTypeData = {}", dataTypeData);
1146 Either<DataTypeData, JanusGraphOperationStatus> createDataTypeResult = janusGraphGenericDao.createNode(dataTypeData, DataTypeData.class);
1147 log.debug("After adding data type to graph. status is = {}", createDataTypeResult);
1148 if (createDataTypeResult.isRight()) {
1149 JanusGraphOperationStatus operationStatus = createDataTypeResult.right().value();
1150 log.debug("Failed to data type {} to graph. status is {}", dataTypeDefinition.getName(), operationStatus);
1151 BeEcompErrorManager.getInstance().logBeFailedAddingNodeTypeError("AddDataType", NodeTypeEnum.DataType.getName());
1152 return Either.right(operationStatus);
1154 DataTypeData resultCTD = createDataTypeResult.left().value();
1155 List<PropertyDefinition> properties = dataTypeDefinition.getProperties();
1156 Either<Map<String, PropertyData>, JanusGraphOperationStatus> addPropertiesToDataType = addPropertiesToDataType(resultCTD.getUniqueId(), dataTypeDefinition.getModel(),
1158 if (addPropertiesToDataType.isRight()) {
1159 log.debug("Failed add properties {} to data type {}", properties, dataTypeDefinition.getName());
1160 return Either.right(addPropertiesToDataType.right().value());
1163 final Either<GraphRelation, JanusGraphOperationStatus> modelRelationship = addDataTypeToModel(dataTypeDefinition);
1164 if (modelRelationship.isRight()) {
1165 return Either.right(modelRelationship.right().value());
1168 String derivedFrom = dataTypeDefinition.getDerivedFromName();
1169 if (derivedFrom != null) {
1170 final Either<DataTypeDefinition, JanusGraphOperationStatus> derivedFromDataType = getDataTypeByNameValidForModel(derivedFrom, dataTypeDefinition.getModel());
1171 if (derivedFromDataType.isRight()) {
1172 return Either.right(derivedFromDataType.right().value());
1175 log.debug("Before creating relation between data type {} to its parent {}", dtUniqueId, derivedFrom);
1176 UniqueIdData from = new UniqueIdData(NodeTypeEnum.DataType, dtUniqueId);
1177 final String deriveFromUid = derivedFromDataType.left().value().getUniqueId();
1178 UniqueIdData to = new UniqueIdData(NodeTypeEnum.DataType, deriveFromUid);
1179 Either<GraphRelation, JanusGraphOperationStatus> createRelation = janusGraphGenericDao
1180 .createRelation(from, to, GraphEdgeLabels.DERIVED_FROM, null);
1181 log.debug("After create relation between capability type {} to its parent {}. status is {}", dtUniqueId, derivedFrom, createRelation);
1182 if (createRelation.isRight()) {
1183 return Either.right(createRelation.right().value());
1186 return Either.left(createDataTypeResult.left().value());
1189 private Either<GraphRelation, JanusGraphOperationStatus> addDataTypeToModel(final DataTypeDefinition dataTypeDefinition) {
1190 final String model = dataTypeDefinition.getModel();
1191 if (model == null) {
1192 return Either.left(null);
1194 final GraphNode from = new UniqueIdData(NodeTypeEnum.Model, UniqueIdBuilder.buildModelUid(model));
1195 final GraphNode to = new UniqueIdData(NodeTypeEnum.DataType, dataTypeDefinition.getUniqueId());
1196 log.info("Connecting model {} to type {}", from, to);
1197 return janusGraphGenericDao.createRelation(from , to, GraphEdgeLabels.MODEL_ELEMENT, Collections.emptyMap());
1200 private DataTypeData buildDataTypeData(DataTypeDefinition dataTypeDefinition, String ctUniqueId) {
1201 DataTypeData dataTypeData = new DataTypeData(dataTypeDefinition);
1202 dataTypeData.getDataTypeDataDefinition().setUniqueId(ctUniqueId);
1203 Long creationDate = dataTypeData.getDataTypeDataDefinition().getCreationTime();
1204 if (creationDate == null) {
1205 creationDate = System.currentTimeMillis();
1207 dataTypeData.getDataTypeDataDefinition().setCreationTime(creationDate);
1208 dataTypeData.getDataTypeDataDefinition().setModificationTime(creationDate);
1209 return dataTypeData;
1213 * add properties to capability type.
1215 * Per property, add a property node and associate it to the capability type
1221 private Either<Map<String, PropertyData>, JanusGraphOperationStatus> addPropertiesToDataType(final String uniqueId, final String modelName,
1222 final List<PropertyDefinition> properties) {
1223 Map<String, PropertyData> propertiesData = new HashMap<>();
1224 if (properties != null && !properties.isEmpty()) {
1225 for (PropertyDefinition propertyDefinition : properties) {
1226 String propertyName = propertyDefinition.getName();
1227 String propertyType = propertyDefinition.getType();
1228 Either<Boolean, JanusGraphOperationStatus> validPropertyType = isValidPropertyType(propertyType, modelName);
1229 if (validPropertyType.isRight()) {
1230 log.debug("Data type {} contains invalid property type {}", uniqueId, propertyType);
1231 return Either.right(validPropertyType.right().value());
1233 Boolean isValid = validPropertyType.left().value();
1234 if (isValid == null || !isValid.booleanValue()) {
1235 log.debug("Data type {} contains invalid property type {}", uniqueId, propertyType);
1236 return Either.right(JanusGraphOperationStatus.INVALID_TYPE);
1238 Either<PropertyData, JanusGraphOperationStatus> addPropertyToNodeType = this
1239 .addPropertyToNodeType(propertyName, propertyDefinition, NodeTypeEnum.DataType, uniqueId);
1240 if (addPropertyToNodeType.isRight()) {
1241 JanusGraphOperationStatus operationStatus = addPropertyToNodeType.right().value();
1242 log.debug("Failed to associate data type {} to property {} in graph. status is {}", uniqueId, propertyName, operationStatus);
1243 BeEcompErrorManager.getInstance()
1244 .logInternalFlowError("AddPropertyToDataType", "Failed to associate property to data type. Status is " + operationStatus,
1245 ErrorSeverity.ERROR);
1246 return Either.right(operationStatus);
1248 propertiesData.put(propertyName, addPropertyToNodeType.left().value());
1250 DataTypeData dataTypeData = new DataTypeData();
1251 dataTypeData.getDataTypeDataDefinition().setUniqueId(uniqueId);
1252 long modificationTime = System.currentTimeMillis();
1253 dataTypeData.getDataTypeDataDefinition().setModificationTime(modificationTime);
1254 Either<DataTypeData, JanusGraphOperationStatus> updateNode = janusGraphGenericDao.updateNode(dataTypeData, DataTypeData.class);
1255 if (updateNode.isRight()) {
1256 JanusGraphOperationStatus operationStatus = updateNode.right().value();
1257 log.debug("Failed to update modification time data type {} from graph. status is {}", uniqueId, operationStatus);
1258 BeEcompErrorManager.getInstance()
1259 .logInternalFlowError("AddPropertyToDataType", "Failed to fetch data type. Status is " + operationStatus, ErrorSeverity.ERROR);
1260 return Either.right(operationStatus);
1262 log.debug("Update data type uid {}. Set modification time to {}", uniqueId, modificationTime);
1265 return Either.left(propertiesData);
1268 public Either<DataTypeDefinition, JanusGraphOperationStatus> getDataTypeByNameValidForModel(final String name, final String modelName) {
1269 final Either<DataTypeData, JanusGraphOperationStatus> dataTypesRes = janusGraphGenericDao
1270 .getNode(GraphPropertiesDictionary.NAME.getProperty(), name, DataTypeData.class, modelName);
1271 if (dataTypesRes.isRight()) {
1272 final JanusGraphOperationStatus status = dataTypesRes.right().value();
1273 log.debug(DATA_TYPE_CANNOT_BE_FOUND_IN_GRAPH_STATUS_IS, name, status);
1274 return Either.right(status);
1276 final DataTypeData dataType = dataTypesRes.left().value();
1277 final DataTypeDefinition dataTypeDefinition = new DataTypeDefinition(dataType.getDataTypeDataDefinition());
1278 final JanusGraphOperationStatus propertiesStatus = fillProperties(dataTypeDefinition.getUniqueId(), dataTypeDefinition);
1279 if (propertiesStatus != JanusGraphOperationStatus.OK) {
1280 log.error(BUSINESS_PROCESS_ERROR, FAILED_TO_FETCH_PROPERTIES_OF_DATA_TYPE, dataTypeDefinition.getUniqueId());
1281 return Either.right(propertiesStatus);
1283 final Either<ImmutablePair<DataTypeData, GraphEdge>, JanusGraphOperationStatus> parentNode = janusGraphGenericDao
1284 .getChild(UniqueIdBuilder.getKeyByNodeType(NodeTypeEnum.DataType), dataTypeDefinition.getUniqueId(), GraphEdgeLabels.DERIVED_FROM, NodeTypeEnum.DataType,
1285 DataTypeData.class);
1286 log.debug(AFTER_RETRIEVING_DERIVED_FROM_NODE_OF_STATUS_IS, dataTypeDefinition.getUniqueId(), parentNode);
1287 if (parentNode.isRight()) {
1288 final JanusGraphOperationStatus janusGraphOperationStatus = parentNode.right().value();
1289 if (janusGraphOperationStatus != JanusGraphOperationStatus.NOT_FOUND) {
1290 log.error(BUSINESS_PROCESS_ERROR, "Failed to find the parent data type of data type {}. status is {}", dataTypeDefinition.getUniqueId(), janusGraphOperationStatus);
1291 return Either.right(janusGraphOperationStatus);
1294 // derived from node was found
1295 final ImmutablePair<DataTypeData, GraphEdge> immutablePair = parentNode.left().value();
1296 final DataTypeData parentDataType = immutablePair.getKey();
1297 final Either<DataTypeDefinition, JanusGraphOperationStatus> dataTypeByUid = getDataTypeByUid(parentDataType.getUniqueId());
1298 if (dataTypeByUid.isRight()) {
1299 return Either.right(dataTypeByUid.right().value());
1301 DataTypeDefinition parentDataTypeDefinition = dataTypeByUid.left().value();
1302 dataTypeDefinition.setDerivedFrom(parentDataTypeDefinition);
1304 return Either.left(dataTypeDefinition);
1308 * Build Data type object from graph by unique id
1313 public Either<DataTypeDefinition, JanusGraphOperationStatus> getDataTypeByUid(String uniqueId) {
1314 Either<DataTypeDefinition, JanusGraphOperationStatus> result = null;
1315 Either<DataTypeData, JanusGraphOperationStatus> dataTypesRes = janusGraphGenericDao
1316 .getNode(UniqueIdBuilder.getKeyByNodeType(NodeTypeEnum.DataType), uniqueId, DataTypeData.class);
1317 if (dataTypesRes.isRight()) {
1318 JanusGraphOperationStatus status = dataTypesRes.right().value();
1319 log.debug(DATA_TYPE_CANNOT_BE_FOUND_IN_GRAPH_STATUS_IS, uniqueId, status);
1320 return Either.right(status);
1322 DataTypeData ctData = dataTypesRes.left().value();
1323 DataTypeDefinition dataTypeDefinition = new DataTypeDefinition(ctData.getDataTypeDataDefinition());
1324 JanusGraphOperationStatus propertiesStatus = fillProperties(uniqueId, dataTypeDefinition);
1325 if (propertiesStatus != JanusGraphOperationStatus.OK) {
1326 log.error(FAILED_TO_FETCH_PROPERTIES_OF_DATA_TYPE, uniqueId);
1327 return Either.right(propertiesStatus);
1329 Either<ImmutablePair<DataTypeData, GraphEdge>, JanusGraphOperationStatus> parentNode = janusGraphGenericDao
1330 .getChild(UniqueIdBuilder.getKeyByNodeType(NodeTypeEnum.DataType), uniqueId, GraphEdgeLabels.DERIVED_FROM, NodeTypeEnum.DataType,
1331 DataTypeData.class);
1332 log.debug(AFTER_RETRIEVING_DERIVED_FROM_NODE_OF_STATUS_IS, uniqueId, parentNode);
1333 if (parentNode.isRight()) {
1334 JanusGraphOperationStatus janusGraphOperationStatus = parentNode.right().value();
1335 if (janusGraphOperationStatus != JanusGraphOperationStatus.NOT_FOUND) {
1336 log.error("Failed to find the parent data type of data type {}. status is {}", uniqueId, janusGraphOperationStatus);
1337 result = Either.right(janusGraphOperationStatus);
1341 // derived from node was found
1342 ImmutablePair<DataTypeData, GraphEdge> immutablePair = parentNode.left().value();
1343 DataTypeData parentCT = immutablePair.getKey();
1344 String parentUniqueId = parentCT.getUniqueId();
1345 Either<DataTypeDefinition, JanusGraphOperationStatus> dataTypeByUid = getDataTypeByUid(parentUniqueId);
1346 if (dataTypeByUid.isRight()) {
1347 return Either.right(dataTypeByUid.right().value());
1349 DataTypeDefinition parentDataTypeDefinition = dataTypeByUid.left().value();
1350 dataTypeDefinition.setDerivedFrom(parentDataTypeDefinition);
1352 result = Either.left(dataTypeDefinition);
1356 private JanusGraphOperationStatus fillProperties(String uniqueId, DataTypeDefinition dataTypeDefinition) {
1357 Either<Map<String, PropertyDefinition>, JanusGraphOperationStatus> findPropertiesOfNode = this
1358 .findPropertiesOfNode(NodeTypeEnum.DataType, uniqueId);
1359 if (findPropertiesOfNode.isRight()) {
1360 JanusGraphOperationStatus janusGraphOperationStatus = findPropertiesOfNode.right().value();
1361 log.debug("After looking for properties of vertex {}. status is {}", uniqueId, janusGraphOperationStatus);
1362 if (JanusGraphOperationStatus.NOT_FOUND.equals(janusGraphOperationStatus)) {
1363 return JanusGraphOperationStatus.OK;
1365 return janusGraphOperationStatus;
1368 Map<String, PropertyDefinition> properties = findPropertiesOfNode.left().value();
1369 if (properties != null && !properties.isEmpty()) {
1370 List<PropertyDefinition> listOfProps = new ArrayList<>();
1371 for (Entry<String, PropertyDefinition> entry : properties.entrySet()) {
1372 String propName = entry.getKey();
1373 PropertyDefinition propertyDefinition = entry.getValue();
1374 PropertyDefinition newPropertyDefinition = new PropertyDefinition(propertyDefinition);
1375 newPropertyDefinition.setName(propName);
1376 listOfProps.add(newPropertyDefinition);
1378 dataTypeDefinition.setProperties(listOfProps);
1380 return JanusGraphOperationStatus.OK;
1384 private Either<DataTypeDefinition, StorageOperationStatus> addDataType(DataTypeDefinition dataTypeDefinition, boolean inTransaction) {
1385 Either<DataTypeDefinition, StorageOperationStatus> result = null;
1387 Either<DataTypeData, JanusGraphOperationStatus> eitherStatus = addDataTypeToGraph(dataTypeDefinition);
1388 if (eitherStatus.isRight()) {
1389 log.debug("Failed to add data type {} to Graph. status is {}", dataTypeDefinition, eitherStatus.right().value().name());
1390 BeEcompErrorManager.getInstance().logBeFailedAddingNodeTypeError("AddDataType", "DataType");
1391 result = Either.right(DaoStatusConverter.convertJanusGraphStatusToStorageStatus(eitherStatus.right().value()));
1394 DataTypeData capabilityTypeData = eitherStatus.left().value();
1395 DataTypeDefinition dataTypeDefResult = convertDTDataToDTDefinition(capabilityTypeData);
1396 log.debug("The returned CapabilityTypeDefinition is {}", dataTypeDefResult);
1397 result = Either.left(dataTypeDefResult);
1401 if (!inTransaction) {
1402 if (result == null || result.isRight()) {
1403 log.error(GOING_TO_EXECUTE_ROLLBACK_ON_GRAPH);
1404 janusGraphGenericDao.rollback();
1406 log.debug(GOING_TO_EXECUTE_COMMIT_ON_GRAPH);
1407 janusGraphGenericDao.commit();
1414 public Either<DataTypeDefinition, StorageOperationStatus> addDataType(DataTypeDefinition dataTypeDefinition) {
1415 return addDataType(dataTypeDefinition, true);
1419 public Either<DataTypeDefinition, StorageOperationStatus> getDataTypeByName(final String name, final String validForModel, final boolean inTransaction) {
1420 Either<DataTypeDefinition, StorageOperationStatus> result = null;
1422 Either<DataTypeDefinition, JanusGraphOperationStatus> ctResult = this.getDataTypeByNameValidForModel(name, validForModel);
1423 if (ctResult.isRight()) {
1424 JanusGraphOperationStatus status = ctResult.right().value();
1425 if (status != JanusGraphOperationStatus.NOT_FOUND) {
1426 log.error("Failed to retrieve information on capability type {} status is {}", name, status);
1428 result = Either.right(DaoStatusConverter.convertJanusGraphStatusToStorageStatus(ctResult.right().value()));
1431 result = Either.left(ctResult.left().value());
1434 if (!inTransaction) {
1435 if (result == null || result.isRight()) {
1436 log.error(GOING_TO_EXECUTE_ROLLBACK_ON_GRAPH);
1437 janusGraphGenericDao.rollback();
1439 log.debug(GOING_TO_EXECUTE_COMMIT_ON_GRAPH);
1440 janusGraphGenericDao.commit();
1447 public Either<DataTypeDefinition, StorageOperationStatus> getDataTypeByName(final String name, final String validForModel) {
1448 return getDataTypeByName(name, validForModel, true);
1451 public Either<DataTypeDefinition, StorageOperationStatus> getDataTypeByUidWithoutDerived(String uid, boolean inTransaction) {
1452 Either<DataTypeDefinition, StorageOperationStatus> result = null;
1454 Either<DataTypeDefinition, JanusGraphOperationStatus> ctResult = this.getDataTypeByUidWithoutDerivedDataTypes(uid);
1455 if (ctResult.isRight()) {
1456 JanusGraphOperationStatus status = ctResult.right().value();
1457 if (status != JanusGraphOperationStatus.NOT_FOUND) {
1458 log.error(BUSINESS_PROCESS_ERROR, "Failed to retrieve information on data type {} status is {}", uid, status);
1460 result = Either.right(DaoStatusConverter.convertJanusGraphStatusToStorageStatus(ctResult.right().value()));
1463 result = Either.left(ctResult.left().value());
1466 if (!inTransaction) {
1467 if (result == null || result.isRight()) {
1468 log.error(GOING_TO_EXECUTE_ROLLBACK_ON_GRAPH);
1469 janusGraphGenericDao.rollback();
1471 log.debug(GOING_TO_EXECUTE_COMMIT_ON_GRAPH);
1472 janusGraphGenericDao.commit();
1478 public Either<DataTypeDefinition, JanusGraphOperationStatus> getDataTypeByUidWithoutDerivedDataTypes(String uniqueId) {
1479 Either<DataTypeData, JanusGraphOperationStatus> dataTypesRes = janusGraphGenericDao
1480 .getNode(UniqueIdBuilder.getKeyByNodeType(NodeTypeEnum.DataType), uniqueId, DataTypeData.class);
1481 if (dataTypesRes.isRight()) {
1482 JanusGraphOperationStatus status = dataTypesRes.right().value();
1483 log.debug(DATA_TYPE_CANNOT_BE_FOUND_IN_GRAPH_STATUS_IS, uniqueId, status);
1484 return Either.right(status);
1486 DataTypeData ctData = dataTypesRes.left().value();
1487 DataTypeDefinition dataTypeDefinition = new DataTypeDefinition(ctData.getDataTypeDataDefinition());
1488 JanusGraphOperationStatus propertiesStatus = fillProperties(uniqueId, dataTypeDefinition);
1489 if (propertiesStatus != JanusGraphOperationStatus.OK) {
1490 log.error(FAILED_TO_FETCH_PROPERTIES_OF_DATA_TYPE, uniqueId);
1491 return Either.right(propertiesStatus);
1493 return Either.left(dataTypeDefinition);
1497 * convert between graph Node object to Java object
1499 * @param dataTypeData
1502 protected DataTypeDefinition convertDTDataToDTDefinition(DataTypeData dataTypeData) {
1503 log.debug("The object returned after create data type is {}", dataTypeData);
1504 return new DataTypeDefinition(dataTypeData.getDataTypeDataDefinition());
1507 private Either<Boolean, JanusGraphOperationStatus> isValidPropertyType(String propertyType, final String modelName) {
1508 if (propertyType == null || propertyType.isEmpty()) {
1509 return Either.left(false);
1511 ToscaPropertyType toscaPropertyType = ToscaPropertyType.isValidType(propertyType);
1512 if (toscaPropertyType == null) {
1513 return isDefinedInDataTypes(propertyType, modelName);
1515 return Either.left(true);
1519 public Either<Boolean, JanusGraphOperationStatus> isDefinedInDataTypes(final String propertyType, final String modelName) {
1520 Either<DataTypeDefinition, JanusGraphOperationStatus> dataType = getDataTypeByNameValidForModel(propertyType, modelName);
1521 if (dataType.isRight()) {
1522 JanusGraphOperationStatus status = dataType.right().value();
1523 if (status == JanusGraphOperationStatus.NOT_FOUND) {
1524 return Either.left(false);
1526 return Either.right(status);
1528 return Either.left(true);
1531 public Either<Map<String, Map<String, DataTypeDefinition>>, JanusGraphOperationStatus> getAllDataTypes() {
1532 final Map<String, Map<String, DataTypeDefinition>> dataTypes = new HashMap<>();
1533 Either<Map<String, Map<String, DataTypeDefinition>>, JanusGraphOperationStatus> result = Either.left(dataTypes);
1534 final Map<String, DataTypeDefinition> allDataTypesFound = new HashMap<>();
1536 final Map<String, List<String>> dataTypeUidstoModels = dataTypeOperation.getAllDataTypeUidsToModels();
1538 if (dataTypeUidstoModels != null) {
1539 log.trace("Number of data types to load is {}", dataTypeUidstoModels.size());
1540 for (Map.Entry<String, List<String>> entry : dataTypeUidstoModels.entrySet()) {
1541 log.trace("Going to fetch data type with uid {}", entry.getKey());
1542 Either<DataTypeDefinition, JanusGraphOperationStatus> dataTypeByUid = this
1543 .getAndAddDataTypeByUid(entry.getKey(), allDataTypesFound);
1544 if (dataTypeByUid.isRight()) {
1545 JanusGraphOperationStatus status = dataTypeByUid.right().value();
1546 if (status == JanusGraphOperationStatus.NOT_FOUND) {
1547 status = JanusGraphOperationStatus.INVALID_ID;
1549 return Either.right(status);
1551 for (final String model: entry.getValue()) {
1552 if (!dataTypes.containsKey(model)) {
1553 dataTypes.put(model, new HashMap<String, DataTypeDefinition>());
1555 DataTypeDefinition dataTypeDefinition = allDataTypesFound.get(entry.getKey());
1556 dataTypes.get(model).put(dataTypeDefinition.getName(), dataTypeDefinition);
1561 if (log.isTraceEnabled()) {
1562 if (result.isRight()) {
1563 log.trace("After fetching all data types {}", result);
1565 Map<String, Map<String, DataTypeDefinition>> map = result.left().value();
1567 String types = map.keySet().stream().collect(Collectors.joining(",", "[", "]"));
1568 log.trace("After fetching all data types {} ", types);
1576 * Build Data type object from graph by unique id
1581 private Either<DataTypeDefinition, JanusGraphOperationStatus> getAndAddDataTypeByUid(String uniqueId,
1582 Map<String, DataTypeDefinition> allDataTypes) {
1583 Either<DataTypeDefinition, JanusGraphOperationStatus> result = null;
1584 if (allDataTypes.containsKey(uniqueId)) {
1585 return Either.left(allDataTypes.get(uniqueId));
1587 Either<DataTypeData, JanusGraphOperationStatus> dataTypesRes = janusGraphGenericDao
1588 .getNode(UniqueIdBuilder.getKeyByNodeType(NodeTypeEnum.DataType), uniqueId, DataTypeData.class);
1589 if (dataTypesRes.isRight()) {
1590 JanusGraphOperationStatus status = dataTypesRes.right().value();
1591 log.debug(DATA_TYPE_CANNOT_BE_FOUND_IN_GRAPH_STATUS_IS, uniqueId, status);
1592 return Either.right(status);
1594 DataTypeData ctData = dataTypesRes.left().value();
1595 DataTypeDefinition dataTypeDefinition = new DataTypeDefinition(ctData.getDataTypeDataDefinition());
1596 JanusGraphOperationStatus propertiesStatus = fillProperties(uniqueId, dataTypeDefinition);
1597 if (propertiesStatus != JanusGraphOperationStatus.OK) {
1598 log.error(FAILED_TO_FETCH_PROPERTIES_OF_DATA_TYPE, uniqueId);
1599 return Either.right(propertiesStatus);
1601 allDataTypes.put(dataTypeDefinition.getUniqueId(), dataTypeDefinition);
1602 String derivedFrom = dataTypeDefinition.getDerivedFromName();
1603 if (allDataTypes.containsKey(derivedFrom)) {
1604 DataTypeDefinition parentDataTypeDefinition = allDataTypes.get(derivedFrom);
1605 dataTypeDefinition.setDerivedFrom(parentDataTypeDefinition);
1606 return Either.left(dataTypeDefinition);
1608 Either<ImmutablePair<DataTypeData, GraphEdge>, JanusGraphOperationStatus> parentNode = janusGraphGenericDao
1609 .getChild(UniqueIdBuilder.getKeyByNodeType(NodeTypeEnum.DataType), uniqueId, GraphEdgeLabels.DERIVED_FROM, NodeTypeEnum.DataType,
1610 DataTypeData.class);
1611 log.debug(AFTER_RETRIEVING_DERIVED_FROM_NODE_OF_STATUS_IS, uniqueId, parentNode);
1612 if (parentNode.isRight()) {
1613 JanusGraphOperationStatus janusGraphOperationStatus = parentNode.right().value();
1614 if (janusGraphOperationStatus != JanusGraphOperationStatus.NOT_FOUND) {
1615 log.error("Failed to find the parent data type of data type {}. status is {}", uniqueId, janusGraphOperationStatus);
1616 result = Either.right(janusGraphOperationStatus);
1620 // derived from node was found
1621 ImmutablePair<DataTypeData, GraphEdge> immutablePair = parentNode.left().value();
1622 DataTypeData parentCT = immutablePair.getKey();
1623 String parentUniqueId = parentCT.getUniqueId();
1624 Either<DataTypeDefinition, JanusGraphOperationStatus> dataTypeByUid = getDataTypeByUid(parentUniqueId);
1625 if (dataTypeByUid.isRight()) {
1626 return Either.right(dataTypeByUid.right().value());
1628 DataTypeDefinition parentDataTypeDefinition = dataTypeByUid.left().value();
1629 dataTypeDefinition.setDerivedFrom(parentDataTypeDefinition);
1630 final var model = getModel(uniqueId);
1631 if (StringUtils.isNotEmpty(model)) {
1632 dataTypeDefinition.setModel(model);
1635 result = Either.left(dataTypeDefinition);
1639 private String getModel(final String uniqueId) {
1640 final Either<ImmutablePair<ModelData, GraphEdge>, JanusGraphOperationStatus> model = janusGraphGenericDao.getParentNode(
1641 UniqueIdBuilder.getKeyByNodeType(NodeTypeEnum.DataType), uniqueId, GraphEdgeLabels.MODEL_ELEMENT,
1642 NodeTypeEnum.Model, ModelData.class);
1643 return model.isLeft() ? model.left().value().getLeft().getName() : StringUtils.EMPTY;
1646 public Either<String, JanusGraphOperationStatus> checkInnerType(PropertyDataDefinition propDataDef) {
1647 String propertyType = propDataDef.getType();
1648 ToscaPropertyType type = ToscaPropertyType.isValidType(propertyType);
1649 return getInnerType(type, propDataDef::getSchema);
1652 public Either<Object, Boolean> validateAndUpdatePropertyValue(String propertyType, String value, boolean isValidate, String innerType,
1653 Map<String, DataTypeDefinition> dataTypes) {
1654 log.trace("Going to validate property value and its type. type = {}, value = {}", propertyType, value);
1655 final ToscaPropertyType type = getType(propertyType);
1658 DataTypeDefinition dataTypeDefinition = dataTypes.get(propertyType);
1659 ImmutablePair<JsonElement, Boolean> validateResult = dataTypeValidatorConverter
1660 .validateAndUpdate(value, dataTypeDefinition, dataTypes);
1661 if (Boolean.FALSE.equals(validateResult.right)) {
1662 log.debug(THE_VALUE_OF_PROPERTY_FROM_TYPE_IS_INVALID, value, propertyType);
1663 return Either.right(false);
1665 JsonElement jsonElement = validateResult.left;
1666 String valueFromJsonElement = getValueFromJsonElement(jsonElement);
1667 return Either.left(valueFromJsonElement);
1669 log.trace("before validating property type {}", propertyType);
1670 boolean isValidProperty = isValidValue(type, value, innerType, dataTypes);
1671 if (!isValidProperty) {
1672 log.debug(THE_VALUE_OF_PROPERTY_FROM_TYPE_IS_INVALID, value, type);
1673 return Either.right(false);
1676 Object convertedValue = value;
1677 if (!isEmptyValue(value) && isValidate) {
1678 PropertyValueConverter converter = type.getConverter();
1679 convertedValue = converter.convert(value, innerType, dataTypes);
1681 return Either.left(convertedValue);
1684 public Either<Object, Boolean> validateAndUpdatePropertyValue(String propertyType, String value, String innerType,
1685 Map<String, DataTypeDefinition> dataTypes) {
1686 return validateAndUpdatePropertyValue(propertyType, value, true, innerType, dataTypes);
1689 public Either<Object, Boolean> validateAndUpdatePropertyValue(final Component containerComponent, final PropertyDataDefinition property,
1690 final Map<String, DataTypeDefinition> dataTypes) {
1691 if (property.isToscaFunction()) {
1692 toscaFunctionValidator.validate(property, containerComponent);
1693 property.setValue(property.getToscaFunction().getValue());
1694 return Either.left(property.getValue());
1696 Either<String, JanusGraphOperationStatus> checkInnerType = checkInnerType(property);
1697 if (checkInnerType.isRight()) {
1698 return Either.right(false);
1700 final String innerType = checkInnerType.left().value();
1701 return validateAndUpdatePropertyValue(property.getType(), property.getValue(), true, innerType, dataTypes);
1704 public <T extends GraphNode> Either<List<PropertyDefinition>, StorageOperationStatus> getAllPropertiesRec(String uniqueId, NodeTypeEnum nodeType,
1706 return this.findPropertiesOfNode(nodeType, uniqueId).right().bind(this::handleNotFoundProperties).left()
1707 .bind(props -> getAllDerivedFromChainProperties(uniqueId, nodeType, clazz, props.values()));
1710 private Either<Map<String, PropertyDefinition>, StorageOperationStatus> handleNotFoundProperties(
1711 JanusGraphOperationStatus janusGraphOperationStatus) {
1712 if (janusGraphOperationStatus == JanusGraphOperationStatus.NOT_FOUND) {
1713 return Either.left(new HashMap<>());
1715 return Either.right(DaoStatusConverter.convertJanusGraphStatusToStorageStatus(janusGraphOperationStatus));
1718 private <T extends GraphNode> Either<List<PropertyDefinition>, StorageOperationStatus> getAllDerivedFromChainProperties(String uniqueId,
1719 NodeTypeEnum nodeType,
1721 Collection<PropertyDefinition> nodeProps) {
1722 List<PropertyDefinition> accumulatedProps = new ArrayList<>(nodeProps);
1723 String currentNodeUid = uniqueId;
1724 Either<T, StorageOperationStatus> derivedFrom;
1725 while ((derivedFrom = derivedFromOperation.getDerivedFromChild(currentNodeUid, nodeType, clazz)).isLeft()) {
1726 currentNodeUid = derivedFrom.left().value().getUniqueId();
1727 JanusGraphOperationStatus janusGraphOperationStatus = fillPropertiesList(currentNodeUid, nodeType, accumulatedProps::addAll);
1728 if (janusGraphOperationStatus != JanusGraphOperationStatus.OK) {
1729 log.debug("failed to fetch properties for type {} with id {}", nodeType, currentNodeUid);
1730 return Either.right(DaoStatusConverter.convertJanusGraphStatusToStorageStatus(janusGraphOperationStatus));
1733 StorageOperationStatus getDerivedResult = derivedFrom.right().value();
1734 return isReachedEndOfDerivedFromChain(getDerivedResult) ? Either.left(accumulatedProps) : Either.right(getDerivedResult);
1737 private boolean isReachedEndOfDerivedFromChain(StorageOperationStatus getDerivedResult) {
1738 return getDerivedResult == StorageOperationStatus.NOT_FOUND;
1742 * @Override public PropertyOperation getPropertyOperation() { return this; }
1744 public JanusGraphOperationStatus fillPropertiesList(String uniqueId, NodeTypeEnum nodeType, Consumer<List<PropertyDefinition>> propertySetter) {
1745 Either<Map<String, PropertyDefinition>, JanusGraphOperationStatus> findPropertiesRes = findPropertiesifExist(uniqueId, nodeType);
1746 if (findPropertiesRes.isRight()) {
1747 return findPropertiesRes.right().value();
1749 Map<String, PropertyDefinition> properties = findPropertiesRes.left().value();
1750 if (properties != null) {
1751 List<PropertyDefinition> propertiesAsList = properties.entrySet().stream().map(Entry::getValue).collect(Collectors.toList());
1752 propertySetter.accept(propertiesAsList);
1754 return JanusGraphOperationStatus.OK;
1757 Either<Map<String, PropertyDefinition>, JanusGraphOperationStatus> findPropertiesifExist(String uniqueId, NodeTypeEnum nodeType) {
1758 Either<Map<String, PropertyDefinition>, JanusGraphOperationStatus> findPropertiesOfNode = this.findPropertiesOfNode(nodeType, uniqueId);
1759 if (findPropertiesOfNode.isRight()) {
1760 log.debug("After looking for properties of vertex {}. status is {}", uniqueId, findPropertiesOfNode.right().value());
1761 if (findPropertiesOfNode.right().value() == JanusGraphOperationStatus.NOT_FOUND) {
1762 return Either.left(Maps.newHashMap());
1764 return findPropertiesOfNode;
1766 return findPropertiesOfNode;
1770 * add properties to element type.
1772 * Per property, add a property node and associate it to the element type
1775 * @param propertiesMap
1778 protected Either<Map<String, PropertyData>, JanusGraphOperationStatus> addPropertiesToElementType(String uniqueId, NodeTypeEnum nodeType,
1779 Map<String, PropertyDefinition> propertiesMap) {
1780 Map<String, PropertyData> propertiesData = new HashMap<>();
1781 if (propertiesMap != null) {
1782 for (Entry<String, PropertyDefinition> propertyDefinitionEntry : propertiesMap.entrySet()) {
1783 String propertyName = propertyDefinitionEntry.getKey();
1784 Either<PropertyData, JanusGraphOperationStatus> addPropertyToNodeType = this
1785 .addPropertyToNodeType(propertyName, propertyDefinitionEntry.getValue(), nodeType, uniqueId);
1786 if (addPropertyToNodeType.isRight()) {
1787 JanusGraphOperationStatus operationStatus = addPropertyToNodeType.right().value();
1788 log.error("Failed to associate {} {} to property {} in graph. status is {}", nodeType.getName(), uniqueId, propertyName,
1790 return Either.right(operationStatus);
1792 propertiesData.put(propertyName, addPropertyToNodeType.left().value());
1795 return Either.left(propertiesData);
1798 public Either<Map<String, PropertyData>, JanusGraphOperationStatus> addPropertiesToElementType(String uniqueId, NodeTypeEnum elementType,
1799 List<PropertyDefinition> properties) {
1800 Map<String, PropertyDefinition> propMap;
1801 if (properties == null) {
1804 propMap = properties.stream().collect(Collectors.toMap(PropertyDataDefinition::getName, propDef -> propDef));
1806 return addPropertiesToElementType(uniqueId, elementType, propMap);
1810 public Either<DataTypeDefinition, StorageOperationStatus> updateDataType(DataTypeDefinition newDataTypeDefinition,
1811 DataTypeDefinition oldDataTypeDefinition) {
1812 return updateDataType(newDataTypeDefinition, oldDataTypeDefinition, true);
1815 private Either<DataTypeDefinition, StorageOperationStatus> updateDataType(DataTypeDefinition newDataTypeDefinition,
1816 DataTypeDefinition oldDataTypeDefinition, boolean inTransaction) {
1817 Either<DataTypeDefinition, StorageOperationStatus> result = null;
1819 List<PropertyDefinition> newProperties = newDataTypeDefinition.getProperties();
1820 List<PropertyDefinition> oldProperties = oldDataTypeDefinition.getProperties();
1821 String newDerivedFromName = newDataTypeDefinition.getDerivedFromName();
1822 String oldDerivedFromName = oldDataTypeDefinition.getDerivedFromName();
1823 String dataTypeName = newDataTypeDefinition.getName();
1824 List<PropertyDefinition> propertiesToAdd = new ArrayList<>();
1825 if (isPropertyTypeChanged(dataTypeName, newProperties, oldProperties, propertiesToAdd)
1826 || isDerivedFromNameChanged(dataTypeName, newDerivedFromName, oldDerivedFromName)) {
1827 log.debug("The new data type {} is invalid.", dataTypeName);
1828 result = Either.right(StorageOperationStatus.CANNOT_UPDATE_EXISTING_ENTITY);
1831 if (CollectionUtils.isEmpty(propertiesToAdd)) {
1832 log.debug("No new properties has been defined in the new data type {}", newDataTypeDefinition);
1833 result = Either.right(StorageOperationStatus.OK);
1836 Map<String, String> newDescriptions = getPropertyDescriptionsToUpdate(oldProperties, newProperties);
1837 if (MapUtils.isNotEmpty(newDescriptions)) {
1838 JanusGraphOperationStatus updatePropertiesStatus = updateDataTypePropertyDescriptions(oldDataTypeDefinition.getUniqueId(),
1840 if (updatePropertiesStatus != JanusGraphOperationStatus.OK) {
1841 log.debug("#updateDataType - Failed to update the descriptions of the properties of the data type {}. Status is {}",
1842 oldDataTypeDefinition, updatePropertiesStatus);
1843 BeEcompErrorManager.getInstance().logBeFailedAddingNodeTypeError(UPDATE_DATA_TYPE, PROPERTY);
1844 result = Either.right(DaoStatusConverter.convertJanusGraphStatusToStorageStatus(updatePropertiesStatus));
1848 Either<Map<String, PropertyData>, JanusGraphOperationStatus> addPropertiesToDataType = addPropertiesToDataType(
1849 oldDataTypeDefinition.getUniqueId(), oldDataTypeDefinition.getModel(), propertiesToAdd);
1850 if (addPropertiesToDataType.isRight()) {
1851 log.debug("Failed to update data type {} to Graph. Status is {}", oldDataTypeDefinition,
1852 addPropertiesToDataType.right().value().name());
1853 BeEcompErrorManager.getInstance().logBeFailedAddingNodeTypeError(UPDATE_DATA_TYPE, PROPERTY);
1854 result = Either.right(DaoStatusConverter.convertJanusGraphStatusToStorageStatus(addPropertiesToDataType.right().value()));
1857 Either<DataTypeDefinition, JanusGraphOperationStatus> dataTypeByUid = this.getDataTypeByUid(oldDataTypeDefinition.getUniqueId());
1858 if (dataTypeByUid.isRight()) {
1859 JanusGraphOperationStatus status = addPropertiesToDataType.right().value();
1860 log.debug("Failed to get data type {} after update. Status is {}", oldDataTypeDefinition.getUniqueId(), status.name());
1861 BeEcompErrorManager.getInstance().logBeFailedRetrieveNodeError(UPDATE_DATA_TYPE, PROPERTY, status.name());
1862 result = Either.right(DaoStatusConverter.convertJanusGraphStatusToStorageStatus(status));
1864 result = Either.left(dataTypeByUid.left().value());
1869 if (!inTransaction) {
1870 if (result == null || result.isRight()) {
1871 log.error(GOING_TO_EXECUTE_ROLLBACK_ON_GRAPH);
1872 janusGraphGenericDao.rollback();
1874 log.debug(GOING_TO_EXECUTE_COMMIT_ON_GRAPH);
1875 janusGraphGenericDao.commit();
1881 private boolean isPropertyTypeChanged(String dataTypeName, List<PropertyDefinition> newProperties, List<PropertyDefinition> oldProperties,
1882 List<PropertyDefinition> outputPropertiesToAdd) {
1883 if (newProperties != null && oldProperties != null) {
1884 Map<String, PropertyDefinition> newPropsMapper = newProperties.stream()
1885 .collect(Collectors.toMap(PropertyDataDefinition::getName, p -> p));
1886 Map<String, PropertyDefinition> oldPropsMapper = oldProperties.stream()
1887 .collect(Collectors.toMap(PropertyDataDefinition::getName, p -> p));
1888 for (Entry<String, PropertyDefinition> newPropertyEntry : newPropsMapper.entrySet()) {
1889 String propName = newPropertyEntry.getKey();
1890 PropertyDefinition propDef = newPropertyEntry.getValue();
1891 PropertyDefinition oldPropertyDefinition = oldPropsMapper.get(propName);
1892 if (oldPropertyDefinition == null) {
1893 log.debug("New property {} received in the data type {}", propName, dataTypeName);
1894 outputPropertiesToAdd.add(propDef);
1897 String oldType = oldPropertyDefinition.getType();
1898 String oldEntryType = getEntryType(oldPropertyDefinition);
1899 String newType = propDef.getType();
1900 String newEntryType = getEntryType(propDef);
1901 if (!oldType.equals(newType)) {
1902 log.debug("Existing property {} in data type {} has a differnet type {} than the new one {}", propName, dataTypeName, oldType,
1906 if (!equalsEntryTypes(oldEntryType, newEntryType)) {
1907 log.debug("Existing property {} in data type {} has a differnet entry type {} than the new one {}", propName, dataTypeName,
1908 oldEntryType, newEntryType);
1916 private boolean equalsEntryTypes(String oldEntryType, String newEntryType) {
1917 if (oldEntryType == null && newEntryType == null) {
1919 } else if (oldEntryType != null && newEntryType != null) {
1920 return oldEntryType.equals(newEntryType);
1926 private String getEntryType(PropertyDefinition oldPropertyDefinition) {
1927 String entryType = null;
1928 SchemaDefinition schema = oldPropertyDefinition.getSchema();
1929 if (schema != null) {
1930 PropertyDataDefinition schemaProperty = schema.getProperty();
1931 if (schemaProperty != null) {
1932 entryType = schemaProperty.getType();
1938 private boolean isDerivedFromNameChanged(String dataTypeName, String newDerivedFromName, String oldDerivedFromName) {
1939 if (newDerivedFromName != null) {
1940 boolean isEqual = newDerivedFromName.equals(oldDerivedFromName);
1942 log.debug("The new datatype {} derived from another data type {} than the existing one {}", dataTypeName, newDerivedFromName,
1943 oldDerivedFromName);
1946 } else if (oldDerivedFromName == null) {
1948 } else {// new=null, old != null
1949 log.debug("The new datatype {} derived from another data type {} than the existing one {}", dataTypeName, newDerivedFromName,
1950 oldDerivedFromName);
1960 public Either<Integer, StorageOperationStatus> increaseAndGetObjInstancePropertyCounter(String instanceId, NodeTypeEnum nodeType) {
1961 Either<JanusGraph, JanusGraphOperationStatus> graphResult = janusGraphGenericDao.getGraph();
1962 if (graphResult.isRight()) {
1963 return Either.right(DaoStatusConverter.convertJanusGraphStatusToStorageStatus(graphResult.right().value()));
1965 Either<JanusGraphVertex, JanusGraphOperationStatus> vertexService = janusGraphGenericDao
1966 .getVertexByProperty(UniqueIdBuilder.getKeyByNodeType(nodeType), instanceId);
1967 if (vertexService.isRight()) {
1968 log.debug("failed to fetch vertex of resource instance for id = {}", instanceId);
1969 return Either.right(DaoStatusConverter.convertJanusGraphStatusToStorageStatus(vertexService.right().value()));
1971 Vertex vertex = vertexService.left().value();
1972 VertexProperty<Object> vertexProperty = vertex.property(GraphPropertiesDictionary.PROPERTY_COUNTER.getProperty());
1973 Integer counter = 0;
1974 if (vertexProperty.isPresent() && vertexProperty.value() != null) {
1975 counter = (Integer) vertexProperty.value();
1978 vertex.property(GraphPropertiesDictionary.PROPERTY_COUNTER.getProperty(), counter);
1979 return Either.left(counter);
1982 public Either<List<PropertyDefinition>, JanusGraphOperationStatus> validatePropertiesUniqueness(
1983 Map<String, PropertyDefinition> inheritedProperties, List<PropertyDefinition> properties) {
1984 Either<List<PropertyDefinition>, JanusGraphOperationStatus> result = Either.left(properties);
1985 for (PropertyDefinition property : properties) {
1986 JanusGraphOperationStatus status = validatePropertyUniqueness(inheritedProperties, property);
1987 if (status != JanusGraphOperationStatus.OK) {
1988 result = Either.right(status);
1996 * Validates uniqueness of examined property by comparing it with properties in propertiesOfType and updates if need type and inner type of the
1999 private JanusGraphOperationStatus validatePropertyUniqueness(Map<String, PropertyDefinition> inheritedProperties, PropertyDefinition property) {
2000 String propertyName = property.getName();
2001 String propertyType = property.getType();
2002 JanusGraphOperationStatus result = JanusGraphOperationStatus.OK;
2003 if (inheritedProperties.containsKey(propertyName)) {
2004 PropertyDefinition defaultProperty = inheritedProperties.get(propertyName);
2005 if (typesMismatch(propertyType, defaultProperty.getType())) {
2006 log.error("#validatePropertyUniqueness - Property with name {} and different type already exists.", propertyName);
2007 result = JanusGraphOperationStatus.PROPERTY_NAME_ALREADY_EXISTS;
2009 property.setType(defaultProperty.getType());
2010 String innerType = defaultProperty.getSchemaType();
2011 PropertyDataDefinition schemaProperty = property.getSchemaProperty();
2012 if (schemaProperty != null) {
2013 schemaProperty.setType(innerType);
2020 private boolean typesMismatch(String type1, String type2) {
2021 return type1 != null && type2 != null && !type2.equals(type1);
2024 public <T extends GraphNode> Either<Map<String, PropertyDefinition>, JanusGraphOperationStatus> getAllTypePropertiesFromAllDerivedFrom(
2025 String nextParentUid, NodeTypeEnum nodeType, Class<T> clazz) {
2026 Map<String, PropertyDefinition> allProperies = new HashMap<>();
2027 return getTypePropertiesFromDerivedFromRecursively(nextParentUid, allProperies, nodeType, clazz);
2030 private <T extends GraphNode> Either<Map<String, PropertyDefinition>, JanusGraphOperationStatus> getTypePropertiesFromDerivedFromRecursively(
2031 String nextParentUid, Map<String, PropertyDefinition> allProperies, NodeTypeEnum nodeType, Class<T> clazz) {
2032 JanusGraphOperationStatus error;
2033 Either<List<ImmutablePair<T, GraphEdge>>, JanusGraphOperationStatus> childrenNodes = janusGraphGenericDao
2034 .getChildrenNodes(UniqueIdBuilder.getKeyByNodeType(nodeType), nextParentUid, GraphEdgeLabels.DERIVED_FROM, nodeType, clazz);
2035 if (childrenNodes.isRight()) {
2036 if (childrenNodes.right().value() != JanusGraphOperationStatus.NOT_FOUND) {
2037 error = childrenNodes.right().value();
2038 log.debug("#getTypePropertiesFromDerivedFromRecursively - Couldn't fetch derived from node with UID {}, error: {}", nextParentUid,
2040 return Either.right(error);
2042 log.debug("#getTypePropertiesFromDerivedFromRecursively - Derived from node is not found with UID {} - this is OK for root.",
2044 return Either.left(allProperies);
2047 Either<Map<String, PropertyDefinition>, JanusGraphOperationStatus> allPropertiesOfTypeRes = findPropertiesOfNode(nodeType, nextParentUid);
2048 if (allPropertiesOfTypeRes.isRight() && !allPropertiesOfTypeRes.right().value().equals(JanusGraphOperationStatus.NOT_FOUND)) {
2049 error = allPropertiesOfTypeRes.right().value();
2051 "#getTypePropertiesFromDerivedFromRecursively - Failed to retrieve properties for node with UID {} from graph. status is {}",
2052 nextParentUid, error);
2053 return Either.right(error);
2054 } else if (allPropertiesOfTypeRes.isLeft()) {
2055 if (allProperies.isEmpty()) {
2056 allProperies.putAll(allPropertiesOfTypeRes.left().value());
2058 allProperies.putAll(allPropertiesOfTypeRes.left().value().entrySet().stream().filter(e -> !allProperies.containsKey(e.getKey()))
2059 .collect(Collectors.toMap(Entry::getKey, Entry::getValue)));
2062 return getTypePropertiesFromDerivedFromRecursively(childrenNodes.left().value().get(0).getLeft().getUniqueId(), allProperies, nodeType,
2067 private JanusGraphOperationStatus updateDataTypePropertyDescriptions(String uniqueId, Map<String, String> newDescriptions) {
2068 if (MapUtils.isNotEmpty(newDescriptions)) {
2069 Either<List<ImmutablePair<JanusGraphVertex, Edge>>, JanusGraphOperationStatus> getDataTypePropertiesRes = janusGraphGenericDao
2070 .getChildrenVertecies(GraphPropertiesDictionary.UNIQUE_ID.getProperty(), uniqueId, GraphEdgeLabels.PROPERTY);
2071 if (getDataTypePropertiesRes.isRight()) {
2072 log.debug("#updateDataTypePropertiesDescriptions - Failed to fetch the property verticies of the Data type {} ", uniqueId);
2073 return getDataTypePropertiesRes.right().value();
2075 getDataTypePropertiesRes.left().value().stream().filter(pair -> newDescriptions.containsKey(getPropertyNameFromEdge(pair)))
2076 .forEach(pair -> setNewDescriptionToVertex(newDescriptions.get(getPropertyNameFromEdge(pair)), pair));
2078 return JanusGraphOperationStatus.OK;
2081 private JanusGraphVertexProperty<String> setNewDescriptionToVertex(String newDescription, ImmutablePair<JanusGraphVertex, Edge> pair) {
2082 return pair.getLeft().property(GraphPropertiesDictionary.DESCRIPTION.getProperty(), newDescription);
2085 private String getPropertyNameFromEdge(ImmutablePair<JanusGraphVertex, Edge> pair) {
2086 return (String) pair.getRight().property(GraphPropertiesDictionary.NAME.getProperty()).value();
2089 private Map<String, String> getPropertyDescriptionsToUpdate(List<PropertyDefinition> oldProperties, List<PropertyDefinition> newProperties) {
2090 Map<String, PropertyDefinition> newPropertiesMap = newProperties.stream().collect(Collectors.toMap(PropertyDefinition::getName, p -> p));
2091 return oldProperties.stream()
2092 .filter(p -> newPropertiesMap.containsKey(p.getName()) && !descriptionsEqual(p, newPropertiesMap.get(p.getName())))
2093 .collect(Collectors.toMap(PropertyDefinition::getName, p -> newPropertiesMap.get(p.getName()).getDescription()));
2096 private boolean descriptionsEqual(PropertyDefinition property, PropertyDefinition otherProperty) {
2097 if (StringUtils.isEmpty(property.getDescription()) && StringUtils.isEmpty(otherProperty.getDescription())) {
2100 if (StringUtils.isNotEmpty(property.getDescription()) && StringUtils.isEmpty(otherProperty.getDescription())) {
2103 if (StringUtils.isEmpty(property.getDescription()) && StringUtils.isNotEmpty(otherProperty.getDescription())) {
2106 return property.getDescription().equals(otherProperty.getDescription());
2109 public static class PropertyConstraintSerialiser implements JsonSerializer<PropertyConstraint> {
2112 public JsonElement serialize(PropertyConstraint src, Type typeOfSrc, JsonSerializationContext context) {
2113 JsonParser parser = new JsonParser();
2114 JsonObject result = new JsonObject();
2115 JsonArray jsonArray = new JsonArray();
2116 if (src instanceof InRangeConstraint) {
2117 InRangeConstraint rangeConstraint = (InRangeConstraint) src;
2118 jsonArray.add(parser.parse(rangeConstraint.getRangeMinValue()));
2119 jsonArray.add(parser.parse(rangeConstraint.getRangeMaxValue()));
2120 result.add("inRange", jsonArray);
2121 } else if (src instanceof GreaterThanConstraint) {
2122 GreaterThanConstraint greaterThanConstraint = (GreaterThanConstraint) src;
2123 jsonArray.add(parser.parse(greaterThanConstraint.getGreaterThan()));
2124 result.add("greaterThan", jsonArray);
2125 } else if (src instanceof LessOrEqualConstraint) {
2126 LessOrEqualConstraint lessOrEqualConstraint = (LessOrEqualConstraint) src;
2127 jsonArray.add(parser.parse(lessOrEqualConstraint.getLessOrEqual()));
2128 result.add("lessOrEqual", jsonArray);
2130 log.warn("PropertyConstraint {} is not supported. Ignored.", src.getClass().getName());
2136 public static class PropertyConstraintDeserialiser implements JsonDeserializer<PropertyConstraint> {
2138 private static final String THE_VALUE_OF_GREATER_THAN_CONSTRAINT_IS_NULL = "The value of GreaterThanConstraint is null";
2141 public PropertyConstraint deserialize(JsonElement json, Type typeOfT, JsonDeserializationContext context) throws JsonParseException {
2142 PropertyConstraint propertyConstraint = null;
2143 Set<Entry<String, JsonElement>> set = json.getAsJsonObject().entrySet();
2144 if (set.size() == 1) {
2145 Entry<String, JsonElement> element = set.iterator().next();
2146 String key = element.getKey();
2147 JsonElement value = element.getValue();
2148 ConstraintType constraintType = ConstraintType.findByType(key).orElse(null);
2149 if (constraintType == null) {
2150 log.warn("ConstraintType was not found for constraint name:{}", key);
2152 switch (constraintType) {
2154 if (value != null) {
2155 if (value instanceof JsonArray) {
2156 JsonArray rangeArray = (JsonArray) value;
2157 if (rangeArray.size() != 2) {
2158 log.error("The range constraint content is invalid. value = {}", value);
2160 InRangeConstraint rangeConstraint = new InRangeConstraint();
2161 String minValue = rangeArray.get(0).getAsString();
2163 JsonElement maxElement = rangeArray.get(1);
2164 if (maxElement.isJsonNull()) {
2165 maxValue = String.valueOf(maxElement.getAsJsonNull());
2167 maxValue = maxElement.getAsString();
2169 rangeConstraint.setRangeMinValue(minValue);
2170 rangeConstraint.setRangeMaxValue(maxValue);
2171 propertyConstraint = rangeConstraint;
2175 log.warn(THE_VALUE_OF_GREATER_THAN_CONSTRAINT_IS_NULL);
2179 if (value != null) {
2180 String asString = value.getAsString();
2181 log.debug("Before adding value to GreaterThanConstraint object. value = {}", asString);
2182 propertyConstraint = new GreaterThanConstraint(asString);
2185 log.warn(THE_VALUE_OF_GREATER_THAN_CONSTRAINT_IS_NULL);
2189 if (value != null) {
2190 String asString = value.getAsString();
2191 log.debug("Before adding value to LessThanConstraint object. value = {}", asString);
2192 propertyConstraint = new LessThanConstraint(asString);
2195 log.warn("The value of LessThanConstraint is null");
2198 case GREATER_OR_EQUAL:
2199 if (value != null) {
2200 String asString = value.getAsString();
2201 log.debug("Before adding value to GreaterThanConstraint object. value = {}", asString);
2202 propertyConstraint = new GreaterOrEqualConstraint(asString);
2205 log.warn("The value of GreaterOrEqualConstraint is null");
2209 if (value != null) {
2210 String asString = value.getAsString();
2211 log.debug("Before adding value to LessOrEqualConstraint object. value = {}", asString);
2212 propertyConstraint = new LessOrEqualConstraint(asString);
2214 log.warn(THE_VALUE_OF_GREATER_THAN_CONSTRAINT_IS_NULL);
2218 if (value != null) {
2219 JsonArray rangeArray = (JsonArray) value;
2220 if (rangeArray.size() == 0) {
2221 log.error("The valid values constraint content is invalid. value = {}", value);
2223 ValidValuesConstraint vvConstraint = new ValidValuesConstraint();
2224 List<String> validValues = new ArrayList<>();
2225 for (JsonElement jsonElement : rangeArray) {
2226 String item = jsonElement.getAsString();
2227 validValues.add(item);
2229 vvConstraint.setValidValues(validValues);
2230 propertyConstraint = vvConstraint;
2235 if (value != null) {
2236 int asInt = value.getAsInt();
2237 log.debug("Before adding value to Min Length object. value = {}", asInt);
2238 propertyConstraint = new MinLengthConstraint(asInt);
2241 log.warn("The value of MinLengthConstraint is null");
2245 log.warn("Key {} is not supported. Ignored.", key);
2249 return propertyConstraint;
2253 public static class PropertyConstraintJacksonDeserializer extends com.fasterxml.jackson.databind.JsonDeserializer<PropertyConstraint> {
2256 public PropertyConstraint deserialize(com.fasterxml.jackson.core.JsonParser json, DeserializationContext context) throws IOException {
2257 ObjectCodec oc = json.getCodec();
2258 JsonNode node = oc.readTree(json);