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