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