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