Resolved below sonar issues:
[aai/aai-service.git] / ajsc-aai / src / main / java / org / openecomp / aai / db / schema / AuditOXM.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.db.schema;
22
23 import com.google.common.collect.Multimap;
24 import com.thinkaurelius.titan.core.Cardinality;
25 import com.thinkaurelius.titan.core.Multiplicity;
26 import com.thinkaurelius.titan.core.schema.SchemaStatus;
27 import java.io.IOException;
28 import java.util.Arrays;
29 import java.util.Collection;
30 import java.util.HashSet;
31 import java.util.LinkedHashSet;
32 import java.util.List;
33 import java.util.Objects;
34 import java.util.Set;
35 import javax.xml.XMLConstants;
36 import javax.xml.parsers.DocumentBuilder;
37 import javax.xml.parsers.DocumentBuilderFactory;
38 import javax.xml.parsers.ParserConfigurationException;
39 import org.openecomp.aai.db.AAIProperties;
40 import org.openecomp.aai.dbmodel.DbEdgeRules;
41 import org.openecomp.aai.introspection.Introspector;
42 import org.openecomp.aai.introspection.Loader;
43 import org.openecomp.aai.introspection.LoaderFactory;
44 import org.openecomp.aai.introspection.ModelType;
45 import org.openecomp.aai.introspection.Version;
46 import org.openecomp.aai.logging.LogLineBuilder;
47 import org.openecomp.aai.util.AAIConstants;
48 import org.slf4j.Logger;
49 import org.slf4j.LoggerFactory;
50 import org.w3c.dom.Document;
51 import org.w3c.dom.NodeList;
52 import org.xml.sax.SAXException;
53
54 public class AuditOXM extends Auditor {
55
56     private static final Logger log = LoggerFactory.getLogger(AuditOXM.class);
57     private Set<Introspector> allObjects;
58     private final LogLineBuilder llBuilder = new LogLineBuilder();
59
60     /**
61      * Instantiates a new audit OXM.
62      *
63      * @param version the version
64      */
65     public AuditOXM(Version version) {
66         Loader loader = LoaderFactory.createLoaderForVersion(ModelType.MOXY, version, llBuilder);
67         Set<String> objectNames = getAllObjects(version);
68         allObjects = new HashSet<>();
69         for (String key : objectNames) {
70             Introspector temp = loader.introspectorFromName(key);
71             allObjects.add(temp);
72             this.createDBProperties(temp);
73         }
74         for (Introspector temp : allObjects) {
75             this.createDBIndexes(temp);
76         }
77         createEdgeLabels();
78     }
79
80     /**
81      * Gets the all objects.
82      *
83      * @param version the version
84      * @return the all objects
85      */
86     private Set<String> getAllObjects(Version version) {
87         String fileName = AAIConstants.AAI_HOME_ETC_OXM + "aai_oxm_" + version.toString() + ".xml";
88         Set<String> result = new HashSet<>();
89         DocumentBuilderFactory docFactory = DocumentBuilderFactory.newInstance();
90         try {
91             docFactory.setFeature(XMLConstants.FEATURE_SECURE_PROCESSING, true);
92             DocumentBuilder docBuilder = docFactory.newDocumentBuilder();
93             Document doc = docBuilder.parse(fileName);
94             NodeList list = doc.getElementsByTagName("java-type");
95             for (int i = 0; i < list.getLength(); i++) {
96                 result.add(list.item(i).getAttributes().getNamedItem("name").getNodeValue());
97             }
98         } catch (ParserConfigurationException | SAXException | IOException e) {
99             // TODO Auto-generated catch block
100             log.error(e.getLocalizedMessage(), e);
101         }
102
103         result.remove("EdgePropNames");
104         return result;
105     }
106
107     /**
108      * Creates the DB properties.
109      *
110      * @param temp the temp
111      */
112     private void createDBProperties(Introspector temp) {
113         List<String> objectProperties = temp.getProperties();
114
115         for (String prop : objectProperties) {
116             if (!properties.containsKey(prop)) {
117                 DBProperty dbProperty = new DBProperty();
118                 dbProperty.setName(prop);
119                 if (temp.isListType(prop)) {
120                     handleListTypePropertyForIntrospector(dbProperty, prop, temp);
121                 } else {
122                     handleNonListTypePropertyForIntrospector(dbProperty, prop, temp);
123                 }
124             }
125         }
126     }
127
128     private void handleListTypePropertyForIntrospector(DBProperty dbProperty, String prop, Introspector temp) {
129         dbProperty.setCardinality(Cardinality.SET);
130         if (temp.isSimpleGenericType(prop)) {
131             Class<?> clazz;
132             try {
133                 clazz = Class.forName(temp.getGenericType(prop));
134             } catch (ClassNotFoundException e) {
135                 clazz = Object.class;
136             }
137             dbProperty.setTypeClass(clazz);
138             properties.put(prop, dbProperty);
139         }
140     }
141
142     private void handleNonListTypePropertyForIntrospector(DBProperty dbProperty, String prop, Introspector temp) {
143         dbProperty.setCardinality(Cardinality.SINGLE);
144         if (temp.isSimpleType(prop)) {
145             Class<?> clazz;
146             try {
147                 clazz = Class.forName(temp.getType(prop));
148             } catch (ClassNotFoundException e) {
149                 clazz = Object.class;
150             }
151             dbProperty.setTypeClass(clazz);
152             properties.put(prop, dbProperty);
153         }
154     }
155
156     /**
157      * Creates the DB indexes.
158      *
159      * @param temp the temp
160      */
161     private void createDBIndexes(Introspector temp) {
162         String uniqueProps = temp.getMetadata("uniqueProps");
163         String namespace = temp.getMetadata("namespace");
164         if (uniqueProps == null) {
165             uniqueProps = "";
166         }
167         if (namespace == null) {
168             namespace = "";
169         }
170         boolean isTopLevel = !Objects.equals(namespace, "");
171         List<String> unique = Arrays.asList(uniqueProps.split(","));
172         List<String> indexed = temp.getIndexedProperties();
173         List<String> keys = temp.getKeys();
174
175         setDbIndexAttributes(indexed, unique);
176
177         if (keys.size() > 1 || isTopLevel) {
178             setDbIndexAttributes(isTopLevel, temp, unique, keys);
179         }
180     }
181
182     private void setDbIndexAttributes(List<String> indexed, List<String> unique) {
183         for (String prop : indexed) {
184             DBIndex dbIndex = new DBIndex();
185             LinkedHashSet<DBProperty> properties = new LinkedHashSet<>();
186             if (!this.indexes.containsKey(prop)) {
187                 dbIndex.setName(prop);
188                 dbIndex.setUnique(unique.contains(prop));
189                 properties.add(this.properties.get(prop));
190                 dbIndex.setProperties(properties);
191                 dbIndex.setStatus(SchemaStatus.ENABLED);
192                 this.indexes.put(prop, dbIndex);
193             }
194         }
195     }
196
197     private void setDbIndexAttributes(boolean isTopLevel, Introspector temp, List<String> unique, List<String> keys) {
198         DBIndex dbIndex = new DBIndex();
199         LinkedHashSet<DBProperty> properties = new LinkedHashSet<>();
200         dbIndex.setName("key-for-" + temp.getDbName());
201         if (!this.indexes.containsKey(dbIndex.getName())) {
202             boolean isUnique = false;
203             if (isTopLevel) {
204                 properties.add(this.properties.get(AAIProperties.NODE_TYPE));
205             }
206             for (String key : keys) {
207                 properties.add(this.properties.get(key));
208
209                 if (unique.contains(key) && !isUnique) {
210                     isUnique = true;
211                 }
212             }
213             dbIndex.setUnique(isUnique);
214             dbIndex.setProperties(properties);
215             dbIndex.setStatus(SchemaStatus.ENABLED);
216             this.indexes.put(dbIndex.getName(), dbIndex);
217         }
218     }
219
220     /**
221      * Creates the edge labels.
222      */
223
224     private void createEdgeLabels() {
225         Multimap<String, String> edgeRules = DbEdgeRules.EdgeRules;
226         for (String key : edgeRules.keySet()) {
227             Collection<String> collection = edgeRules.get(key);
228             EdgeProperty prop = new EdgeProperty();
229             //there is only ever one, they used the wrong type for EdgeRules
230             String label = "";
231             for (String item : collection) {
232                 label = item.split(",")[0];
233             }
234             prop.setName(label);
235             prop.setMultiplicity(Multiplicity.MULTI);
236             this.edgeLabels.put(label, prop);
237         }
238     }
239
240     /**
241      * Gets the all introspectors.
242      *
243      * @return the all introspectors
244      */
245     public Set<Introspector> getAllIntrospectors() {
246         return this.allObjects;
247     }
248 }