[SDC] rebase 1710 code
[sdc.git] / catalog-model / src / main / java / org / openecomp / sdc / be / model / jsontitan / operations / ToscaElementLifecycleOperation.java
1 /*-
2  * ============LICENSE_START=======================================================
3  * SDC
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
10  * 
11  *      http://www.apache.org/licenses/LICENSE-2.0
12  * 
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=========================================================
19  */
20
21 package org.openecomp.sdc.be.model.jsontitan.operations;
22
23 import java.util.ArrayList;
24 import java.util.EnumMap;
25 import java.util.HashMap;
26 import java.util.Iterator;
27 import java.util.List;
28 import java.util.Map;
29 import java.util.Optional;
30 import java.util.stream.Collectors;
31
32 import org.apache.commons.collections.CollectionUtils;
33 import org.apache.commons.collections.MapUtils;
34 import org.apache.commons.lang.StringUtils;
35 import org.apache.commons.lang3.tuple.ImmutablePair;
36 import org.apache.tinkerpop.gremlin.structure.Direction;
37 import org.apache.tinkerpop.gremlin.structure.Edge;
38 import org.apache.tinkerpop.gremlin.structure.Vertex;
39 import org.openecomp.sdc.be.config.ConfigurationManager;
40 import org.openecomp.sdc.be.dao.jsongraph.GraphVertex;
41 import org.openecomp.sdc.be.dao.jsongraph.types.EdgeLabelEnum;
42 import org.openecomp.sdc.be.dao.jsongraph.types.EdgePropertyEnum;
43 import org.openecomp.sdc.be.dao.jsongraph.types.JsonParseFlagEnum;
44 import org.openecomp.sdc.be.dao.jsongraph.types.VertexTypeEnum;
45 import org.openecomp.sdc.be.dao.jsongraph.utils.IdBuilderUtils;
46 import org.openecomp.sdc.be.dao.jsongraph.utils.JsonParserUtils;
47 import org.openecomp.sdc.be.dao.neo4j.GraphEdgeLabels;
48 import org.openecomp.sdc.be.dao.titan.TitanOperationStatus;
49 import org.openecomp.sdc.be.datatypes.elements.ArtifactDataDefinition;
50 import org.openecomp.sdc.be.datatypes.elements.ComponentInstanceDataDefinition;
51 import org.openecomp.sdc.be.datatypes.elements.CompositionDataDefinition;
52 import org.openecomp.sdc.be.datatypes.elements.GroupDataDefinition;
53 import org.openecomp.sdc.be.datatypes.elements.GroupInstanceDataDefinition;
54 import org.openecomp.sdc.be.datatypes.elements.MapArtifactDataDefinition;
55 import org.openecomp.sdc.be.datatypes.elements.MapGroupsDataDefinition;
56 import org.openecomp.sdc.be.datatypes.elements.MapPropertiesDataDefinition;
57 import org.openecomp.sdc.be.datatypes.elements.PropertyDataDefinition;
58 import org.openecomp.sdc.be.datatypes.enums.ComponentTypeEnum;
59 import org.openecomp.sdc.be.datatypes.enums.GraphPropertyEnum;
60 import org.openecomp.sdc.be.datatypes.enums.JsonPresentationFields;
61 import org.openecomp.sdc.be.datatypes.enums.OriginTypeEnum;
62 import org.openecomp.sdc.be.datatypes.tosca.ToscaDataDefinition;
63 import org.openecomp.sdc.be.model.ComponentParametersView;
64 import org.openecomp.sdc.be.model.DistributionStatusEnum;
65 import org.openecomp.sdc.be.model.LifecycleStateEnum;
66 import org.openecomp.sdc.be.model.User;
67 import org.openecomp.sdc.be.model.jsontitan.datamodel.TopologyTemplate;
68 import org.openecomp.sdc.be.model.jsontitan.datamodel.ToscaElement;
69 import org.openecomp.sdc.be.model.jsontitan.datamodel.ToscaElementTypeEnum;
70 import org.openecomp.sdc.be.model.jsontitan.enums.JsonConstantKeysEnum;
71 import org.openecomp.sdc.be.model.operations.api.StorageOperationStatus;
72 import org.openecomp.sdc.be.model.operations.impl.DaoStatusConverter;
73 import org.openecomp.sdc.be.model.operations.impl.UniqueIdBuilder;
74 import org.openecomp.sdc.common.jsongraph.util.CommonUtility;
75 import org.openecomp.sdc.common.jsongraph.util.CommonUtility.LogLevelEnum;
76 import org.slf4j.Logger;
77 import org.slf4j.LoggerFactory;
78
79 import fj.data.Either;
80
81 @org.springframework.stereotype.Component("tosca-element-lifecycle-operation")
82
83 /**
84  * Allows to perform lifecycle operations: checkin, checkout, submit for testing, start certification and certification process for tosca element
85  */
86 public class ToscaElementLifecycleOperation extends BaseOperation {
87
88         private static final String FAILED_TO_GET_VERTICES = "Failed to get vertices by id {}. Status is {}. ";
89         public static final String VERSION_DELIMETER = ".";
90         public static final String VERSION_DELIMETER_REGEXP = "\\.";
91
92         private static Logger logger = LoggerFactory.getLogger(ToscaElementLifecycleOperation.class.getName());
93
94         /**
95          * Performs changing a lifecycle state of tosca element from "checked out" or "ready for certification" to "checked in"
96          * 
97          * @param currState
98          * @param toscaElementId
99          * @param modifierId
100          * @param ownerId
101          * @return
102          */
103         public Either<ToscaElement, StorageOperationStatus> checkinToscaELement(LifecycleStateEnum currState, String toscaElementId, String modifierId, String ownerId) {
104                 Either<GraphVertex, StorageOperationStatus> updateResult = null;
105                 Either<ToscaElement, StorageOperationStatus> result = null;
106                 Map<String, GraphVertex> vertices = null;
107                 ToscaElementOperation operation;
108                 try {
109                         Either<Map<String, GraphVertex>, TitanOperationStatus> getVerticesRes = titanDao.getVerticesByUniqueIdAndParseFlag(prepareParametersToGetVerticesForCheckin(toscaElementId, modifierId, ownerId));
110                         if (getVerticesRes.isRight()) {
111                                 CommonUtility.addRecordToLog(logger, LogLevelEnum.DEBUG, FAILED_TO_GET_VERTICES, toscaElementId);
112                                 updateResult = Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(getVerticesRes.right().value()));
113                         } else {
114                                 vertices = getVerticesRes.left().value();
115                                 updateResult = checkinToscaELement(currState, vertices.get(toscaElementId), vertices.get(ownerId), vertices.get(modifierId), LifecycleStateEnum.NOT_CERTIFIED_CHECKIN);
116                         }
117                         if (updateResult.isLeft()) {
118                                 ComponentParametersView componentParametersView = buildComponentParametersViewAfterCheckin();
119                                 operation = getToscaElementOperation(vertices.get(toscaElementId).getLabel());
120                                 result = operation.getToscaElement(updateResult.left().value().getUniqueId(), componentParametersView);
121                                 if (result.isRight()) {
122                                         CommonUtility.addRecordToLog(logger, LogLevelEnum.DEBUG, "Failed to get updated tosca element {}. Status is {}", toscaElementId, result.right().value());
123                                 }
124                         } else {
125                                 result = Either.right(updateResult.right().value());
126                         }
127                 } catch (Exception e) {
128                         CommonUtility.addRecordToLog(logger, LogLevelEnum.DEBUG, "Exception occured during checkin of tosca element {}. {} ", toscaElementId, e.getMessage());
129                 }
130                 return result;
131         }
132
133         /**
134          * Returns vertex presenting owner of tosca element specified by uniqueId
135          * 
136          * @param toscaElement
137          * @return
138          */
139         public Either<User, StorageOperationStatus> getToscaElementOwner(String toscaElementId) {
140                 Either<User, StorageOperationStatus> result = null;
141                 GraphVertex toscaElement = null;
142                 Either<GraphVertex, TitanOperationStatus> getToscaElementRes = titanDao.getVertexById(toscaElementId, JsonParseFlagEnum.NoParse);
143                 if (getToscaElementRes.isRight()) {
144                         result = Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(getToscaElementRes.right().value()));
145                 }
146                 if (result == null) {
147                         toscaElement = getToscaElementRes.left().value();
148                         Iterator<Vertex> vertices = toscaElement.getVertex().vertices(Direction.IN, EdgeLabelEnum.STATE.name());
149                         if (vertices == null || !vertices.hasNext()) {
150                                 result = Either.right(StorageOperationStatus.NOT_FOUND);
151                         } else {
152                                 result = Either.left(convertToUser(vertices.next()));
153                         }
154                 }
155                 return result;
156         }
157
158         /**
159          * Returns vertex presenting owner of tosca element specified by uniqueId
160          * 
161          * @param toscaElement
162          * @return
163          */
164         public Either<User, StorageOperationStatus> getToscaElementOwner(GraphVertex toscaElement) {
165                 Either<User, StorageOperationStatus> result = null;
166                 Iterator<Vertex> vertices = toscaElement.getVertex().vertices(Direction.IN, EdgeLabelEnum.STATE.name());
167                 if (vertices == null || !vertices.hasNext()) {
168                         result = Either.right(StorageOperationStatus.NOT_FOUND);
169                 } else {
170                         result = Either.left(convertToUser(vertices.next()));
171                 }
172                 return result;
173         }
174
175         /**
176          * Performs checkout of a tosca element
177          * 
178          * @param toscaElementId
179          * @param modifierId
180          * @param ownerId
181          * @param currState
182          * @return
183          */
184         public Either<ToscaElement, StorageOperationStatus> checkoutToscaElement(String toscaElementId, String modifierId, String ownerId) {
185                 Either<ToscaElement, StorageOperationStatus> result = null;
186                 Map<String, GraphVertex> vertices = null;
187                 try {
188                         Either<Map<String, GraphVertex>, TitanOperationStatus> getVerticesRes = titanDao.getVerticesByUniqueIdAndParseFlag(prepareParametersToGetVerticesForCheckout(toscaElementId, modifierId, ownerId));
189                         if (getVerticesRes.isRight()) {
190                                 CommonUtility.addRecordToLog(logger, LogLevelEnum.DEBUG, FAILED_TO_GET_VERTICES, toscaElementId);
191                                 result = Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(getVerticesRes.right().value()));
192                         }
193                         if (result == null) {
194                                 vertices = getVerticesRes.left().value();
195                                 // update previous component if not certified
196                                 StorageOperationStatus status = updatePreviousVersion(vertices.get(toscaElementId), vertices.get(ownerId));
197                                 if (status != StorageOperationStatus.OK) {
198                                         CommonUtility.addRecordToLog(logger, LogLevelEnum.DEBUG, "Failed to update vertex with id {} . Status is {}. ", status);
199                                         result = Either.right(status);
200                                 }
201                         }
202                         if (result == null) {
203                                 result = cloneToscaElementForCheckout(vertices.get(toscaElementId), vertices.get(modifierId));
204                                 if (result.isRight()) {
205                                         CommonUtility.addRecordToLog(logger, LogLevelEnum.DEBUG, "Failed to checkout tosca element {}. Status is {} ", toscaElementId, result.right().value());
206                                 }
207
208                         }
209                 } catch (Exception e) {
210                         CommonUtility.addRecordToLog(logger, LogLevelEnum.DEBUG, "Exception occured during checkout tosca element {}. {}", toscaElementId, e.getMessage());
211                 }
212                 return result;
213         }
214
215         /**
216          * Performs undo checkout for tosca element
217          * 
218          * @param toscaElementId
219          * @return
220          */
221         public Either<ToscaElement, StorageOperationStatus> undoCheckout(String toscaElementId) {
222                 Either<ToscaElement, StorageOperationStatus> result = null;
223                 Either<GraphVertex, TitanOperationStatus> getToscaElementRes = null;
224                 Iterator<Edge> nextVersionComponentIter = null;
225                 ToscaElementOperation operation;
226                 try {
227                         getToscaElementRes = titanDao.getVertexById(toscaElementId, JsonParseFlagEnum.ParseMetadata);
228                         if (getToscaElementRes.isRight()) {
229                                 CommonUtility.addRecordToLog(logger, LogLevelEnum.DEBUG, FAILED_TO_GET_VERTICES, toscaElementId);
230                                 result = Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(getToscaElementRes.right().value()));
231                         }
232                         if (result == null && hasPreviousVersion(getToscaElementRes.left().value())) {
233                                 // find previous version
234                                 nextVersionComponentIter = getToscaElementRes.left().value().getVertex().edges(Direction.IN, EdgeLabelEnum.VERSION.name());
235                                 if (nextVersionComponentIter == null || !nextVersionComponentIter.hasNext()) {
236                                         CommonUtility.addRecordToLog(logger, LogLevelEnum.DEBUG, "Failed to fetch previous version of tosca element with name {}. ", getToscaElementRes.left().value().getMetadataProperty(GraphPropertyEnum.NORMALIZED_NAME).toString());
237                                         result = Either.right(StorageOperationStatus.NOT_FOUND);
238                                 }
239                                 if (result == null) {
240                                         StorageOperationStatus updateOldResourceResult = updateOldToscaElementBeforeUndoCheckout(nextVersionComponentIter.next().outVertex());
241                                         if (updateOldResourceResult != StorageOperationStatus.OK) {
242                                                 result = Either.right(updateOldResourceResult);
243                                         }
244                                 }
245                         }
246                         if (result == null) {
247                                 operation = getToscaElementOperation(getToscaElementRes.left().value().getLabel());
248                                 result = operation.deleteToscaElement(getToscaElementRes.left().value());
249                         }
250                 } catch (Exception e) {
251                         CommonUtility.addRecordToLog(logger, LogLevelEnum.DEBUG, "Exception occured during undo checkout tosca element {}. {}", toscaElementId, e.getMessage());
252                 }
253                 return result;
254         }
255
256         private boolean hasPreviousVersion(GraphVertex toscaElementVertex) {
257                 boolean hasPreviousVersion = true;
258                 String version = (String) toscaElementVertex.getMetadataProperty(GraphPropertyEnum.VERSION);
259                 if (StringUtils.isEmpty(version) || version.equals("0.1"))
260                         hasPreviousVersion = false;
261                 return hasPreviousVersion;
262         }
263
264         /**
265          * Performs request certification for tosca element
266          * 
267          * @param toscaElementId
268          * @param modifierId
269          * @param ownerId
270          * @return
271          */
272         public Either<ToscaElement, StorageOperationStatus> requestCertificationToscaElement(String toscaElementId, String modifierId, String ownerId) {
273                 Either<GraphVertex, StorageOperationStatus> resultUpdate = null;
274                 Either<ToscaElement, StorageOperationStatus> result = null;
275                 GraphVertex toscaElement = null;
276                 GraphVertex modifier = null;
277                 GraphVertex owner;
278                 try {
279                         Either<Map<String, GraphVertex>, TitanOperationStatus> getVerticesRes = titanDao.getVerticesByUniqueIdAndParseFlag(prepareParametersToGetVerticesForRequestCertification(toscaElementId, modifierId, ownerId));
280                         if (getVerticesRes.isRight()) {
281                                 CommonUtility.addRecordToLog(logger, LogLevelEnum.DEBUG, FAILED_TO_GET_VERTICES, toscaElementId);
282                                 result = Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(getVerticesRes.right().value()));
283                         }
284                         if (result == null) {
285                                 toscaElement = getVerticesRes.left().value().get(toscaElementId);
286                                 modifier = getVerticesRes.left().value().get(modifierId);
287                                 owner = getVerticesRes.left().value().get(ownerId);
288
289                                 StorageOperationStatus status = handleRelationsUponRequestForCertification(toscaElement, modifier, owner);
290                                 if (status != StorageOperationStatus.OK) {
291                                         CommonUtility.addRecordToLog(logger, LogLevelEnum.DEBUG, "Failed to handle relations on certification request for tosca element {}. Status is {}. ", toscaElement.getUniqueId(), status);
292                                 }
293                         }
294                         if (result == null) {
295                                 LifecycleStateEnum nextState = LifecycleStateEnum.READY_FOR_CERTIFICATION;
296
297                                 toscaElement.addMetadataProperty(GraphPropertyEnum.STATE, nextState.name());
298                                 toscaElement.setJsonMetadataField(JsonPresentationFields.LAST_UPDATE_DATE, System.currentTimeMillis());
299
300                                 resultUpdate = updateToscaElementVertexMetadataPropertiesAndJson(toscaElement);
301                                 if (resultUpdate.isRight()) {
302                                         CommonUtility.addRecordToLog(logger, LogLevelEnum.DEBUG, "Failed to set lifecycle for tosca elememt {} to state {}, error: {}", toscaElement.getUniqueId(), nextState, resultUpdate.right().value());
303                                         result = Either.right(resultUpdate.right().value());
304                                 }
305                         }
306                         if (result == null) {
307                                 ToscaElementOperation operation = getToscaElementOperation(toscaElement.getLabel());
308                                 result = operation.getToscaElement(toscaElement.getUniqueId());
309                         }
310                         return result;
311
312                 } catch (Exception e) {
313                         CommonUtility.addRecordToLog(logger, LogLevelEnum.DEBUG, "Exception occured during request certification tosca element {}. {}", toscaElementId, e.getMessage());
314                 }
315                 return result;
316         }
317
318         /**
319          * Starts certification of tosca element
320          * 
321          * @param toscaElementId
322          * @param modifierId
323          * @param ownerId
324          * @return
325          */
326         public Either<ToscaElement, StorageOperationStatus> startCertificationToscaElement(String toscaElementId, String modifierId, String ownerId) {
327                 Either<ToscaElement, StorageOperationStatus> result = null;
328                 Either<GraphVertex, StorageOperationStatus> resultUpdate = null;
329                 GraphVertex toscaElement = null;
330                 GraphVertex modifier = null;
331                 GraphVertex owner;
332                 try {
333                         Either<Map<String, GraphVertex>, TitanOperationStatus> getVerticesRes = titanDao.getVerticesByUniqueIdAndParseFlag(prepareParametersToGetVerticesForRequestCertification(toscaElementId, modifierId, ownerId));
334                         if (getVerticesRes.isRight()) {
335                                 CommonUtility.addRecordToLog(logger, LogLevelEnum.DEBUG, FAILED_TO_GET_VERTICES, toscaElementId);
336                                 result = Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(getVerticesRes.right().value()));
337                         }
338                         if (result == null) {
339                                 toscaElement = getVerticesRes.left().value().get(toscaElementId);
340                                 modifier = getVerticesRes.left().value().get(modifierId);
341                                 owner = getVerticesRes.left().value().get(ownerId);
342
343                                 StorageOperationStatus status = handleRelationsUponCertification(toscaElement, modifier, owner);
344                                 if (status != StorageOperationStatus.OK) {
345                                         CommonUtility.addRecordToLog(logger, LogLevelEnum.DEBUG, "Failed to handle relations during certification of tosca element {}. Status is {}. ", toscaElement.getUniqueId(), status);
346                                 }
347                         }
348                         if (result == null) {
349                                 LifecycleStateEnum nextState = LifecycleStateEnum.CERTIFICATION_IN_PROGRESS;
350
351                                 toscaElement.addMetadataProperty(GraphPropertyEnum.STATE, nextState.name());
352                                 toscaElement.setJsonMetadataField(JsonPresentationFields.LAST_UPDATE_DATE, System.currentTimeMillis());
353
354                                 resultUpdate = updateToscaElementVertexMetadataPropertiesAndJson(toscaElement);
355                                 if (resultUpdate.isRight()) {
356                                         CommonUtility.addRecordToLog(logger, LogLevelEnum.DEBUG, "Couldn't set lifecycle for component {} to state {}, error: {}", toscaElement.getUniqueId(), nextState, resultUpdate.right().value());
357                                         result = Either.right(resultUpdate.right().value());
358                                 }
359                         }
360                         if (result == null) {
361                                 ToscaElementOperation operation = getToscaElementOperation(toscaElement.getLabel());
362                                 result = operation.getToscaElement(toscaElement.getUniqueId());
363                         }
364                 } catch (Exception e) {
365                         CommonUtility.addRecordToLog(logger, LogLevelEnum.DEBUG, "Exception occured during start certification tosca element {}. {}", toscaElementId, e.getMessage());
366                 }
367                 return result;
368         }
369
370         public Either<ToscaElement, StorageOperationStatus> certifyToscaElement(String toscaElementId, String modifierId, String ownerId) {
371                 Either<ToscaElement, StorageOperationStatus> result = null;
372                 Either<GraphVertex, StorageOperationStatus> cloneRes = null;
373                 GraphVertex toscaElement = null;
374                 GraphVertex modifier = null;
375                 GraphVertex certifiedToscaElement = null;
376                 Integer majorVersion = null;
377
378                 StorageOperationStatus status;
379                 try {
380                         Either<Map<String, GraphVertex>, TitanOperationStatus> getVerticesRes = titanDao.getVerticesByUniqueIdAndParseFlag(prepareParametersToGetVerticesForRequestCertification(toscaElementId, modifierId, ownerId));
381                         if (getVerticesRes.isRight()) {
382                                 CommonUtility.addRecordToLog(logger, LogLevelEnum.DEBUG, FAILED_TO_GET_VERTICES, toscaElementId);
383                                 result = Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(getVerticesRes.right().value()));
384                         }
385                         if (result == null) {
386                                 toscaElement = getVerticesRes.left().value().get(toscaElementId);
387                                 modifier = getVerticesRes.left().value().get(modifierId);
388                                 majorVersion = getMajorVersion((String) toscaElement.getMetadataProperty(GraphPropertyEnum.VERSION));
389                                 status = handleRelationsOfPreviousToscaElementBeforeCertifying(toscaElement, modifier, majorVersion);
390                                 if (status != StorageOperationStatus.OK) {
391                                         CommonUtility.addRecordToLog(logger, LogLevelEnum.DEBUG, "Failed to handle relations of previous tosca element before certifying {}. Status is {}. ", toscaElement.getUniqueId(), status);
392                                 }
393                         }
394                         if (result == null) {
395                                 cloneRes = cloneToscaElementForCertify(toscaElement, modifier, majorVersion);
396                                 if (cloneRes.isRight()) {
397                                         CommonUtility.addRecordToLog(logger, LogLevelEnum.DEBUG, "Failed to clone tosca element during certification. ");
398                                         result = Either.right(cloneRes.right().value());
399                                 }
400                         }
401                         if (result == null) {
402                                 certifiedToscaElement = cloneRes.left().value();
403                                 status = handleRelationsOfNewestCertifiedToscaElement(toscaElement, certifiedToscaElement);
404                                 if (status != StorageOperationStatus.OK) {
405                                         CommonUtility.addRecordToLog(logger, LogLevelEnum.DEBUG, "Failed to handle relations of newest certified tosca element {}. Status is {}. ", certifiedToscaElement.getUniqueId(), status);
406                                 }
407                         }
408                         if (result == null) {
409                                 return getToscaElementOperation(toscaElement.getLabel()).getToscaElement(certifiedToscaElement.getUniqueId());
410                         }
411                 } catch (Exception e) {
412                         CommonUtility.addRecordToLog(logger, LogLevelEnum.DEBUG, "Exception occured during certification tosca element {}. {}", toscaElementId, e.getMessage());
413                 }
414                 return result;
415         }
416
417         /**
418          * Deletes (marks as deleted) all tosca elements according received name and uuid
419          * 
420          * @param vertexType
421          * @param componentType
422          * @param componentName
423          * @param uuid
424          * @return
425          */
426         public Either<Boolean, StorageOperationStatus> deleteOldToscaElementVersions(VertexTypeEnum vertexType, ComponentTypeEnum componentType, String componentName, String uuid) {
427
428                 Either<Boolean, StorageOperationStatus> result = null;
429                 ToscaElementOperation operation = getToscaElementOperation(componentType);
430
431                 try {
432                         Map<GraphPropertyEnum, Object> properties = new EnumMap<>(GraphPropertyEnum.class);
433                         properties.put(GraphPropertyEnum.UUID, uuid);
434                         properties.put(GraphPropertyEnum.NAME, componentName);
435                         Either<List<GraphVertex>, TitanOperationStatus> getToscaElementsRes = titanDao.getByCriteria(vertexType, properties, JsonParseFlagEnum.ParseMetadata);
436                         if (getToscaElementsRes.isRight()) {
437                                 result = Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(getToscaElementsRes.right().value()));
438                         }
439                         if (result == null) {
440                                 result = markToscaElementsAsDeleted(operation, getToscaElementsRes.left().value());
441                         }
442                         if (result == null) {
443                                 result = Either.left(true);
444                         }
445                 } catch (Exception e) {
446                         CommonUtility.addRecordToLog(logger, LogLevelEnum.DEBUG, "Exception occured during deleteng all tosca elements by UUID {} and name {}. {} ", uuid, componentName, e.getMessage());
447                 }
448                 return result;
449         }
450
451         /**
452          * Performs cancelation or failure of certification for received tosca element
453          * 
454          * @param toscaElementId
455          * @param modifierId
456          * @param ownerId
457          * @param nextState
458          * @return
459          */
460         public Either<ToscaElement, StorageOperationStatus> cancelOrFailCertification(String toscaElementId, String modifierId, String ownerId, LifecycleStateEnum nextState) {
461                 Either<ToscaElement, StorageOperationStatus> result = null;
462                 StorageOperationStatus status;
463                 ToscaElementOperation operation = null;
464                 GraphVertex toscaElement = null;
465                 GraphVertex modifier = null;
466                 try {
467                         Either<Map<String, GraphVertex>, TitanOperationStatus> getVerticesRes = titanDao.getVerticesByUniqueIdAndParseFlag(prepareParametersToGetVerticesForRequestCertification(toscaElementId, modifierId, ownerId));
468                         if (getVerticesRes.isRight()) {
469                                 CommonUtility.addRecordToLog(logger, LogLevelEnum.DEBUG, FAILED_TO_GET_VERTICES, toscaElementId);
470                                 result = Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(getVerticesRes.right().value()));
471                         }
472                         if (result == null) {
473                                 toscaElement = getVerticesRes.left().value().get(toscaElementId);
474                                 modifier = getVerticesRes.left().value().get(modifierId);
475                                 operation = getToscaElementOperation(toscaElement.getLabel());
476                                 toscaElement.setJsonMetadataField(JsonPresentationFields.LAST_UPDATE_DATE, System.currentTimeMillis());
477                                 toscaElement.setJsonMetadataField(JsonPresentationFields.USER_ID_LAST_UPDATER, modifier.getUniqueId());
478                                 toscaElement.addMetadataProperty(GraphPropertyEnum.STATE, nextState.name());
479
480                                 Either<GraphVertex, TitanOperationStatus> updateVertexRes = titanDao.updateVertex(toscaElement);
481                                 if (updateVertexRes.isRight()) {
482                                         CommonUtility.addRecordToLog(logger, LogLevelEnum.DEBUG, "Failed to update vertex {} . Status is {}. ", toscaElementId, updateVertexRes.right().value());
483                                         result = Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(updateVertexRes.right().value()));
484                                 }
485                         }
486                         if (result == null) {
487                                 // cancel certification process
488                                 status = handleRelationsUponCancelCertification(toscaElement, nextState);
489                                 if (status != StorageOperationStatus.OK) {
490                                         CommonUtility.addRecordToLog(logger, LogLevelEnum.DEBUG, "Failed to handle relations upon cancel certification {}. Status is {}. ", toscaElement.getUniqueId(), status);
491                                 }
492                         }
493                         if (result == null) {
494                                 // fail certification
495                                 status = handleRelationsUponFailCertification(toscaElement, nextState);
496                                 if (status != StorageOperationStatus.OK) {
497                                         CommonUtility.addRecordToLog(logger, LogLevelEnum.DEBUG, "Failed to handle relations upon fail certification {}. Status is {}. ", toscaElement.getUniqueId(), status);
498                                 }
499                         }
500                         if (result == null) {
501                                 result = operation.getToscaElement(toscaElementId);
502                         }
503                 } catch (Exception e) {
504                         CommonUtility.addRecordToLog(logger, LogLevelEnum.DEBUG, "Exception occured during cancel or fail certification of tosca element {}. {}. ", toscaElementId, e.getMessage());
505                 }
506                 return result;
507         }
508
509         public Either<GraphVertex, TitanOperationStatus> findUser(String userId) {
510                 return findUserVertex(userId);
511         }
512
513         private Either<Boolean, StorageOperationStatus> markToscaElementsAsDeleted(ToscaElementOperation operation, List<GraphVertex> toscaElements) {
514                 Either<Boolean, StorageOperationStatus> result = Either.left(true);
515                 for (GraphVertex resourceToDelete : toscaElements) {
516                         if (!((String) resourceToDelete.getJsonMetadataField(JsonPresentationFields.LIFECYCLE_STATE)).equals(LifecycleStateEnum.CERTIFIED.name())) {
517                                 Either<GraphVertex, StorageOperationStatus> deleteElementRes = operation.markComponentToDelete(resourceToDelete);
518                                 if (deleteElementRes.isRight()) {
519                                         CommonUtility.addRecordToLog(logger, LogLevelEnum.DEBUG, "Failed to delete tosca element {}. Status is {}. ", resourceToDelete.getUniqueId(), deleteElementRes.right().value());
520                                         result = Either.right(deleteElementRes.right().value());
521                                         break;
522                                 }
523                         }
524                 }
525                 return result;
526         }
527
528         private StorageOperationStatus handleRelationsOfNewestCertifiedToscaElement(GraphVertex toscaElement, GraphVertex certifiedToscaElement) {
529                 StorageOperationStatus result = null;
530                 Edge foundEdge = null;
531                 Iterator<Edge> certReqUserEdgeIter = null;
532                 // add rfc relation to preserve follower information
533                 // get user of certification request
534                 certReqUserEdgeIter = toscaElement.getVertex().edges(Direction.IN, GraphEdgeLabels.LAST_STATE.name());
535                 if (certReqUserEdgeIter == null || !certReqUserEdgeIter.hasNext()) {
536                         CommonUtility.addRecordToLog(logger, LogLevelEnum.DEBUG, "Failed to find rfc relation during certification clone. ");
537                         result = StorageOperationStatus.NOT_FOUND;
538                 }
539                 if (result == null) {
540                         TitanOperationStatus createVersionEdgeStatus = titanDao.createEdge(toscaElement, certifiedToscaElement, EdgeLabelEnum.VERSION, new HashMap<>());
541                         if (createVersionEdgeStatus != TitanOperationStatus.OK) {
542                                 CommonUtility.addRecordToLog(logger, LogLevelEnum.DEBUG, "Failed to create version edge from last element {} to new certified element {}. status=", toscaElement.getUniqueId(),certifiedToscaElement.getUniqueId(), createVersionEdgeStatus);
543                                 result = DaoStatusConverter.convertTitanStatusToStorageStatus(createVersionEdgeStatus);
544                         }
545                 }
546                 if(result == null){
547
548                         while (certReqUserEdgeIter.hasNext()) {
549                                 Edge edge = certReqUserEdgeIter.next();
550                                 if (((String) titanDao.getProperty(edge, EdgePropertyEnum.STATE)).equals(LifecycleStateEnum.READY_FOR_CERTIFICATION.name())) {
551                                         foundEdge = edge;
552                                         break;
553                                 }
554
555                         }
556                         if (foundEdge == null) {
557                                 CommonUtility.addRecordToLog(logger, LogLevelEnum.DEBUG, "Failed to find rfc relation during certification clone. ");
558                                 result = StorageOperationStatus.NOT_FOUND;
559                         }
560                 }
561                 if (result == null) {
562                         TitanOperationStatus createEdgeRes = titanDao.createEdge(foundEdge.outVertex(), certifiedToscaElement.getVertex(), EdgeLabelEnum.LAST_STATE, foundEdge);
563                         if (createEdgeRes != TitanOperationStatus.OK) {
564                                 CommonUtility.addRecordToLog(logger, LogLevelEnum.DEBUG, "Failed to create rfc relation for component {}. status=", certifiedToscaElement.getUniqueId(), createEdgeRes);
565                                 result = DaoStatusConverter.convertTitanStatusToStorageStatus(createEdgeRes);
566                         }
567                 }
568                 if (result == null) {
569                         result = StorageOperationStatus.OK;
570                 }
571                 return result;
572         }
573
574         private StorageOperationStatus handleRelationsUponFailCertification(GraphVertex toscaElement, LifecycleStateEnum nextState) {
575                 StorageOperationStatus result = null;
576                 TitanOperationStatus status = null;
577                 Edge originEdge;
578                 Vertex user = null;
579                 if (nextState == LifecycleStateEnum.NOT_CERTIFIED_CHECKIN) {
580                         // fail certification
581                         // delete relation CERTIFICATION_IN_PROGRESS
582                         Map<GraphPropertyEnum, Object> properties = new EnumMap<>(GraphPropertyEnum.class);
583                         properties.put(GraphPropertyEnum.STATE, LifecycleStateEnum.CERTIFICATION_IN_PROGRESS);
584
585                         Either<Edge, TitanOperationStatus> deleteResult = titanDao.deleteBelongingEdgeByCriteria(toscaElement, EdgeLabelEnum.STATE, properties);
586                         if (deleteResult.isRight()) {
587                                 status = deleteResult.right().value();
588                                 CommonUtility.addRecordToLog(logger, LogLevelEnum.DEBUG, "Failed to delete state edge. Status is {}. ", status);
589                                 result = StorageOperationStatus.INCONSISTENCY;
590                         }
591                         if (result == null) {
592                                 // delete relation READY_FOR_CERTIFICATION
593                                 properties.put(GraphPropertyEnum.STATE, LifecycleStateEnum.READY_FOR_CERTIFICATION);
594                                 deleteResult = titanDao.deleteBelongingEdgeByCriteria(toscaElement, EdgeLabelEnum.LAST_STATE, properties);
595                                 if (deleteResult.isRight()) {
596                                         status = deleteResult.right().value();
597                                         CommonUtility.addRecordToLog(logger, LogLevelEnum.DEBUG, "Failed to delete last state edge. Status is {}. ", status);
598                                         result = StorageOperationStatus.INCONSISTENCY;
599                                 }
600                         }
601                         if (result == null) {
602                                 // delete relation NOT_CERTIFIED_CHECKIN (in order to change to STATE)
603                                 properties.put(GraphPropertyEnum.STATE, LifecycleStateEnum.NOT_CERTIFIED_CHECKIN);
604                                 deleteResult = titanDao.deleteBelongingEdgeByCriteria(toscaElement, EdgeLabelEnum.LAST_STATE, properties);
605                                 if (deleteResult.isRight()) {
606                                         status = deleteResult.right().value();
607                                         CommonUtility.addRecordToLog(logger, LogLevelEnum.DEBUG, "Failed to delete last state edge. Status is {}. ", status);
608                                         result = StorageOperationStatus.INCONSISTENCY;
609                                 }
610                         }
611                         if (result == null) {
612                                 // create new STATE relation NOT_CERTIFIED_CHECKIN
613                                 originEdge = deleteResult.left().value();
614                                 user = originEdge.outVertex();
615                                 status = titanDao.createEdge(user, toscaElement.getVertex(), EdgeLabelEnum.STATE, originEdge);
616                                 if (status != TitanOperationStatus.OK) {
617                                         CommonUtility.addRecordToLog(logger, LogLevelEnum.DEBUG, "Failed to create state edge. Status is {}. ", status);
618                                         result = StorageOperationStatus.INCONSISTENCY;
619                                 }
620                         }
621                         if (result == null) {
622                                 // delete relation LAST_MODIFIER (in order to change tester to designer)
623                                 deleteResult = titanDao.deleteBelongingEdgeByCriteria(toscaElement, EdgeLabelEnum.LAST_MODIFIER, new HashMap<>());
624                                 if (status != TitanOperationStatus.OK) {
625                                         CommonUtility.addRecordToLog(logger, LogLevelEnum.DEBUG, "Failed to create last modifier edge. Status is {}. ", status);
626                                         result = StorageOperationStatus.INCONSISTENCY;
627                                 }
628                         }
629                         if (result == null) {
630                                 // create new LAST_MODIFIER relation
631                                 originEdge = deleteResult.left().value();
632                                 status = titanDao.createEdge(user, toscaElement.getVertex(), EdgeLabelEnum.LAST_MODIFIER, originEdge);
633                                 if (status != TitanOperationStatus.OK) {
634                                         CommonUtility.addRecordToLog(logger, LogLevelEnum.DEBUG, "Failed to create last modifier edge. Status is {}. ", status);
635                                         result = StorageOperationStatus.INCONSISTENCY;
636                                 }
637                         }
638                 }
639                 if (result == null) {
640                         result = StorageOperationStatus.OK;
641                 }
642                 return result;
643         }
644
645         private StorageOperationStatus handleRelationsUponCancelCertification(GraphVertex toscaElement, LifecycleStateEnum nextState) {
646                 StorageOperationStatus result = null;
647                 Edge originEdge;
648                 if (nextState == LifecycleStateEnum.READY_FOR_CERTIFICATION) {
649                         // delete relation CERTIFICATION_IN_PROGRESS
650                         Map<GraphPropertyEnum, Object> properties = new EnumMap<>(GraphPropertyEnum.class);
651                         properties.put(GraphPropertyEnum.STATE, LifecycleStateEnum.CERTIFICATION_IN_PROGRESS);
652                         Either<Edge, TitanOperationStatus> deleteResult = titanDao.deleteBelongingEdgeByCriteria(toscaElement, EdgeLabelEnum.STATE, properties);
653
654                         if (deleteResult.isRight()) {
655                                 CommonUtility.addRecordToLog(logger, LogLevelEnum.DEBUG, "Failed to delete state edge. Status is  {}. ", deleteResult.right().value());
656                                 result = StorageOperationStatus.INCONSISTENCY;
657                         }
658                         if (result == null) {
659                                 // delete relation READY_FOR_CERTIFICATION (LAST_STATE)
660                                 properties.put(GraphPropertyEnum.STATE, nextState);
661                                 deleteResult = titanDao.deleteBelongingEdgeByCriteria(toscaElement, EdgeLabelEnum.LAST_STATE, properties);
662
663                                 if (deleteResult.isRight()) {
664                                         CommonUtility.addRecordToLog(logger, LogLevelEnum.DEBUG, "Failed to delete last state edge. Status is {}. ", deleteResult.right().value());
665                                         result = StorageOperationStatus.INCONSISTENCY;
666                                 }
667                         }
668                         if (result == null) {
669                                 // create relation READY_FOR_CERTIFICATION (STATE)
670                                 originEdge = deleteResult.left().value();
671                                 TitanOperationStatus status = titanDao.createEdge(originEdge.outVertex(), toscaElement.getVertex(), EdgeLabelEnum.STATE, originEdge);
672                                 if (status != TitanOperationStatus.OK) {
673                                         CommonUtility.addRecordToLog(logger, LogLevelEnum.DEBUG, "Failed to create state edge. Status is {}. ", status);
674                                         result = StorageOperationStatus.INCONSISTENCY;
675                                 }
676                         }
677                         if (result == null) {
678                                 result = StorageOperationStatus.OK;
679                         }
680                 }
681                 return result;
682         }
683
684         private StorageOperationStatus handleRelationsOfPreviousToscaElementBeforeCertifying(GraphVertex toscaElement, GraphVertex modifier, Integer majorVersion) {
685                 StorageOperationStatus result = null;
686                 if (majorVersion > 0) {
687                         Either<Vertex, StorageOperationStatus> findRes = findLastCertifiedToscaElementVertex(toscaElement);
688                         if (findRes.isRight()) {
689                                 CommonUtility.addRecordToLog(logger, LogLevelEnum.DEBUG, "Failed to fetch last certified tosca element {} . Status is {}. ", toscaElement.getMetadataProperty(GraphPropertyEnum.NAME), findRes.right().value());
690                                 result = findRes.right().value();
691                         }
692                         if (result == null) {
693                                 Vertex lastCertifiedVertex = findRes.left().value();
694                                 Map<GraphPropertyEnum, Object> properties = new EnumMap<>(GraphPropertyEnum.class);
695                                 properties.put(GraphPropertyEnum.IS_HIGHEST_VERSION, false);
696                                 TitanOperationStatus status = titanDao.updateVertexMetadataPropertiesWithJson(lastCertifiedVertex, properties);
697                                 if (status != TitanOperationStatus.OK) {
698                                         CommonUtility.addRecordToLog(logger, LogLevelEnum.DEBUG, "Failed to set highest version  of tosca element {} to [{}]. Status is {}", toscaElement.getUniqueId(), false, status);
699                                         result = DaoStatusConverter.convertTitanStatusToStorageStatus(status);
700                                 }
701                         }
702                 }
703                 if (result == null) {
704                         result = StorageOperationStatus.OK;
705                 }
706                 return result;
707         }
708
709         private StorageOperationStatus handleRelationsUponRequestForCertification(GraphVertex toscaElement, GraphVertex modifier, GraphVertex owner) {
710                 TitanOperationStatus status;
711                 StorageOperationStatus result = null;
712
713                 if (((String) toscaElement.getMetadataProperty(GraphPropertyEnum.STATE)).equals(LifecycleStateEnum.NOT_CERTIFIED_CHECKOUT.name())) {
714                         // remove CHECKOUT relation
715                         Either<Edge, TitanOperationStatus> deleteRes = titanDao.deleteEdge(owner, toscaElement, EdgeLabelEnum.STATE);
716                         if (deleteRes.isRight()) {
717                                 status = deleteRes.right().value();
718                                 CommonUtility.addRecordToLog(logger, LogLevelEnum.DEBUG, "Failed to delete edge. Status is {}. ", status);
719                                 result = DaoStatusConverter.convertTitanStatusToStorageStatus(status);
720                         }
721                         if (result == null) {
722                                 // create CHECKIN relation
723                                 Map<EdgePropertyEnum, Object> properties = new EnumMap<>(EdgePropertyEnum.class);
724                                 properties.put(EdgePropertyEnum.STATE, LifecycleStateEnum.NOT_CERTIFIED_CHECKIN);
725                                 status = titanDao.createEdge(modifier.getVertex(), toscaElement.getVertex(), EdgeLabelEnum.LAST_STATE, properties);
726                                 if (status != TitanOperationStatus.OK) {
727                                         CommonUtility.addRecordToLog(logger, LogLevelEnum.DEBUG, "Failed to create edge. Status is {}", status);
728                                         result = DaoStatusConverter.convertTitanStatusToStorageStatus(status);
729                                 }
730                         }
731                 } else {
732                         status = titanDao.replaceEdgeLabel(owner.getVertex(), toscaElement.getVertex(), EdgeLabelEnum.STATE, EdgeLabelEnum.LAST_STATE);
733                         if (status != TitanOperationStatus.OK) {
734                                 result = DaoStatusConverter.convertTitanStatusToStorageStatus(status);
735                         }
736                 }
737                 if (result == null) {
738                         // create RFC relation
739                         Map<EdgePropertyEnum, Object> properties = new EnumMap<>(EdgePropertyEnum.class);
740                         properties.put(EdgePropertyEnum.STATE, LifecycleStateEnum.READY_FOR_CERTIFICATION);
741                         status = titanDao.createEdge(modifier.getVertex(), toscaElement.getVertex(), EdgeLabelEnum.STATE, properties);
742                         if (status != TitanOperationStatus.OK) {
743                                 CommonUtility.addRecordToLog(logger, LogLevelEnum.DEBUG, "Failed to create edge. Status is {}", status);
744                                 result = DaoStatusConverter.convertTitanStatusToStorageStatus(status);
745                         }
746                 }
747                 if (result == null) {
748                         result = StorageOperationStatus.OK;
749                 }
750                 return result;
751         }
752
753         private StorageOperationStatus handleRelationsUponCertification(GraphVertex toscaElement, GraphVertex modifier, GraphVertex owner) {
754
755                 StorageOperationStatus result = null;
756                 TitanOperationStatus status = titanDao.replaceEdgeLabel(owner.getVertex(), toscaElement.getVertex(), EdgeLabelEnum.STATE, EdgeLabelEnum.LAST_STATE);
757                 if (status != TitanOperationStatus.OK) {
758                         result = DaoStatusConverter.convertTitanStatusToStorageStatus(status);
759                 }
760                 if (result == null) {
761                         Map<EdgePropertyEnum, Object> properties = new EnumMap<>(EdgePropertyEnum.class);
762                         properties.put(EdgePropertyEnum.STATE, LifecycleStateEnum.CERTIFICATION_IN_PROGRESS);
763                         status = titanDao.createEdge(modifier, toscaElement, EdgeLabelEnum.STATE, properties);
764                         if (status != TitanOperationStatus.OK) {
765                                 CommonUtility.addRecordToLog(logger, LogLevelEnum.DEBUG, "failed to create edge. Status is {}", status);
766                                 result = DaoStatusConverter.convertTitanStatusToStorageStatus(status);
767                         }
768                 }
769                 if (result == null) {
770                         result = StorageOperationStatus.OK;
771                 }
772                 return result;
773         }
774
775         private Either<Vertex, StorageOperationStatus> findLastCertifiedToscaElementVertex(GraphVertex toscaElement) {
776                 return findLastCertifiedToscaElementVertexRecursively(toscaElement.getVertex());
777         }
778
779         private Either<Vertex, StorageOperationStatus> findLastCertifiedToscaElementVertexRecursively(Vertex vertex) {
780                 if (isCertifiedVersion((String) vertex.property(GraphPropertyEnum.VERSION.getProperty()).value())) {
781                         return Either.left(vertex);
782                 }
783                 Iterator<Edge> edgeIter = vertex.edges(Direction.IN, EdgeLabelEnum.VERSION.name());
784                 if (!edgeIter.hasNext()) {
785                         return Either.right(StorageOperationStatus.NOT_FOUND);
786                 }
787                 return findLastCertifiedToscaElementVertexRecursively(edgeIter.next().outVertex());
788         }
789
790         private boolean isCertifiedVersion(String version) {
791                 String[] versionParts = version.split(VERSION_DELIMETER_REGEXP);
792                 if (Integer.parseInt(versionParts[0]) > 0 && Integer.parseInt(versionParts[1]) == 0) {
793                         return true;
794                 }
795                 return false;
796         }
797
798         private StorageOperationStatus updateOldToscaElementBeforeUndoCheckout(Vertex previousVersionToscaElement) {
799
800                 StorageOperationStatus result = StorageOperationStatus.OK;
801                 String previousVersion = (String) previousVersionToscaElement.property(GraphPropertyEnum.VERSION.getProperty()).value();
802                 if (!previousVersion.endsWith(".0")) {
803                         try {
804                                 CommonUtility.addRecordToLog(logger, LogLevelEnum.TRACE, "Going to update vertex of previous version of tosca element", previousVersionToscaElement.property(GraphPropertyEnum.NORMALIZED_NAME.getProperty()));
805
806                                 Map<String, Object> propertiesToUpdate = new HashMap<>();
807                                 propertiesToUpdate.put(GraphPropertyEnum.IS_HIGHEST_VERSION.getProperty(), true);
808                                 Map<String, Object> jsonMetadataMap = JsonParserUtils.parseToJson((String) previousVersionToscaElement.property(GraphPropertyEnum.METADATA.getProperty()).value());
809                                 jsonMetadataMap.put(GraphPropertyEnum.IS_HIGHEST_VERSION.getProperty(), true);
810                                 propertiesToUpdate.put(GraphPropertyEnum.METADATA.getProperty(), JsonParserUtils.jsonToString(jsonMetadataMap));
811
812                                 titanDao.setVertexProperties(previousVersionToscaElement, propertiesToUpdate);
813
814                                 Iterator<Edge> edgesIter = previousVersionToscaElement.edges(Direction.IN, EdgeLabelEnum.LAST_STATE.name());
815                                 if (!edgesIter.hasNext()) {
816                                         CommonUtility.addRecordToLog(logger, LogLevelEnum.DEBUG, "Failed to fetch last modifier vertex for tosca element {}. ", previousVersionToscaElement.property(GraphPropertyEnum.NORMALIZED_NAME.getProperty()));
817                                         result = StorageOperationStatus.NOT_FOUND;
818                                 } else {
819                                         Edge lastStateEdge = edgesIter.next();
820                                         Vertex lastModifier = lastStateEdge.outVertex();
821                                         TitanOperationStatus replaceRes = titanDao.replaceEdgeLabel(lastModifier, previousVersionToscaElement, lastStateEdge, EdgeLabelEnum.LAST_STATE, EdgeLabelEnum.STATE);
822                                         if (replaceRes != TitanOperationStatus.OK) {
823                                                 CommonUtility.addRecordToLog(logger, LogLevelEnum.DEBUG, "Failed to replace label from {} to {}. status = {}", EdgeLabelEnum.LAST_STATE, EdgeLabelEnum.STATE, replaceRes);
824                                                 result = StorageOperationStatus.INCONSISTENCY;
825                                                 if (replaceRes != TitanOperationStatus.INVALID_ID) {
826                                                         result = DaoStatusConverter.convertTitanStatusToStorageStatus(replaceRes);
827                                                 }
828                                         }
829                                 }
830                         } catch (Exception e) {
831                                 CommonUtility.addRecordToLog(logger, LogLevelEnum.DEBUG, "Exception occured during update previous tosca element {} before undo checkout. {} ", e.getMessage());
832                         }
833                 }
834                 return result;
835         }
836
837         private StorageOperationStatus updatePreviousVersion(GraphVertex toscaElementVertex, GraphVertex ownerVertex) {
838                 StorageOperationStatus result = null;
839                 String ownerId = (String) ownerVertex.getMetadataProperty(GraphPropertyEnum.USERID);
840                 String toscaElementId = toscaElementVertex.getUniqueId();
841                 if (!toscaElementVertex.getMetadataProperty(GraphPropertyEnum.STATE).equals(LifecycleStateEnum.CERTIFIED.name())) {
842                         toscaElementVertex.addMetadataProperty(GraphPropertyEnum.IS_HIGHEST_VERSION, false);
843                         Either<GraphVertex, TitanOperationStatus> updateVertexRes = titanDao.updateVertex(toscaElementVertex);
844                         if (updateVertexRes.isRight()) {
845                                 TitanOperationStatus titatStatus = updateVertexRes.right().value();
846                                 CommonUtility.addRecordToLog(logger, LogLevelEnum.DEBUG, "Failed to update tosca element vertex {}. Status is  {}", toscaElementVertex.getUniqueId(), titatStatus);
847                                 result = DaoStatusConverter.convertTitanStatusToStorageStatus(titatStatus);
848                         }
849                         Either<Edge, TitanOperationStatus> deleteEdgeRes = null;
850                         if (result == null) {
851                                 CommonUtility.addRecordToLog(logger, LogLevelEnum.TRACE, "Going to replace edge with label {} to label {} from {} to {}. ", EdgeLabelEnum.STATE, EdgeLabelEnum.LAST_STATE, ownerId, toscaElementId);
852
853                                 deleteEdgeRes = titanDao.deleteEdge(ownerVertex, toscaElementVertex, EdgeLabelEnum.STATE);
854                                 if (deleteEdgeRes.isRight()) {
855                                         TitanOperationStatus titanStatus = deleteEdgeRes.right().value();
856                                         CommonUtility.addRecordToLog(logger, LogLevelEnum.DEBUG, "Failed to delete edge with label {} from {} to {}. Status is {} ", EdgeLabelEnum.STATE, EdgeLabelEnum.LAST_STATE, ownerId, toscaElementId, titanStatus);
857                                         if (!titanStatus.equals(TitanOperationStatus.INVALID_ID)) {
858                                                 result = DaoStatusConverter.convertTitanStatusToStorageStatus(titanStatus);
859                                         } else {
860                                                 result = StorageOperationStatus.INCONSISTENCY;
861                                         }
862                                 }
863                         }
864                         if (result == null) {
865                                 TitanOperationStatus createEdgeRes = titanDao.createEdge(ownerVertex.getVertex(), toscaElementVertex.getVertex(), EdgeLabelEnum.LAST_STATE, deleteEdgeRes.left().value());
866                                 if (createEdgeRes != TitanOperationStatus.OK) {
867                                         result = DaoStatusConverter.convertTitanStatusToStorageStatus(createEdgeRes);
868                                 }
869                         }
870                 }
871                 if (result == null) {
872                         result = StorageOperationStatus.OK;
873                 }
874                 return result;
875         }
876
877         private Either<ToscaElement, StorageOperationStatus> cloneToscaElementForCheckout(GraphVertex toscaElementVertex, GraphVertex modifierVertex) {
878
879                 Either<ToscaElement, StorageOperationStatus> result = null;
880                 Either<GraphVertex, StorageOperationStatus> cloneResult = null;
881                 ToscaElementOperation operation = getToscaElementOperation(toscaElementVertex.getLabel());
882                 // check if component with the next version doesn't exist.
883                 Iterator<Edge> nextVersionComponentIter = toscaElementVertex.getVertex().edges(Direction.OUT, EdgeLabelEnum.VERSION.name());
884                 if (nextVersionComponentIter != null && nextVersionComponentIter.hasNext()) {
885                         String fetchedVersion = (String) nextVersionComponentIter.next().inVertex().property(GraphPropertyEnum.VERSION.getProperty()).value();
886                         String fetchedName = (String) nextVersionComponentIter.next().inVertex().property(GraphPropertyEnum.NORMALIZED_NAME.getProperty()).value();
887                         CommonUtility.addRecordToLog(logger, LogLevelEnum.DEBUG, "Failed to checkout component {} with version {}. The component with name {} and version {} was fetched from graph as existing following version. ",
888                                         toscaElementVertex.getMetadataProperty(GraphPropertyEnum.NORMALIZED_NAME).toString(), toscaElementVertex.getMetadataProperty(GraphPropertyEnum.VERSION).toString(), fetchedName, fetchedVersion);
889                         result = Either.right(StorageOperationStatus.ENTITY_ALREADY_EXISTS);
890                 }
891                 if (result == null) {
892                         cloneResult = operation.cloneToscaElement(toscaElementVertex, cloneGraphVertexForCheckout(toscaElementVertex, modifierVertex), modifierVertex);
893                         if (cloneResult.isRight()) {
894                                 result = Either.right(cloneResult.right().value());
895                         }
896                 }
897                 GraphVertex clonedVertex = null;
898                 if (result == null) {
899                         clonedVertex = cloneResult.left().value();
900                         TitanOperationStatus status = titanDao.createEdge(toscaElementVertex.getVertex(), cloneResult.left().value().getVertex(), EdgeLabelEnum.VERSION, new HashMap<>());
901                         if (status != TitanOperationStatus.OK) {
902                                 CommonUtility.addRecordToLog(logger, LogLevelEnum.DEBUG, "Failed to create edge with label {} from vertex {} to tosca element vertex {} on graph. Status is {}. ", EdgeLabelEnum.VERSION,
903                                                 toscaElementVertex.getMetadataProperty(GraphPropertyEnum.NORMALIZED_NAME), cloneResult.left().value().getMetadataProperty(GraphPropertyEnum.NORMALIZED_NAME), status);
904                                 result = Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(status));
905                         }
906                 }
907                 if (result == null) {
908                         result = operation.getToscaElement(cloneResult.left().value().getUniqueId());
909                         if (result.isRight()) {
910                                 return result;
911                         }
912
913                         ToscaElement toscaElement = result.left().value();
914                         if (toscaElement.getToscaType() == ToscaElementTypeEnum.TopologyTemplate) {
915                                 result = handleFixTopologyTemplate(toscaElementVertex, result, operation, clonedVertex, toscaElement);
916                         }
917                 }
918                 return result;
919         }
920
921         private Either<ToscaElement, StorageOperationStatus> handleFixTopologyTemplate(GraphVertex toscaElementVertex, Either<ToscaElement, StorageOperationStatus> result, ToscaElementOperation operation, GraphVertex clonedVertex,
922                         ToscaElement toscaElement) {
923                 TopologyTemplate topologyTemplate = (TopologyTemplate) toscaElement;
924                 Map<String, MapPropertiesDataDefinition> instInputs = topologyTemplate.getInstInputs();
925                 Map<String, MapGroupsDataDefinition> instGroups = topologyTemplate.getInstGroups();
926                 Map<String, MapArtifactDataDefinition> instArtifactsMap = topologyTemplate.getInstanceArtifacts();
927                 Map<String, ToscaElement> origCompMap = new HashMap<>();
928                 if (instInputs == null) {
929                         instInputs = new HashMap<>();
930                 }
931                 if (instGroups == null) {
932                         instGroups = new HashMap<>();
933                 }
934                 if (instArtifactsMap == null) {
935                         instArtifactsMap = new HashMap<>();
936                 }
937                 Map<String, ComponentInstanceDataDefinition> instancesMap = topologyTemplate.getComponentInstances();
938                 boolean isAddInstGroup = instGroups == null || instGroups.isEmpty();
939                 boolean needUpdateComposition = false;
940
941                 if (instancesMap != null && !instancesMap.isEmpty()) {
942                         for (ComponentInstanceDataDefinition vfInst : instancesMap.values()) {
943                                 CommonUtility.addRecordToLog(logger, LogLevelEnum.DEBUG, "vfInst name is {} . OriginType {}. ", vfInst.getName(), vfInst.getOriginType());
944                                 if (vfInst.getOriginType().name().equals(OriginTypeEnum.VF.name())) {
945                                         collectInstanceInputAndGroups(instInputs, instGroups, instArtifactsMap, origCompMap, isAddInstGroup, vfInst, clonedVertex);
946                                 }
947                                 needUpdateComposition = needUpdateComposition || fixToscaComponentName(vfInst, origCompMap);
948                                 if(needUpdateComposition){
949                                         instancesMap.put(vfInst.getUniqueId(), vfInst);
950                                 }
951                         }
952                         CommonUtility.addRecordToLog(logger, LogLevelEnum.DEBUG, "before add to graph instInputs {}  instGroups {} needUpdateComposition {}", instInputs, instGroups, needUpdateComposition);
953                         if (!instInputs.isEmpty()) {
954                                 CommonUtility.addRecordToLog(logger, LogLevelEnum.DEBUG, "before add inst inputs {} ", instInputs == null ? 0 : instInputs.size());
955                                 GraphVertex toscaDataVertex = null;
956                                 Either<GraphVertex, TitanOperationStatus> instInpVertexEither = titanDao.getChildVertex(toscaElementVertex, EdgeLabelEnum.INST_INPUTS, JsonParseFlagEnum.ParseJson);
957                                 if (instInpVertexEither.isLeft()) {
958                                         toscaDataVertex = instInpVertexEither.left().value();
959                                 }
960
961                                 StorageOperationStatus status = handleToscaData(clonedVertex, VertexTypeEnum.INST_INPUTS, EdgeLabelEnum.INST_INPUTS, toscaDataVertex, instInputs);
962                                 if (status != StorageOperationStatus.OK) {
963                                         CommonUtility.addRecordToLog(logger, LogLevelEnum.DEBUG, "Failed to update instance inputs . Status is {}. ", status);
964                                         result = Either.right(status);
965                                         return result;
966                                 }
967
968                         }
969                         if (!instGroups.isEmpty()) {
970                                 CommonUtility.addRecordToLog(logger, LogLevelEnum.DEBUG, "before add inst groups {} ", instGroups == null ? 0 : instGroups.size());
971                                 GraphVertex toscaDataVertex = null;
972                                 Either<GraphVertex, TitanOperationStatus> instGrVertexEither = titanDao.getChildVertex(toscaElementVertex, EdgeLabelEnum.INST_GROUPS, JsonParseFlagEnum.ParseJson);
973                                 if (instGrVertexEither.isLeft()) {
974                                         toscaDataVertex = instGrVertexEither.left().value();
975                                 }
976
977                                 StorageOperationStatus status = handleToscaData(clonedVertex, VertexTypeEnum.INST_GROUPS, EdgeLabelEnum.INST_GROUPS, toscaDataVertex, instGroups);
978                                 if (status != StorageOperationStatus.OK) {
979                                         CommonUtility.addRecordToLog(logger, LogLevelEnum.DEBUG, "Failed to update instance group . Status is {}. ", status);
980                                         result = Either.right(status);
981                                         return result;
982                                 }
983
984                         }
985                         if (needUpdateComposition) {
986                                 CommonUtility.addRecordToLog(logger, LogLevelEnum.DEBUG, "before update Instances ");
987                                 Map<String, CompositionDataDefinition> jsonComposition = (Map<String, CompositionDataDefinition>) clonedVertex.getJson();
988                                 CompositionDataDefinition compositionDataDefinition = jsonComposition.get(JsonConstantKeysEnum.COMPOSITION.getValue());
989                                 compositionDataDefinition.setComponentInstances(instancesMap);
990                                 Either<GraphVertex, TitanOperationStatus> updateElement = titanDao.updateVertex(clonedVertex);
991                                 if (updateElement.isRight()) {
992                                         TitanOperationStatus status = updateElement.right().value();
993                                         CommonUtility.addRecordToLog(logger, LogLevelEnum.DEBUG, "Failed to update instances on metadata vertex . Status is {}. ", status);
994                                         result = Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(status));
995                                         return result;
996                                 }
997                         }
998
999                         result = operation.getToscaElement(clonedVertex.getUniqueId());
1000
1001                 } else {
1002                         CommonUtility.addRecordToLog(logger, LogLevelEnum.DEBUG, "RI map empty on component {}", toscaElement.getUniqueId());
1003                 }
1004                 return result;
1005         }
1006         
1007         //TODO remove after jsonModelMigration
1008         public boolean resolveToscaComponentName(ComponentInstanceDataDefinition vfInst, Map<String, ToscaElement> origCompMap) {
1009                 return fixToscaComponentName(vfInst, origCompMap);
1010         }
1011
1012         private boolean fixToscaComponentName(ComponentInstanceDataDefinition vfInst, Map<String, ToscaElement> origCompMap) {
1013                 if (vfInst.getToscaComponentName() == null || vfInst.getToscaComponentName().isEmpty()) {
1014                         String ciUid = vfInst.getUniqueId();
1015                         String origCompUid = vfInst.getComponentUid();
1016                         CommonUtility.addRecordToLog(logger, LogLevelEnum.DEBUG, "fixToscaComponentName:: Ri id {} . origin component id is {}. type is{} ", ciUid, origCompUid, vfInst.getOriginType());
1017                         ToscaElement origComp = null;
1018                         if (!origCompMap.containsKey(origCompUid)) {
1019                                 Either<ToscaElement, StorageOperationStatus> origCompEither;
1020                                 if (vfInst.getOriginType() == null || vfInst.getOriginType().name().equals(OriginTypeEnum.VF.name())) {
1021                                         origCompEither = topologyTemplateOperation.getToscaElement(origCompUid);
1022                                 }else{
1023                                         origCompEither = nodeTypeOperation.getToscaElement(origCompUid);
1024                                 }
1025                                 if (origCompEither.isRight()) {
1026                                         CommonUtility.addRecordToLog(logger, LogLevelEnum.DEBUG, "Failed to find orig component {} . Status is {}. ", origCompEither.right().value());
1027                                         return false;
1028                                 }
1029                                 origComp = origCompEither.left().value();
1030                                 origCompMap.put(origCompUid, origComp);
1031                         } else {
1032                                 origComp = origCompMap.get(origCompUid);
1033                         }
1034                         String toscaName = (String) origComp.getMetadataValue(JsonPresentationFields.TOSCA_RESOURCE_NAME);
1035                         CommonUtility.addRecordToLog(logger, LogLevelEnum.DEBUG, "Origin component id is {}. toscaName {}", origCompUid, toscaName);
1036                         vfInst.setToscaComponentName(toscaName);
1037                         return true;
1038                 }
1039                 return false;
1040         }
1041
1042         private void collectInstanceInputAndGroups(Map<String, MapPropertiesDataDefinition> instInputs, Map<String, MapGroupsDataDefinition> instGroups, Map<String, MapArtifactDataDefinition> instArtifactsMap, Map<String, ToscaElement> origCompMap,
1043                         boolean isAddInstGroup, ComponentInstanceDataDefinition vfInst, GraphVertex clonedVertex) {
1044                 String ciUid = vfInst.getUniqueId();
1045                 String origCompUid = vfInst.getComponentUid();
1046                 CommonUtility.addRecordToLog(logger, LogLevelEnum.DEBUG, "collectInstanceInputAndGroups:: Ri id {} . origin component id is {}. ", ciUid, origCompUid);
1047                 TopologyTemplate origComp = null;
1048                 if (!origCompMap.containsKey(origCompUid)) {
1049                         Either<ToscaElement, StorageOperationStatus> origCompEither = topologyTemplateOperation.getToscaElement(origCompUid);
1050                         if (origCompEither.isRight()) {
1051                                 CommonUtility.addRecordToLog(logger, LogLevelEnum.DEBUG, "Failed to find orig component {} . Status is {}. ", origCompEither.right().value());
1052                                 return;
1053                         }
1054                         origComp = (TopologyTemplate) origCompEither.left().value();
1055                         origCompMap.put(origCompUid, origComp);
1056                 } else {
1057                         origComp = (TopologyTemplate) origCompMap.get(origCompUid);
1058                 }
1059                 CommonUtility.addRecordToLog(logger, LogLevelEnum.DEBUG, "Orig component {}. ", origComp.getUniqueId());
1060
1061                 Map<String, PropertyDataDefinition> origInputs = origComp.getInputs();
1062                 CommonUtility.addRecordToLog(logger, LogLevelEnum.DEBUG, "Orig component inputs size {}. ", origInputs == null ? 0 : origInputs.size());
1063                 if (origInputs != null) {
1064                         if (!instInputs.containsKey(ciUid)) {
1065                                 MapPropertiesDataDefinition instProperties = new MapPropertiesDataDefinition(origInputs);
1066                                 instInputs.put(ciUid, instProperties);
1067                         } else {
1068
1069                                 MapPropertiesDataDefinition instInputMap = instInputs.get(ciUid);
1070                                 Map<String, PropertyDataDefinition> instProp = instInputMap.getMapToscaDataDefinition();
1071                                 origInputs.forEach((propName, propMap) -> {
1072                                         if (!instProp.containsKey(propName)) {
1073                                                 instProp.put(propName, propMap);
1074                                         }
1075                                 });
1076                         }
1077                         CommonUtility.addRecordToLog(logger, LogLevelEnum.DEBUG, "ComponentInstanseInputs {}. ", instInputs.get(ciUid));
1078                 }
1079
1080                 if (isAddInstGroup) {
1081                         CommonUtility.addRecordToLog(logger, LogLevelEnum.DEBUG, "before create group instance. ");
1082                         List<GroupDataDefinition> filteredGroups = null;
1083
1084                         
1085                         CommonUtility.addRecordToLog(logger, LogLevelEnum.DEBUG, "check vf groups before filter. Size is {} ", filteredGroups == null ? 0 : filteredGroups.size());
1086                         if (origComp.getGroups() != null && !origComp.getGroups().isEmpty()) {
1087                                 filteredGroups = origComp.getGroups().values().stream().filter(g -> g.getType().equals(VF_MODULE)).collect(Collectors.toList());
1088                                 CommonUtility.addRecordToLog(logger, LogLevelEnum.DEBUG, "check vf groups . Size is {} ", filteredGroups == null ? 0 : filteredGroups.size());
1089                         }
1090                         CommonUtility.addRecordToLog(logger, LogLevelEnum.DEBUG, "check vf groups after filter. Size is {} ", filteredGroups == null ? 0 : filteredGroups.size());
1091                         if (CollectionUtils.isNotEmpty(filteredGroups)) {
1092                                 MapArtifactDataDefinition instArifacts = null;
1093                                 if(!instArtifactsMap.containsKey(ciUid)){
1094                                 
1095                                                 CommonUtility.addRecordToLog(logger, LogLevelEnum.DEBUG, "istance artifacts not found ");
1096                                                 
1097                                                 Map<String, ArtifactDataDefinition> deploymentArtifacts = origComp.getDeploymentArtifacts();
1098                                                 
1099                                                 
1100                                                 instArifacts = new MapArtifactDataDefinition(deploymentArtifacts);
1101                                                  addToscaDataDeepElementsBlockToToscaElement(clonedVertex, EdgeLabelEnum.INST_DEPLOYMENT_ARTIFACTS, VertexTypeEnum.INST_DEPLOYMENT_ARTIFACTS, instArifacts, ciUid);
1102                                                 
1103                                                  instArtifactsMap.put(ciUid, instArifacts);
1104                                                 
1105                                 }else{
1106                                         instArifacts = instArtifactsMap.get(ciUid);
1107                                 }
1108                                         
1109                                 if(instArifacts != null){
1110                                         Map<String, ArtifactDataDefinition> instDeplArtifMap = instArifacts.getMapToscaDataDefinition();
1111                                 
1112                                         CommonUtility.addRecordToLog(logger, LogLevelEnum.DEBUG, "check group dep artifacts. Size is {} ", instDeplArtifMap == null ? 0 : instDeplArtifMap.values().size());
1113                                         Map<String, GroupInstanceDataDefinition> groupInstanceToCreate = new HashMap<>();
1114                                         for(GroupDataDefinition group:filteredGroups){
1115                                                 CommonUtility.addRecordToLog(logger, LogLevelEnum.DEBUG, "create new groupInstance  {} ", group.getName());
1116                                                 GroupInstanceDataDefinition groupInstance = buildGroupInstanceDataDefinition(group, vfInst);
1117                                                 List<String> artifactsUid = new ArrayList<>();
1118                                                 List<String> artifactsId = new ArrayList<>();
1119                                                 for (ArtifactDataDefinition artifact : instDeplArtifMap.values()) {
1120                                                         //CommonUtility.addRecordToLog(logger, LogLevelEnum.DEBUG, "create new groupInstance  {} ", artifact.getA);
1121                                                         Optional<String> op = group.getArtifacts().stream().filter(p -> p.equals(artifact.getGeneratedFromId())).findAny();
1122                                                         if (op.isPresent()) {
1123                                                                 artifactsUid.add(artifact.getArtifactUUID());
1124                                                                 artifactsId.add(artifact.getUniqueId());
1125                                                                 
1126                                                         }
1127                                                 }
1128                                                 groupInstance.setGroupInstanceArtifacts(artifactsId);
1129                                                 groupInstance.setGroupInstanceArtifactsUuid(artifactsUid);
1130                                                 groupInstanceToCreate.put(groupInstance.getName(), groupInstance);
1131                                         }
1132                                         if (MapUtils.isNotEmpty(groupInstanceToCreate)) {
1133                                                 instGroups.put(vfInst.getUniqueId(), new MapGroupsDataDefinition(groupInstanceToCreate));
1134         
1135                                         }
1136                                 }
1137                         }
1138                 }
1139         }
1140
1141         private GraphVertex cloneGraphVertexForCheckout(GraphVertex toscaElementVertex, GraphVertex modifierVertex) {
1142                 GraphVertex nextVersionToscaElementVertex = new GraphVertex();
1143                 String uniqueId = UniqueIdBuilder.buildComponentUniqueId();
1144                 Map<GraphPropertyEnum, Object> metadataProperties = new HashMap<>(toscaElementVertex.getMetadataProperties());
1145                 nextVersionToscaElementVertex.setMetadataProperties(metadataProperties);
1146                 nextVersionToscaElementVertex.setUniqueId(uniqueId);
1147                 nextVersionToscaElementVertex.setLabel(toscaElementVertex.getLabel());
1148                 nextVersionToscaElementVertex.setType(toscaElementVertex.getType());
1149
1150                 nextVersionToscaElementVertex.addMetadataProperty(GraphPropertyEnum.UNIQUE_ID, uniqueId);
1151                 nextVersionToscaElementVertex.addMetadataProperty(GraphPropertyEnum.COMPONENT_TYPE, nextVersionToscaElementVertex.getType().name());
1152                 String nextVersion = getNextVersion((String) toscaElementVertex.getMetadataProperty(GraphPropertyEnum.VERSION));
1153                 if (isFirstCheckoutAfterCertification(nextVersion)) {
1154                         nextVersionToscaElementVertex.addMetadataProperty(GraphPropertyEnum.UUID, IdBuilderUtils.generateUUID());
1155                 }
1156                 nextVersionToscaElementVertex.addMetadataProperty(GraphPropertyEnum.VERSION, nextVersion);
1157                 nextVersionToscaElementVertex.addMetadataProperty(GraphPropertyEnum.STATE, LifecycleStateEnum.NOT_CERTIFIED_CHECKOUT.name());
1158                 nextVersionToscaElementVertex.addMetadataProperty(GraphPropertyEnum.IS_HIGHEST_VERSION, true);
1159
1160                 if (toscaElementVertex.getType() == ComponentTypeEnum.SERVICE && toscaElementVertex.getMetadataProperty(GraphPropertyEnum.STATE).equals(LifecycleStateEnum.CERTIFIED.name())) {
1161                         nextVersionToscaElementVertex.addMetadataProperty(GraphPropertyEnum.DISTRIBUTION_STATUS, DistributionStatusEnum.DISTRIBUTION_NOT_APPROVED.getValue());
1162                 }
1163                 if (!MapUtils.isEmpty(toscaElementVertex.getMetadataJson())) {
1164                         nextVersionToscaElementVertex.setMetadataJson(new HashMap<String, Object>(toscaElementVertex.getMetadataJson()));
1165                         nextVersionToscaElementVertex.updateMetadataJsonWithCurrentMetadataProperties();
1166                 }
1167                 long currTime = System.currentTimeMillis();
1168                 nextVersionToscaElementVertex.setJsonMetadataField(JsonPresentationFields.CREATION_DATE, currTime);
1169                 nextVersionToscaElementVertex.setJsonMetadataField(JsonPresentationFields.LAST_UPDATE_DATE, currTime);
1170                 nextVersionToscaElementVertex.setJsonMetadataField(JsonPresentationFields.USER_ID_CREATOR, modifierVertex.getUniqueId());
1171                 nextVersionToscaElementVertex.setJsonMetadataField(JsonPresentationFields.USER_ID_LAST_UPDATER, modifierVertex.getUniqueId());
1172                 if (toscaElementVertex.getType() == ComponentTypeEnum.SERVICE) {
1173                         nextVersionToscaElementVertex.setJsonMetadataField(JsonPresentationFields.CONFORMANCE_LEVEL, ConfigurationManager.getConfigurationManager().getConfiguration().getToscaConformanceLevel());
1174                 }
1175
1176                 if (!MapUtils.isEmpty(toscaElementVertex.getJson())) {
1177                         nextVersionToscaElementVertex.setJson(new HashMap<String, ToscaDataDefinition>(toscaElementVertex.getJson()));
1178                 }
1179                 return nextVersionToscaElementVertex;
1180         }
1181
1182         private Either<GraphVertex, StorageOperationStatus> cloneToscaElementForCertify(GraphVertex toscaElementVertex, GraphVertex modifierVertex, Integer majorVersion) {
1183                 Either<GraphVertex, StorageOperationStatus> result;
1184                 Either<List<GraphVertex>, StorageOperationStatus> deleteResult = null;
1185                 GraphVertex clonedToscaElement = null;
1186                 result = getToscaElementOperation(toscaElementVertex.getLabel()).cloneToscaElement(toscaElementVertex, cloneGraphVertexForCertify(toscaElementVertex, modifierVertex, majorVersion), modifierVertex);
1187                 if (result.isRight()) {
1188                         CommonUtility.addRecordToLog(logger, LogLevelEnum.DEBUG, "Failed to clone tosca element {} for certification. Sattus is {}. ", toscaElementVertex.getUniqueId(), result.right().value());
1189                 } else {
1190                         clonedToscaElement = result.left().value();
1191                         deleteResult = deleteAllPreviousNotCertifiedVersions(toscaElementVertex);
1192                         if (deleteResult.isRight()) {
1193                                 CommonUtility.addRecordToLog(logger, LogLevelEnum.DEBUG, "Failed to delete all previous npt certified versions of tosca element {}. Status is {}. ", toscaElementVertex.getUniqueId(), deleteResult.right().value());
1194                                 result = Either.right(deleteResult.right().value());
1195                         }
1196                 }
1197                 if (result.isLeft()) {
1198                         result = handlePreviousVersionRelation(clonedToscaElement, deleteResult.left().value(), majorVersion);
1199                 }
1200                 return result;
1201         }
1202
1203         private Either<GraphVertex, StorageOperationStatus> handlePreviousVersionRelation(GraphVertex clonedToscaElement, List<GraphVertex> deletedVersions, Integer majorVersion) {
1204                 Either<GraphVertex, StorageOperationStatus> result = null;
1205                 Vertex previousCertifiedToscaElement = null;
1206                 if (majorVersion > 0) {
1207                         List<GraphVertex> firstMinorVersionVertex = deletedVersions.stream().filter(gv -> getMinorVersion((String) gv.getMetadataProperty(GraphPropertyEnum.VERSION)) == 1).collect(Collectors.toList());
1208
1209                         if (CollectionUtils.isEmpty(firstMinorVersionVertex)) {
1210                                 result = Either.right(StorageOperationStatus.NOT_FOUND);
1211                         } else {
1212                                 previousCertifiedToscaElement = getPreviousCertifiedToscaElement(firstMinorVersionVertex.get(0));
1213                                 if (previousCertifiedToscaElement == null) {
1214                                         result = Either.right(StorageOperationStatus.NOT_FOUND);
1215                                 }
1216                         }
1217                         if (result == null) {
1218                                 TitanOperationStatus status = titanDao.createEdge(previousCertifiedToscaElement, clonedToscaElement.getVertex(), EdgeLabelEnum.VERSION, new HashMap<>());
1219                                 if (status != TitanOperationStatus.OK) {
1220                                         CommonUtility.addRecordToLog(logger, LogLevelEnum.DEBUG, "Failed to create edge with label {} from vertex {} to tosca element vertex {} on graph. Status is {}. ", EdgeLabelEnum.VERSION,
1221                                                         previousCertifiedToscaElement.property(GraphPropertyEnum.UNIQUE_ID.getProperty()), clonedToscaElement.getUniqueId(), status);
1222                                         result = Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(status));
1223                                 }
1224                         }
1225                 }
1226                 if (result == null) {
1227                         result = Either.left(clonedToscaElement);
1228                 }
1229                 return result;
1230         }
1231
1232         private Vertex getPreviousCertifiedToscaElement(GraphVertex graphVertex) {
1233
1234                 Iterator<Edge> edges = graphVertex.getVertex().edges(Direction.IN, EdgeLabelEnum.VERSION.name());
1235                 if (edges.hasNext()) {
1236                         return edges.next().outVertex();
1237                 }
1238                 return null;
1239         }
1240
1241         private Either<List<GraphVertex>, StorageOperationStatus> deleteAllPreviousNotCertifiedVersions(GraphVertex toscaElementVertex) {
1242                 Either<List<GraphVertex>, StorageOperationStatus> result = null;
1243
1244                 ToscaElementOperation operation = getToscaElementOperation(toscaElementVertex.getLabel());
1245                 List<GraphVertex> previosVersions = null;
1246                 Object uuid = toscaElementVertex.getMetadataProperty(GraphPropertyEnum.UUID);
1247                 Object componentName = toscaElementVertex.getMetadataProperty(GraphPropertyEnum.NAME);
1248                 try {
1249                         Map<GraphPropertyEnum, Object> properties = new HashMap<>();
1250                         properties.put(GraphPropertyEnum.UUID, uuid);
1251                         properties.put(GraphPropertyEnum.NAME, componentName);
1252                         Either<List<GraphVertex>, TitanOperationStatus> getToscaElementsRes = titanDao.getByCriteria(toscaElementVertex.getLabel(), properties, JsonParseFlagEnum.ParseMetadata);
1253                         if (getToscaElementsRes.isRight()) {
1254                                 result = Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(getToscaElementsRes.right().value()));
1255                         }
1256                         if (result == null) {
1257                                 previosVersions = getToscaElementsRes.left().value();
1258                                 Either<Boolean, StorageOperationStatus> deleteResult = markToscaElementsAsDeleted(operation, getToscaElementsRes.left().value());
1259                                 if (deleteResult.isRight()) {
1260                                         result = Either.right(deleteResult.right().value());
1261                                 }
1262                         }
1263                         if (result == null) {
1264                                 result = Either.left(previosVersions);
1265                         }
1266                 } catch (Exception e) {
1267                         CommonUtility.addRecordToLog(logger, LogLevelEnum.DEBUG, "Exception occured during deleteng all tosca elements by UUID {} and name {}. {} ", uuid, componentName, e.getMessage());
1268                 }
1269                 return result;
1270         }
1271
1272         private GraphVertex cloneGraphVertexForCertify(GraphVertex toscaElementVertex, GraphVertex modifierVertex, Integer majorVersion) {
1273
1274                 GraphVertex nextVersionToscaElementVertex = new GraphVertex();
1275                 String uniqueId = IdBuilderUtils.generateUniqueId();
1276                 Map<GraphPropertyEnum, Object> metadataProperties = new HashMap<>(toscaElementVertex.getMetadataProperties());
1277                 nextVersionToscaElementVertex.setMetadataProperties(metadataProperties);
1278                 nextVersionToscaElementVertex.setUniqueId(uniqueId);
1279                 nextVersionToscaElementVertex.setLabel(toscaElementVertex.getLabel());
1280                 nextVersionToscaElementVertex.setType(toscaElementVertex.getType());
1281
1282                 nextVersionToscaElementVertex.addMetadataProperty(GraphPropertyEnum.UNIQUE_ID, uniqueId);
1283                 nextVersionToscaElementVertex.addMetadataProperty(GraphPropertyEnum.COMPONENT_TYPE, nextVersionToscaElementVertex.getType().name());
1284                 nextVersionToscaElementVertex.addMetadataProperty(GraphPropertyEnum.VERSION, (majorVersion + 1) + VERSION_DELIMETER + "0");
1285                 nextVersionToscaElementVertex.addMetadataProperty(GraphPropertyEnum.STATE, LifecycleStateEnum.CERTIFIED.name());
1286                 nextVersionToscaElementVertex.addMetadataProperty(GraphPropertyEnum.IS_HIGHEST_VERSION, true);
1287                 nextVersionToscaElementVertex.setJsonMetadataField(JsonPresentationFields.CREATION_DATE, System.currentTimeMillis());
1288                 nextVersionToscaElementVertex.setJsonMetadataField(JsonPresentationFields.LAST_UPDATE_DATE, null);
1289                 nextVersionToscaElementVertex.setJsonMetadataField(JsonPresentationFields.USER_ID_CREATOR, modifierVertex.getUniqueId());
1290                 nextVersionToscaElementVertex.setJsonMetadataField(JsonPresentationFields.USER_ID_LAST_UPDATER, modifierVertex.getUniqueId());
1291
1292                 if (toscaElementVertex.getType() == ComponentTypeEnum.SERVICE && toscaElementVertex.getMetadataProperty(GraphPropertyEnum.STATE).equals(LifecycleStateEnum.CERTIFIED)) {
1293                         nextVersionToscaElementVertex.addMetadataProperty(GraphPropertyEnum.DISTRIBUTION_STATUS, DistributionStatusEnum.DISTRIBUTION_NOT_APPROVED.getValue());
1294                 }
1295                 if (!MapUtils.isEmpty(toscaElementVertex.getMetadataJson())) {
1296                         nextVersionToscaElementVertex.setMetadataJson(new HashMap<String, Object>(toscaElementVertex.getMetadataJson()));
1297                         nextVersionToscaElementVertex.updateMetadataJsonWithCurrentMetadataProperties();
1298                 }
1299                 if (!MapUtils.isEmpty(toscaElementVertex.getJson())) {
1300                         nextVersionToscaElementVertex.setJson(new HashMap<String, ToscaDataDefinition>(toscaElementVertex.getJson()));
1301                 }
1302                 return nextVersionToscaElementVertex;
1303         }
1304
1305         private ComponentParametersView buildComponentParametersViewAfterCheckin() {
1306                 ComponentParametersView componentParametersView = new ComponentParametersView();
1307                 componentParametersView.disableAll();
1308                 componentParametersView.setIgnoreUsers(false);
1309                 return componentParametersView;
1310         }
1311
1312         private Either<GraphVertex, StorageOperationStatus> checkinToscaELement(LifecycleStateEnum currState, GraphVertex toscaElementVertex, GraphVertex ownerVertex, GraphVertex modifierVertex, LifecycleStateEnum nextState) {
1313                 Either<GraphVertex, StorageOperationStatus> updateRelationsRes;
1314                 Either<GraphVertex, StorageOperationStatus> result = changeStateToCheckedIn(currState, toscaElementVertex, ownerVertex, modifierVertex);
1315                 if (result.isLeft()) {
1316                         toscaElementVertex.addMetadataProperty(GraphPropertyEnum.STATE, nextState.name());
1317                         toscaElementVertex.setJsonMetadataField(JsonPresentationFields.LAST_UPDATE_DATE, System.currentTimeMillis());
1318                         result = updateToscaElementVertexMetadataPropertiesAndJson(toscaElementVertex);
1319                 }
1320                 if (result.isLeft()) {
1321                         updateRelationsRes = updateLastModifierEdge(toscaElementVertex, ownerVertex, modifierVertex);
1322                         if (updateRelationsRes.isRight()) {
1323                                 result = Either.right(updateRelationsRes.right().value());
1324                         }
1325                 }
1326                 return result;
1327         }
1328
1329         private Either<GraphVertex, StorageOperationStatus> updateToscaElementVertexMetadataPropertiesAndJson(GraphVertex toscaElementVertex) {
1330
1331                 Either<GraphVertex, StorageOperationStatus> result;
1332
1333                 Either<GraphVertex, TitanOperationStatus> updateVertexRes = titanDao.updateVertex(toscaElementVertex);
1334                 if (updateVertexRes.isRight()) {
1335                         TitanOperationStatus titatStatus = updateVertexRes.right().value();
1336                         CommonUtility.addRecordToLog(logger, LogLevelEnum.DEBUG, "Failed to update state of tosca element vertex {} metadata. Status is  {}", toscaElementVertex.getUniqueId(), titatStatus);
1337                         result = Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(titatStatus));
1338                 } else {
1339                         result = Either.left(updateVertexRes.left().value());
1340                 }
1341                 return result;
1342         }
1343
1344         private Either<GraphVertex, StorageOperationStatus> changeStateToCheckedIn(LifecycleStateEnum currState, GraphVertex toscaElementVertex, GraphVertex ownerVertex, GraphVertex modifierVertex) {
1345                 Either<GraphVertex, StorageOperationStatus> result = null;
1346                 LifecycleStateEnum nextState = LifecycleStateEnum.NOT_CERTIFIED_CHECKIN;
1347                 String faileToUpdateStateMsg = "Failed to update state of tosca element {}. Status is  {}";
1348
1349                 if (currState == LifecycleStateEnum.READY_FOR_CERTIFICATION) {
1350                         // In case of cancel "ready for certification" remove last state edge with "STATE" property equals to "NOT_CERTIFIED_CHECKIN"
1351                         Map<GraphPropertyEnum, Object> vertexProperties = new HashMap<>();
1352                         vertexProperties.put(GraphPropertyEnum.STATE, nextState);
1353                         Either<Edge, TitanOperationStatus> deleteResult = titanDao.deleteBelongingEdgeByCriteria(toscaElementVertex, EdgeLabelEnum.LAST_STATE, vertexProperties);
1354                         if (deleteResult.isRight()) {
1355                                 CommonUtility.addRecordToLog(logger, LogLevelEnum.DEBUG, faileToUpdateStateMsg, toscaElementVertex.getUniqueId(), deleteResult.right().value());
1356                                 CommonUtility.addRecordToLog(logger, LogLevelEnum.DEBUG, "failed to update last state relation");
1357                                 result = Either.right(StorageOperationStatus.INCONSISTENCY);
1358                         }
1359                 }
1360                 if (result == null) {
1361                         // Remove CHECKOUT relation
1362                         Either<Edge, TitanOperationStatus> deleteEdgeResult = titanDao.deleteEdge(ownerVertex, toscaElementVertex, EdgeLabelEnum.STATE);
1363                         if (deleteEdgeResult.isRight()) {
1364                                 CommonUtility.addRecordToLog(logger, LogLevelEnum.DEBUG, faileToUpdateStateMsg, toscaElementVertex.getUniqueId());
1365                                 result = Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(deleteEdgeResult.right().value()));
1366                         }
1367                 }
1368                 if (result == null) {
1369                         // Create CHECKIN relation
1370                         Map<EdgePropertyEnum, Object> edgeProperties = new HashMap<>();
1371                         edgeProperties.put(EdgePropertyEnum.STATE, nextState);
1372                         TitanOperationStatus createEdgeRes = titanDao.createEdge(modifierVertex.getVertex(), toscaElementVertex.getVertex(), EdgeLabelEnum.STATE, edgeProperties);
1373                         if (createEdgeRes != TitanOperationStatus.OK) {
1374                                 CommonUtility.addRecordToLog(logger, LogLevelEnum.DEBUG, faileToUpdateStateMsg, toscaElementVertex.getUniqueId());
1375                                 result = Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(createEdgeRes));
1376                         }
1377                 }
1378                 if (result == null) {
1379                         result = Either.left(toscaElementVertex);
1380                 }
1381                 return result;
1382         }
1383
1384         private Either<GraphVertex, StorageOperationStatus> updateLastModifierEdge(GraphVertex toscaElementVertex, GraphVertex ownerVertex, GraphVertex modifierVertex) {
1385                 Either<GraphVertex, StorageOperationStatus> result = null;
1386                 if (!modifierVertex.getMetadataProperties().get(GraphPropertyEnum.USERID).equals(ownerVertex.getMetadataProperties().get(GraphPropertyEnum.USERID))) {
1387                         Either<Edge, TitanOperationStatus> deleteEdgeRes = titanDao.deleteEdge(ownerVertex, toscaElementVertex, EdgeLabelEnum.LAST_MODIFIER);
1388                         if (deleteEdgeRes.isRight()) {
1389                                 CommonUtility.addRecordToLog(logger, LogLevelEnum.DEBUG, "Failed to delete last modifier {} to tosca element {}. Edge type is {}", ownerVertex.getUniqueId(), ownerVertex.getUniqueId(), EdgeLabelEnum.LAST_MODIFIER);
1390                                 result = Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(deleteEdgeRes.right().value()));
1391                         }
1392                         if (result == null) {
1393                                 TitanOperationStatus createEdgeRes = titanDao.createEdge(modifierVertex.getVertex(), toscaElementVertex.getVertex(), EdgeLabelEnum.LAST_MODIFIER, new HashMap<>());
1394
1395                                 if (createEdgeRes != TitanOperationStatus.OK) {
1396                                         CommonUtility.addRecordToLog(logger, LogLevelEnum.DEBUG, "Failed to associate user {} to component {}. Edge type is {}", modifierVertex.getUniqueId(), ownerVertex.getUniqueId(), EdgeLabelEnum.LAST_MODIFIER);
1397                                         result = Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(createEdgeRes));
1398                                 } else {
1399                                         result = Either.left(modifierVertex);
1400                                 }
1401                         }
1402                 } else {
1403                         result = Either.left(ownerVertex);
1404                 }
1405                 return result;
1406         }
1407
1408         private Map<String, ImmutablePair<GraphPropertyEnum, JsonParseFlagEnum>> prepareParametersToGetVerticesForCheckin(String toscaElementId, String modifierId, String ownerId) {
1409                 Map<String, ImmutablePair<GraphPropertyEnum, JsonParseFlagEnum>> verticesToGetParameters = new HashMap<>();
1410                 verticesToGetParameters.put(toscaElementId, new ImmutablePair<>(GraphPropertyEnum.UNIQUE_ID, JsonParseFlagEnum.ParseMetadata));
1411                 verticesToGetParameters.put(modifierId, new ImmutablePair<>(GraphPropertyEnum.USERID, JsonParseFlagEnum.NoParse));
1412                 verticesToGetParameters.put(ownerId, new ImmutablePair<>(GraphPropertyEnum.USERID, JsonParseFlagEnum.NoParse));
1413                 return verticesToGetParameters;
1414         }
1415
1416         private Map<String, ImmutablePair<GraphPropertyEnum, JsonParseFlagEnum>> prepareParametersToGetVerticesForRequestCertification(String toscaElementId, String modifierId, String ownerId) {
1417                 Map<String, ImmutablePair<GraphPropertyEnum, JsonParseFlagEnum>> verticesToGetParameters = new HashMap<>();
1418                 verticesToGetParameters.put(toscaElementId, new ImmutablePair<>(GraphPropertyEnum.UNIQUE_ID, JsonParseFlagEnum.ParseAll));
1419                 verticesToGetParameters.put(modifierId, new ImmutablePair<>(GraphPropertyEnum.USERID, JsonParseFlagEnum.NoParse));
1420                 verticesToGetParameters.put(ownerId, new ImmutablePair<>(GraphPropertyEnum.USERID, JsonParseFlagEnum.NoParse));
1421                 return verticesToGetParameters;
1422         }
1423
1424         private Map<String, ImmutablePair<GraphPropertyEnum, JsonParseFlagEnum>> prepareParametersToGetVerticesForCheckout(String toscaElementId, String modifierId, String ownerId) {
1425                 Map<String, ImmutablePair<GraphPropertyEnum, JsonParseFlagEnum>> verticesToGetParameters = new HashMap<>();
1426                 verticesToGetParameters.put(toscaElementId, new ImmutablePair<>(GraphPropertyEnum.UNIQUE_ID, JsonParseFlagEnum.ParseAll));
1427                 verticesToGetParameters.put(modifierId, new ImmutablePair<>(GraphPropertyEnum.USERID, JsonParseFlagEnum.NoParse));
1428                 verticesToGetParameters.put(ownerId, new ImmutablePair<>(GraphPropertyEnum.USERID, JsonParseFlagEnum.NoParse));
1429                 return verticesToGetParameters;
1430         }
1431
1432         private String getNextVersion(String currVersion) {
1433                 String[] versionParts = currVersion.split(VERSION_DELIMETER_REGEXP);
1434                 Integer minorVersion = Integer.parseInt(versionParts[1]) + 1;
1435                 return versionParts[0] + VERSION_DELIMETER + minorVersion;
1436         }
1437
1438         private Integer getMinorVersion(String version) {
1439                 String[] versionParts = version.split(VERSION_DELIMETER_REGEXP);
1440                 return Integer.parseInt(versionParts[1]);
1441         }
1442
1443         private Integer getMajorVersion(String version) {
1444                 String[] versionParts = version.split(VERSION_DELIMETER_REGEXP);
1445                 return Integer.parseInt(versionParts[0]);
1446         }
1447
1448         private boolean isFirstCheckoutAfterCertification(String version) {
1449                 if (Integer.parseInt(version.split(VERSION_DELIMETER_REGEXP)[0]) != 0 && Integer.parseInt(version.split(VERSION_DELIMETER_REGEXP)[1]) == 1) {
1450                         return true;
1451                 }
1452                 return false;
1453         }
1454
1455         public Either<ToscaElement,StorageOperationStatus> forceCerificationOfToscaElement(String toscaElementId, String modifierId, String ownerId) {
1456                 Either<GraphVertex, StorageOperationStatus> resultUpdate = null;
1457                 Either<ToscaElement, StorageOperationStatus> result = null;
1458                 GraphVertex toscaElement = null;
1459                 GraphVertex modifier = null;
1460                 GraphVertex owner;
1461                 try {
1462                         Either<Map<String, GraphVertex>, TitanOperationStatus> getVerticesRes = titanDao.getVerticesByUniqueIdAndParseFlag(prepareParametersToGetVerticesForRequestCertification(toscaElementId, modifierId, ownerId));
1463                         if (getVerticesRes.isRight()) {
1464                                 CommonUtility.addRecordToLog(logger, LogLevelEnum.DEBUG, FAILED_TO_GET_VERTICES, toscaElementId);
1465                                 result = Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(getVerticesRes.right().value()));
1466                         }
1467                         if (result == null) {
1468                                 toscaElement = getVerticesRes.left().value().get(toscaElementId);
1469                                 modifier = getVerticesRes.left().value().get(modifierId);
1470                                 owner = getVerticesRes.left().value().get(ownerId);
1471
1472                                 StorageOperationStatus status = handleRelationsUponForceCertification(toscaElement, modifier, owner);
1473                                 if (status != StorageOperationStatus.OK) {
1474                                         CommonUtility.addRecordToLog(logger, LogLevelEnum.DEBUG, "Failed to handle relations on certification request for tosca element {}. Status is {}. ", toscaElement.getUniqueId(), status);
1475                                 }
1476                         }
1477                         if (result == null) {
1478                                 LifecycleStateEnum nextState = LifecycleStateEnum.CERTIFIED;
1479
1480                                 toscaElement.addMetadataProperty(GraphPropertyEnum.STATE, LifecycleStateEnum.CERTIFIED.name());
1481                                 toscaElement.addMetadataProperty(GraphPropertyEnum.VERSION, "1.0");
1482
1483                                 resultUpdate = updateToscaElementVertexMetadataPropertiesAndJson(toscaElement);
1484                                 if (resultUpdate.isRight()) {
1485                                         CommonUtility.addRecordToLog(logger, LogLevelEnum.DEBUG, "Failed to set lifecycle for tosca elememt {} to state {}, error: {}", toscaElement.getUniqueId(), nextState, resultUpdate.right().value());
1486                                         result = Either.right(resultUpdate.right().value());
1487                                 }
1488                         }
1489                         if (result == null) {
1490                                 ToscaElementOperation operation = getToscaElementOperation(toscaElement.getLabel());
1491                                 result = operation.getToscaElement(toscaElement.getUniqueId());
1492                         }
1493                         return result;
1494
1495                 } catch (Exception e) {
1496                         CommonUtility.addRecordToLog(logger, LogLevelEnum.DEBUG, "Exception occured during request certification tosca element {}. {}", toscaElementId, e.getMessage());
1497                 }
1498                 return result;
1499         }
1500
1501         private StorageOperationStatus handleRelationsUponForceCertification(GraphVertex toscaElement, GraphVertex modifier, GraphVertex owner) {
1502
1503                         StorageOperationStatus result = null;
1504                         TitanOperationStatus status = titanDao.replaceEdgeLabel(owner.getVertex(), toscaElement.getVertex(), EdgeLabelEnum.STATE, EdgeLabelEnum.LAST_STATE);
1505                         if (status != TitanOperationStatus.OK) {
1506                                 result = DaoStatusConverter.convertTitanStatusToStorageStatus(status);
1507                         }
1508                         if (result == null) {
1509                                 Map<EdgePropertyEnum, Object> properties = new EnumMap<>(EdgePropertyEnum.class);
1510                                 properties.put(EdgePropertyEnum.STATE, LifecycleStateEnum.CERTIFIED);
1511                                 status = titanDao.createEdge(modifier, toscaElement, EdgeLabelEnum.STATE, properties);
1512                                 if (status != TitanOperationStatus.OK) {
1513                                         CommonUtility.addRecordToLog(logger, LogLevelEnum.DEBUG, "failed to create edge. Status is {}", status);
1514                                         result = DaoStatusConverter.convertTitanStatusToStorageStatus(status);
1515                                 }
1516                         }
1517                         if (result == null) {
1518                                 result = StorageOperationStatus.OK;
1519                         }
1520                         return result;
1521         }
1522 }