Change openecomp to onap and update license
[aai/aai-common.git] / aai-core / src / main / java / org / onap / aai / dbmap / AAIGraph.java
1 /**
2  * ============LICENSE_START=======================================================
3  * org.onap.aai
4  * ================================================================================
5  * Copyright © 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  * ECOMP is a trademark and service mark of AT&T Intellectual Property.
21  */
22 package org.onap.aai.dbmap;
23
24 import java.io.FileInputStream;
25 import java.io.FileNotFoundException;
26 import java.io.IOException;
27 import java.io.InputStream;
28 import java.util.HashMap;
29 import java.util.Map;
30 import java.util.Properties;
31
32 import org.apache.commons.lang.exception.ExceptionUtils;
33 import org.apache.tinkerpop.gremlin.structure.Graph;
34 import org.apache.tinkerpop.gremlin.structure.io.IoCore;
35 import org.onap.aai.dbgen.SchemaGenerator;
36 import org.onap.aai.exceptions.AAIException;
37 import org.onap.aai.util.AAIConstants;
38
39 import com.att.eelf.configuration.EELFLogger;
40 import com.att.eelf.configuration.EELFManager;
41 import com.thinkaurelius.titan.core.TitanFactory;
42 import com.thinkaurelius.titan.core.TitanGraph;
43 import com.thinkaurelius.titan.core.schema.TitanManagement;
44
45 /**
46  * Database Mapping class which acts as the middle man between the REST
47  * interface objects and Titan DB objects. This class provides methods to commit
48  * the objects received on the REST interface into the Titan graph database as
49  * vertices and edges. Transactions are also managed here by using a TitanGraph
50  * object to load, commit/rollback and shutdown for each request. The data model
51  * rules such as keys/required properties are handled by calling DBMeth methods
52  * which are driven by a specification file in json.
53  * 
54  
55  */
56 public class AAIGraph {
57
58         private static final EELFLogger logger = EELFManager.getInstance().getLogger(AAIGraph.class);
59         protected static final String COMPONENT = "aaidbmap";
60         protected Map<String, TitanGraph> graphs = new HashMap<>();
61         private final String REALTIME_DB = "realtime";
62         private final String CACHED_DB = "cached";
63
64
65
66         /**
67          * Instantiates a new AAI graph.
68          */
69         private AAIGraph() {
70                 try {
71                         String rtConfig = System.getProperty("realtime.db.config");
72                         String cachedConfig = System.getProperty("cached.db.config");
73                         if (rtConfig == null) {
74                                 rtConfig = AAIConstants.REALTIME_DB_CONFIG;
75                         }
76                         if (cachedConfig == null) {
77                                 cachedConfig = AAIConstants.CACHED_DB_CONFIG;
78                         }
79                         this.loadGraph(REALTIME_DB, rtConfig);
80                         this.loadGraph(CACHED_DB, cachedConfig);
81                 } catch (Exception e) {
82                         throw new RuntimeException("Failed to instantiate graphs", e);
83                 }
84         }
85         
86         private static class Helper {
87                 private static final AAIGraph INSTANCE = new AAIGraph();
88         }
89         
90         /**
91          * Gets the single instance of AAIGraph.
92          *
93          * @return single instance of AAIGraph
94          */
95         public static AAIGraph getInstance() {
96                 return Helper.INSTANCE;
97         }
98         
99         private void loadGraph(String name, String configPath) throws AAIException {
100             // Graph being opened by TitanFactory is being placed in hashmap to be used later
101                 // These graphs shouldn't be closed until the application shutdown
102             TitanGraph graph = TitanFactory.open(configPath);
103                 try (InputStream is = new FileInputStream(configPath)) {
104
105                         Properties graphProps = new Properties();
106                         graphProps.load(is);
107
108                         if ("inmemory".equals(graphProps.get("storage.backend"))) {
109                                 // Load the propertyKeys, indexes and edge-Labels into the DB
110                                 loadSchema(graph);
111                                 loadSnapShotToInMemoryGraph(graph, graphProps);
112                         }
113
114                         if (graph == null) {
115                                 throw new AAIException("AAI_5102");
116                         }
117
118                         graphs.put(name, graph);
119                 } catch (FileNotFoundException fnfe) {
120                         throw new AAIException("AAI_4001");
121             } catch (IOException e) {
122                         throw new AAIException("AAI_4002");
123             }
124         }
125
126         private void loadSnapShotToInMemoryGraph(TitanGraph graph, Properties graphProps) {
127                 if (logger.isDebugEnabled()) {
128                         logger.debug("Load Snapshot to InMemory Graph");
129                 }
130                 if (graphProps.containsKey("load.snapshot.file")) {
131                         String value = graphProps.getProperty("load.snapshot.file");
132                         if ("true".equals(value)) {
133                                 try (Graph transaction = graph.newTransaction()) {
134                                         String location = System.getProperty("snapshot.location");
135                                         logAndPrint(logger, "Loading snapshot to inmemory graph.");
136                                         transaction.io(IoCore.graphson()).readGraph(location);
137                                         transaction.tx().commit();
138                                         logAndPrint(logger, "Snapshot loaded to inmemory graph.");
139                                 } catch (Exception e) {
140                                         logAndPrint(logger,
141                                                 "ERROR: Could not load datasnapshot to in memory graph. \n"
142                                                         + ExceptionUtils.getFullStackTrace(e));
143                                         System.exit(0);
144                                 }
145                         }
146                 }
147         }
148
149         private void loadSchema(TitanGraph graph) {
150                 // Load the propertyKeys, indexes and edge-Labels into the DB
151                 TitanManagement graphMgt = graph.openManagement();
152                 
153                 System.out.println("-- loading schema into Titan");
154                 SchemaGenerator.loadSchemaIntoTitan( graph, graphMgt );
155         }
156
157         /**
158          * Graph shutdown.
159          */
160         public void graphShutdown() {
161                 graphs.get(REALTIME_DB).close();
162         }
163
164         /**
165          * Gets the graph.
166          *
167          * @return the graph
168          */
169         public TitanGraph getGraph() {
170                 return graphs.get(REALTIME_DB);
171         }
172         
173         public void graphShutdown(DBConnectionType connectionType) {
174                 
175                 graphs.get(this.getGraphName(connectionType)).close();
176         }
177         
178         public TitanGraph getGraph(DBConnectionType connectionType) {
179                 return graphs.get(this.getGraphName(connectionType));
180         }
181         
182         private String getGraphName(DBConnectionType connectionType) {
183                 String graphName = "";
184                 if (DBConnectionType.CACHED.equals(connectionType)) {
185                         graphName = this.CACHED_DB;
186                 } else if (DBConnectionType.REALTIME.equals(connectionType)) {
187                         graphName = this.REALTIME_DB;
188                 }
189                 
190                 return graphName;
191         }
192         
193         private void logAndPrint(EELFLogger logger, String msg) {
194                 System.out.println(msg);
195                 logger.info(msg);
196         }
197 }