Merge "AAI-1523 Tweak onap-java-formatter.xml"
[aai/aai-common.git] / aai-core / src / main / java / org / onap / aai / dbgen / SchemaGenerator.java
1 /**
2  * ============LICENSE_START=======================================================
3  * org.onap.aai
4  * ================================================================================
5  * Copyright © 2017-2018 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 package org.onap.aai.dbgen;
21
22 import java.util.HashMap;
23 import java.util.HashSet;
24 import java.util.Map;
25 import java.util.Optional;
26 import java.util.Set;
27
28 import org.apache.tinkerpop.gremlin.structure.Vertex;
29 import org.onap.aai.config.SpringContextAware;
30 import org.onap.aai.db.props.AAIProperties;
31 import org.onap.aai.edges.EdgeIngestor;
32 import org.onap.aai.edges.exceptions.EdgeRuleNotFoundException;
33 import org.onap.aai.introspection.*;
34 import org.onap.aai.logging.LogFormatTools;
35 import org.onap.aai.schema.enums.PropertyMetadata;
36 import org.onap.aai.edges.EdgeRule;
37 import org.onap.aai.setup.SchemaVersions;
38 import org.onap.aai.util.AAIConfig;
39
40 import com.att.eelf.configuration.EELFLogger;
41 import com.att.eelf.configuration.EELFManager;
42 import com.google.common.collect.Multimap;
43 import org.janusgraph.core.Cardinality;
44 import org.janusgraph.core.Multiplicity;
45 import org.janusgraph.core.PropertyKey;
46 import org.janusgraph.core.JanusGraph;
47 import org.janusgraph.core.schema.JanusGraphManagement;
48
49 public class SchemaGenerator {
50
51         private static final EELFLogger LOGGER = EELFManager.getInstance().getLogger(SchemaGenerator.class);
52
53         /**
54          * Load schema into JanusGraph.
55          *
56          * @param graph
57          *            the graph
58          * @param graphMgmt
59          *            the graph mgmt
60          */
61         public static void loadSchemaIntoJanusGraph(final JanusGraph graph, final JanusGraphManagement graphMgmt,
62                         String backend) {
63
64                 try {
65                         AAIConfig.init();
66                 } catch (Exception ex) {
67                         LOGGER.error(" ERROR - Could not run AAIConfig.init(). " + LogFormatTools.getStackTop(ex));
68                         //System.out.println(" ERROR - Could not run AAIConfig.init(). ");
69                         System.exit(1);
70                 }
71
72                 // NOTE - JanusGraph 0.5.3 doesn't keep a list of legal node Labels.
73                 // They are only used when a vertex is actually being created.
74                 // JanusGraph 1.1 will keep track (we think).
75
76                 // Use EdgeRules to make sure edgeLabels are defined in the db. NOTE:
77                 // the multiplicty used here is
78                 // always "MULTI". This is not the same as our internal "Many2Many",
79                 // "One2One", "One2Many" or "Many2One"
80                 // We use the same edge-label for edges between many different types of
81                 // nodes and our internal
82                 // multiplicty definitions depends on which two types of nodes are being
83                 // connected.
84
85                 Multimap<String, EdgeRule> edges = null;
86                 Set<String> labels = new HashSet<>();
87
88                 EdgeIngestor edgeIngestor = SpringContextAware.getBean(EdgeIngestor.class);
89
90                 try {
91                         edges = edgeIngestor.getAllCurrentRules();
92                 } catch (EdgeRuleNotFoundException e) {
93                         LOGGER.error("Unable to find all rules {}", LogFormatTools.getStackTop(e));
94                 }
95
96                 for (EdgeRule rule : edges.values()) {
97                         labels.add(rule.getLabel());
98                 }
99
100                 for (String label : labels) {
101                         if (graphMgmt.containsRelationType(label)) {
102                                 String dmsg = " EdgeLabel  [" + label + "] already existed. ";
103                                 LOGGER.debug(dmsg);
104                         } else {
105                                 String dmsg = "Making EdgeLabel: [" + label + "]";
106                                 LOGGER.debug(dmsg);
107                                 graphMgmt.makeEdgeLabel(label).multiplicity(Multiplicity.valueOf("MULTI")).make();
108                         }
109                 }
110
111                 Loader loader = LoaderUtil.getLatestVersion();
112
113                 Map<String, Introspector> objs = loader.getAllObjects();
114                 Map<String, PropertyKey> seenProps = new HashMap<>();
115
116                 for (Introspector obj : objs.values()) {
117                         for (String propName : obj.getProperties()) {
118                                 String dbPropName = propName;
119                                 Optional<String> alias = obj.getPropertyMetadata(propName, PropertyMetadata.DB_ALIAS);
120                                 if (alias.isPresent()) {
121                                         dbPropName = alias.get();
122                                 }
123                                 if (graphMgmt.containsRelationType(dbPropName)) {
124                                         String dmsg = " PropertyKey  [" + dbPropName + "] already existed in the DB. ";
125                                         LOGGER.debug(dmsg);
126                                 } else {
127                                         Class<?> type = obj.getClass(propName);
128                                         Cardinality cardinality = Cardinality.SINGLE;
129                                         boolean process = false;
130                                         if (obj.isListType(propName) && obj.isSimpleGenericType(propName)) {
131                                                 cardinality = Cardinality.SET;
132                                                 type = obj.getGenericTypeClass(propName);
133                                                 process = true;
134                                         } else if (obj.isSimpleType(propName)) {
135                                                 process = true;
136                                         }
137
138                                         if (process) {
139
140                                                 String imsg = "Creating PropertyKey: [" + dbPropName + "], [" + type.getSimpleName() + "], ["
141                                                                 + cardinality + "]";
142                                                 LOGGER.info(imsg);
143                                                 PropertyKey propK;
144                                                 if (!seenProps.containsKey(dbPropName)) {
145                                                         propK = graphMgmt.makePropertyKey(dbPropName).dataType(type).cardinality(cardinality)
146                                                                         .make();
147                                                         seenProps.put(dbPropName, propK);
148                                                 } else {
149                                                         propK = seenProps.get(dbPropName);
150                                                 }
151                                                 if (graphMgmt.containsGraphIndex(dbPropName)) {
152                                                         String dmsg = " Index  [" + dbPropName + "] already existed in the DB. ";
153                                                         LOGGER.debug(dmsg);
154                                                 } else {
155                                                         if (obj.getIndexedProperties().contains(propName)) {
156                                                                 if (obj.getUniqueProperties().contains(propName)) {
157                                                                         imsg = "Add Unique index for PropertyKey: [" + dbPropName + "]";
158                                                                         LOGGER.info(imsg);
159                                                                         graphMgmt.buildIndex(dbPropName, Vertex.class).addKey(propK).unique()
160                                                                                         .buildCompositeIndex();
161                                                                 } else {
162                                                                         imsg = "Add index for PropertyKey: [" + dbPropName + "]";
163                                                                         LOGGER.info(imsg);
164                                                                         graphMgmt.buildIndex(dbPropName, Vertex.class).addKey(propK).buildCompositeIndex();
165                                                                 }
166                                                         } else {
167                                                                 imsg = "No index added for PropertyKey: [" + dbPropName + "]";
168                                                                 LOGGER.info(imsg);
169                                                         }
170                                                 }
171                                         }
172                                 }
173                         }
174                 }
175
176                 String imsg = "-- About to call graphMgmt commit";
177                 LOGGER.info(imsg);
178                 if(backend != null){
179                         LOGGER.info("Successfully loaded the schema to " + backend);
180                 }
181
182                 graphMgmt.commit();
183         }
184
185 }