Merge "[AAI] Fix doc config files"
[aai/aai-common.git] / aai-core / src / main / java / org / onap / aai / dbgen / SchemaGenerator4Hist.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
21 package org.onap.aai.dbgen;
22
23 import static org.onap.aai.db.props.AAIProperties.*;
24
25 import com.google.common.collect.Multimap;
26
27 import java.util.HashMap;
28 import java.util.HashSet;
29 import java.util.Map;
30 import java.util.Optional;
31 import java.util.Set;
32
33 import org.apache.tinkerpop.gremlin.structure.Vertex;
34 import org.janusgraph.core.Cardinality;
35 import org.janusgraph.core.Multiplicity;
36 import org.janusgraph.core.PropertyKey;
37 import org.janusgraph.core.schema.JanusGraphManagement;
38 import org.onap.aai.config.SpringContextAware;
39 import org.onap.aai.edges.EdgeIngestor;
40 import org.onap.aai.edges.EdgeRule;
41 import org.onap.aai.edges.exceptions.EdgeRuleNotFoundException;
42 import org.onap.aai.introspection.Introspector;
43 import org.onap.aai.introspection.Loader;
44 import org.onap.aai.introspection.LoaderUtil;
45 import org.onap.aai.logging.LogFormatTools;
46 import org.onap.aai.schema.enums.PropertyMetadata;
47 import org.onap.aai.util.AAIConfig;
48 import org.slf4j.Logger;
49 import org.slf4j.LoggerFactory;
50
51 public class SchemaGenerator4Hist {
52
53     private static final Logger LOGGER = LoggerFactory.getLogger(SchemaGenerator4Hist.class);
54
55     private SchemaGenerator4Hist() {
56
57     }
58
59     /**
60      * Load schema into JanusGraph.
61      *
62      * @param graphMgmt
63      *        the graph mgmt
64      */
65     public static void loadSchemaIntoJanusGraph(final JanusGraphManagement graphMgmt, String backend) {
66
67         try {
68             AAIConfig.init();
69         } catch (Exception ex) {
70             LOGGER.error(" ERROR - Could not run AAIConfig.init(). {}", LogFormatTools.getStackTop(ex));
71             System.exit(1);
72         }
73
74         // NOTE - JanusGraph 0.5.3 doesn't keep a list of legal node Labels.
75         // They are only used when a vertex is actually being created.
76         // JanusGraph 1.1 will keep track (we think).
77
78         // Use EdgeRules to make sure edgeLabels are defined in the db. NOTE:
79         // the multiplicty used here is
80         // always "MULTI". This is not the same as our internal "Many2Many",
81         // "One2One", "One2Many" or "Many2One"
82         // We use the same edge-label for edges between many different types of
83         // nodes and our internal
84         // multiplicty definitions depends on which two types of nodes are being
85         // connected.
86
87         Multimap<String, EdgeRule> edges = null;
88         Set<String> labels = new HashSet<>();
89
90         EdgeIngestor edgeIngestor = SpringContextAware.getBean(EdgeIngestor.class);
91
92         try {
93             edges = edgeIngestor.getAllCurrentRules();
94         } catch (EdgeRuleNotFoundException e) {
95             LOGGER.error("Unable to find all rules {}", LogFormatTools.getStackTop(e));
96         }
97
98         for (EdgeRule rule : edges.values()) {
99             labels.add(rule.getLabel());
100         }
101
102         for (String label : labels) {
103             if (graphMgmt.containsRelationType(label)) {
104                 LOGGER.debug(" EdgeLabel  [{}] already existed. ", label);
105             } else {
106                 LOGGER.debug("Making EdgeLabel: [{}]", label);
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                     LOGGER.debug(" PropertyKey  [{}] already existed in the DB. ", dbPropName);
125                 } else {
126                     Class<?> type = obj.getClass(propName);
127                     Cardinality cardinality = Cardinality.LIST;
128                     boolean process = false;
129                     if (obj.isListType(propName) && obj.isSimpleGenericType(propName)) {
130                         // NOTE - For history - All properties have cardinality = LIST
131                         // It is assumed that there is special processing in the Resources MS
132                         // for History to turn what used to be SET (referred to as isListType
133                         // above) will be stored in our db as a single String. And that
134                         // single string will have Cardinality = LIST so we can track its
135                         // history.
136                         type = obj.getGenericTypeClass(propName);
137                         process = true;
138                     } else if (obj.isSimpleType(propName)) {
139                         process = true;
140                     }
141
142                     if (process) {
143
144                         LOGGER.info(" Creating PropertyKey: [{}], [{}], [{}]", dbPropName, type.getSimpleName(),
145                                 cardinality);
146                         PropertyKey propK;
147                         if (!seenProps.containsKey(dbPropName)) {
148                             propK = graphMgmt.makePropertyKey(dbPropName).dataType(type).cardinality(cardinality)
149                                     .make();
150                             seenProps.put(dbPropName, propK);
151                         } else {
152                             propK = seenProps.get(dbPropName);
153                         }
154                         if (graphMgmt.containsGraphIndex(dbPropName)) {
155                             LOGGER.debug(" Index  [{}] already existed in the DB. ", dbPropName);
156                         } else {
157                             if (obj.getIndexedProperties().contains(propName)) {
158                                 // NOTE - for History we never add a unique index - just a regular index
159                                 LOGGER.info("Add index for PropertyKey: [{}]", dbPropName);
160                                 graphMgmt.buildIndex(dbPropName, Vertex.class).addKey(propK).buildCompositeIndex();
161                             } else {
162                                 LOGGER.info("No index needed/added for PropertyKey: [{}]", dbPropName);
163                             }
164                         }
165                     }
166                 }
167             }
168         } // Done processing all properties defined in the OXM
169
170         // Add the 3 new History properties are in the DB
171         // They are all Cardinality=Single since instance of a Node, Edge or Property can
172         // only have one of them. That is, a Property can show up many times in a
173         // node, but each instance of that property will only have a single start-ts,
174         // end-ts, end-source-of-truth. Same goes for a node or edge itself.
175         makeNewProperty(graphMgmt, seenProps, String.class, END_SOT);
176         makeNewProperty(graphMgmt, seenProps, Long.class, START_TS);
177         makeNewProperty(graphMgmt, seenProps, Long.class, END_TS);
178         makeNewProperty(graphMgmt, seenProps, String.class, START_TX_ID);
179         makeNewProperty(graphMgmt, seenProps, String.class, END_TX_ID);
180
181         String imsg = "-- About to call graphMgmt commit";
182         LOGGER.info(imsg);
183         graphMgmt.commit();
184         if (backend != null) {
185             LOGGER.info("Successfully loaded the schema to {}", backend);
186         }
187
188     }
189
190     private static <T> void makeNewProperty(JanusGraphManagement graphMgmt, Map<String, PropertyKey> seenProps,
191             Class<T> type, String propertyName) {
192         if (graphMgmt.containsRelationType(propertyName)) {
193             LOGGER.debug("PropertyKey [{}] already existed in the DB.", propertyName);
194         } else if (!seenProps.containsKey(propertyName)) {
195             LOGGER.info("Creating PropertyKey: [{}], [{}], [{}]", propertyName, type.getSimpleName(),
196                     Cardinality.SINGLE);
197             graphMgmt.makePropertyKey(propertyName).dataType(type).cardinality(Cardinality.SINGLE).make();
198         }
199     }
200 }