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