Added oparent to sdc main
[sdc.git] / catalog-be / src / test / java / org / openecomp / sdc / be / components / path / beans / InMemoryJanusGraphClient.java
1 /*-
2  * ============LICENSE_START=======================================================
3  * SDC
4  * ================================================================================
5  * Copyright (C) 2019 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.components.path.beans;
22
23
24 import org.janusgraph.core.*;
25 import org.janusgraph.core.schema.ConsistencyModifier;
26 import org.janusgraph.core.schema.JanusGraphIndex;
27 import org.janusgraph.core.schema.JanusGraphManagement;
28 import org.janusgraph.core.util.JanusGraphCleanup;
29 import org.janusgraph.diskstorage.BackendException;
30 import org.janusgraph.diskstorage.ResourceUnavailableException;
31 import org.janusgraph.diskstorage.locking.PermanentLockingException;
32 import org.janusgraph.graphdb.database.idassigner.IDPoolExhaustedException;
33 import fj.data.Either;
34 import org.apache.tinkerpop.gremlin.structure.Vertex;
35 import org.openecomp.sdc.be.dao.JanusGraphClientStrategy;
36 import org.openecomp.sdc.be.dao.janusgraph.JanusGraphOperationStatus;
37 import org.openecomp.sdc.be.dao.neo4j.GraphPropertiesDictionary;
38 import org.openecomp.sdc.be.dao.janusgraph.JanusGraphClient;
39 import org.slf4j.Logger;
40 import org.slf4j.LoggerFactory;
41 import org.springframework.stereotype.Component;
42
43 import javax.annotation.PostConstruct;
44 import java.util.ArrayList;
45 import java.util.HashMap;
46
47 @Component("janusgraph-client")
48 public class InMemoryJanusGraphClient extends JanusGraphClient {
49
50
51     private static final Logger logger = LoggerFactory.getLogger(InMemoryJanusGraphClient.class);
52
53     private static final String OK = "GOOD";
54
55     public InMemoryJanusGraphClient() {
56     }
57
58
59     private JanusGraph graph;
60     JanusGraphClientStrategy janusGraphClientStrategy;
61
62     public InMemoryJanusGraphClient(JanusGraphClientStrategy janusGraphClientStrategy) {
63         super();
64         this.janusGraphClientStrategy = janusGraphClientStrategy;
65         logger.info("** JanusGraphClient created");
66     }
67
68     @PostConstruct
69     public JanusGraphOperationStatus createGraph() {
70
71         logger.info("** createGraph started **");
72         graph = JanusGraphFactory.build().set("storage.backend", "inmemory").open();
73         createJanusGraphSchema();
74
75         logger.info("** in memory graph created");
76         return JanusGraphOperationStatus.OK;
77
78     }
79
80
81     public void cleanupGraph() {
82         if (graph != null) {
83             // graph.shutdown();
84             graph.close();
85             try {
86                 JanusGraphFactory.drop(graph);
87             } catch (BackendException e) {
88                 e.printStackTrace();
89             }
90         }
91     }
92
93     public JanusGraphOperationStatus createGraph(String janusGraphCfgFile) {
94         logger.info("** open graph with {} started", janusGraphCfgFile);
95         try {
96             logger.info("openGraph : try to load file {}", janusGraphCfgFile);
97             graph = JanusGraphFactory.open(janusGraphCfgFile);
98             if (graph.isClosed()) {
99                 logger.error("janusgraph graph was not initialized");
100                 return JanusGraphOperationStatus.NOT_CREATED;
101             }
102
103         } catch (Exception e) {
104             this.graph = null;
105             logger.info("createGraph : failed to open JanusGraph graph with configuration file: {}", janusGraphCfgFile, e);
106             return JanusGraphOperationStatus.NOT_CONNECTED;
107         }
108
109         logger.info("** JanusGraph graph created ");
110
111         return JanusGraphOperationStatus.OK;
112     }
113
114
115     public Either<JanusGraph, JanusGraphOperationStatus> getGraph() {
116         if (graph != null) {
117             return Either.left(graph);
118         } else {
119             return Either.right(JanusGraphOperationStatus.NOT_CREATED);
120         }
121     }
122
123     public JanusGraphOperationStatus commit() {
124         if (graph != null) {
125             try {
126                 graph.tx().commit();
127                 return JanusGraphOperationStatus.OK;
128             } catch (Exception e) {
129                 return handleJanusGraphException(e);
130             }
131         } else {
132             return JanusGraphOperationStatus.NOT_CREATED;
133         }
134     }
135
136     public JanusGraphOperationStatus rollback() {
137         if (graph != null) {
138             try {
139                 // graph.rollback();
140                 graph.tx().rollback();
141                 return JanusGraphOperationStatus.OK;
142             } catch (Exception e) {
143                 return handleJanusGraphException(e);
144             }
145         } else {
146             return JanusGraphOperationStatus.NOT_CREATED;
147         }
148     }
149
150     public static JanusGraphOperationStatus handleJanusGraphException(Exception e) {
151         if (e instanceof JanusGraphConfigurationException) {
152             return JanusGraphOperationStatus.JANUSGRAPH_CONFIGURATION;
153         }
154         if (e instanceof SchemaViolationException) {
155             return JanusGraphOperationStatus.JANUSGRAPH_SCHEMA_VIOLATION;
156         }
157         if (e instanceof PermanentLockingException) {
158             return JanusGraphOperationStatus.JANUSGRAPH_SCHEMA_VIOLATION;
159         }
160         if (e instanceof IDPoolExhaustedException) {
161             return JanusGraphOperationStatus.GENERAL_ERROR;
162         }
163         if (e instanceof InvalidElementException) {
164             return JanusGraphOperationStatus.INVALID_ELEMENT;
165         }
166         if (e instanceof InvalidIDException) {
167             return JanusGraphOperationStatus.INVALID_ID;
168         }
169         if (e instanceof QueryException) {
170             return JanusGraphOperationStatus.INVALID_QUERY;
171         }
172         if (e instanceof ResourceUnavailableException) {
173             return JanusGraphOperationStatus.RESOURCE_UNAVAILABLE;
174         }
175         if (e instanceof IllegalArgumentException) {
176             // TODO check the error message??
177             return JanusGraphOperationStatus.ILLEGAL_ARGUMENT;
178         }
179
180         return JanusGraphOperationStatus.GENERAL_ERROR;
181     }
182
183     public boolean getHealth() {
184         return true;
185     }
186
187     private boolean isGraphOpen() {
188         return true;
189     }
190
191
192     private static final String JANUSGRAPH_HEALTH_CHECK_STR = "janusGraphHealthCheck";
193
194
195     private void createJanusGraphSchema() {
196
197         JanusGraphManagement graphMgt = graph.openManagement();
198         JanusGraphIndex index = null;
199         for (GraphPropertiesDictionary prop : GraphPropertiesDictionary.values()) {
200             PropertyKey propKey = null;
201             if (!graphMgt.containsPropertyKey(prop.getProperty())) {
202                 Class<?> clazz = prop.getClazz();
203                 if (!ArrayList.class.getName().equals(clazz.getName()) && !HashMap.class.getName().equals(clazz.getName())) {
204                     propKey = graphMgt.makePropertyKey(prop.getProperty()).dataType(prop.getClazz()).make();
205                 }
206             } else {
207                 propKey = graphMgt.getPropertyKey(prop.getProperty());
208             }
209             if (prop.isIndexed()) {
210                 if (!graphMgt.containsGraphIndex(prop.getProperty())) {
211                     if (prop.isUnique()) {
212                         index = graphMgt.buildIndex(prop.getProperty(), Vertex.class).addKey(propKey).unique().buildCompositeIndex();
213
214                         graphMgt.setConsistency(propKey, ConsistencyModifier.LOCK); // Ensures
215                         // only
216                         // one
217                         // name
218                         // per
219                         // vertex
220                         graphMgt.setConsistency(index, ConsistencyModifier.LOCK); // Ensures
221                         // name
222                         // uniqueness
223                         // in
224                         // the
225                         // graph
226
227                     } else {
228                         graphMgt.buildIndex(prop.getProperty(), Vertex.class).addKey(propKey).buildCompositeIndex();
229                     }
230                 }
231             }
232         }
233         graphMgt.commit();
234     }
235
236 }