Integrate aai-schema-ingest library into aai-core
[aai/aai-common.git] / aai-core / src / main / java / org / onap / aai / audit / ListEndpoints.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.audit;
21
22 import java.util.ArrayList;
23 import java.util.HashMap;
24 import java.util.HashSet;
25 import java.util.LinkedHashSet;
26 import java.util.List;
27 import java.util.Map;
28 import java.util.Set;
29 import java.util.regex.Matcher;
30 import java.util.regex.Pattern;
31
32 import org.apache.commons.lang.StringUtils;
33 import org.onap.aai.config.SpringContextAware;
34 import org.onap.aai.db.props.AAIProperties;
35 import org.onap.aai.introspection.Introspector;
36 import org.onap.aai.introspection.Loader;
37 import org.onap.aai.introspection.LoaderFactory;
38 import org.onap.aai.introspection.ModelType;
39 import org.onap.aai.setup.SchemaVersion;
40 import org.onap.aai.introspection.exceptions.AAIUnknownObjectException;
41 import org.onap.aai.logging.LogFormatTools;
42
43 import com.att.eelf.configuration.EELFLogger;
44 import com.att.eelf.configuration.EELFManager;
45 import com.google.common.base.CaseFormat;
46 import org.onap.aai.setup.SchemaVersions;
47 import org.springframework.context.annotation.AnnotationConfigApplicationContext;
48
49 /**
50  * The Class ListEndpoints.
51  */
52 public class ListEndpoints {
53
54         private static final EELFLogger LOGGER = EELFManager.getInstance().getLogger(ListEndpoints.class);
55
56         private final String start = "inventory";
57         private final String[] blacklist = { "search", "aai-internal" };
58
59         private List<String> endpoints = new ArrayList<>();
60         private Map<String, String> endpointToLogicalName = new HashMap<String, String>();
61
62         /**
63          * The main method.
64          *
65          * @param args the arguments
66          */
67         public static void main(String[] args) {
68
69                 AnnotationConfigApplicationContext context = new AnnotationConfigApplicationContext(
70                         "org.onap.aai.config",
71                         "org.onap.aai.setup"
72                 );
73
74                 String schemaUriBasePath =  context.getEnvironment().getProperty("schema.uri.base.path");
75
76                 if(schemaUriBasePath == null){
77                         System.err.println("Unable to find the property schema.uri.base.path,"
78                                 +" please check if specified in system property or in schema-ingest.properties"
79                         );
80                 }
81
82                 SchemaVersions schemaVersions = context.getBean(SchemaVersions.class);
83                 ListEndpoints endPoints = new ListEndpoints(schemaUriBasePath, schemaVersions.getDefaultVersion());
84
85                 LOGGER.info(endPoints.toString("relationship-list"));
86         }
87
88         /**
89          * Instantiates a new list endpoints.
90          *
91          * @param version the version
92          */
93         public ListEndpoints(String basePath, SchemaVersion version) {
94
95                 Loader loader = SpringContextAware.getBean(LoaderFactory.class).createLoaderForVersion(ModelType.MOXY, version);
96
97                 try {
98                         final Introspector start = loader.introspectorFromName(this.start);
99                         Set<String> startMap = new HashSet<>();
100                         beginAudit(start, basePath + "/" + version, startMap);
101                 } catch (AAIUnknownObjectException e) {
102                         throw new RuntimeException("Failed to find object " + this.start + ", cannot run ListEndpoints audit");
103                 }
104         }
105
106         /**
107          * Begin audit.
108          *
109          * @param obj the obj
110          * @param uri the uri
111          */
112         private void beginAudit(Introspector obj, String uri, Set<String> visited) {
113
114                 String currentUri = "";
115
116                 if (!obj.getDbName().equals("inventory")) {
117                         currentUri = uri + obj.getGenericURI();
118                 } else {
119                         currentUri = uri;
120                 }
121                 if (obj.getName().equals("relationship-data") || obj.getName().equals("related-to-property")) {
122                         return;
123                 }
124                 if (!obj.isContainer()) {
125                         endpoints.add(currentUri);
126                 }
127                 
128                 String dbName = obj.getDbName();
129                 
130                 populateLogicalName(obj, uri, currentUri);
131                 
132                 Set<String> properties = obj.getProperties();
133                 Set<String> props = new LinkedHashSet<>(properties);
134                 if (obj.isContainer()) {
135                         for (String key : visited) {
136                                 if (props.remove(key)) {
137                                         try {
138                                                 endpoints.add(currentUri + obj.getLoader().introspectorFromName(key).getGenericURI());
139                                         } catch (AAIUnknownObjectException e) {
140                                                 LOGGER.warn("Skipping endpoint for " + key + " (Unknown object) " + LogFormatTools.getStackTop(e));
141                                         }
142                                 }
143                         }
144                 }
145                 
146                 outer: for (String propName : props) {
147                         
148                         for (String item : blacklist) {
149                                 if (propName.equals(item)) {
150                                         continue outer;
151                                 }
152                         }
153                         if (obj.isListType(propName)) {
154                                 if (obj.isComplexGenericType(propName)) {
155                                         try {
156                                                 final Introspector nestedObj = obj.newIntrospectorInstanceOfNestedProperty(propName);
157                                                 Set<String> newVisited = new HashSet<>();
158                                                 newVisited.addAll(visited);
159                                                 newVisited.add(nestedObj.getDbName());
160                                                 beginAudit(
161                                                                 nestedObj,
162                                                                 currentUri,
163                                                                 newVisited
164                                                                 );
165                                         } catch (AAIUnknownObjectException e) {
166                                                 LOGGER.warn("Skipping nested endpoint for " + propName + " (Unknown Object) " + LogFormatTools.getStackTop(e));
167                                         }
168                                 }
169                         } else if (obj.isComplexType(propName)) {
170                                 try {
171                                         final Introspector nestedObj = obj.newIntrospectorInstanceOfProperty(propName);
172                                         Set<String> newVisited = new HashSet<>();
173                                         newVisited.addAll(visited);
174                                         newVisited.add(nestedObj.getDbName());
175                                         beginAudit(nestedObj,
176                                                         currentUri,
177                                                         visited
178                                                         );
179                                 } catch (AAIUnknownObjectException e) {
180                                         LOGGER.warn("Skipping nested enpoint for " + propName + " (Unknown Object) "+ LogFormatTools.getStackTop(e));
181                                 }
182                         }
183                 }
184
185         }
186
187         /**
188          * Populate logical name.
189          *
190          * @param obj the obj
191          * @param uri the uri
192          * @param currentUri the current uri
193          */
194         private void populateLogicalName(Introspector obj, String uri, String currentUri) {
195
196                 if (obj.getDbName().equals("inventory") || currentUri.split("/").length <= 4 || currentUri.endsWith("relationship-list")) {
197                         return;
198                 }
199                 
200                 if (uri.endsWith("/relationship-list")) {
201                         uri = uri.substring(0, uri.lastIndexOf("/"));
202                 }
203
204                 String logicalName = "";
205                 String keys = "";
206                 
207
208                 if (!obj.getAllKeys().isEmpty()) {
209                         
210                         Pattern p = Pattern.compile("/\\{[\\w\\d\\-]+\\}/\\{[\\w\\d\\-]+\\}+$");
211                         Matcher m = p.matcher(currentUri);
212                         
213                         if (m.find()) {
214                                 keys = StringUtils.join(obj.getAllKeys(), "-and-");
215                         } else {
216                                 keys = StringUtils.join(obj.getAllKeys(), "-or-");
217                         }
218                         keys = CaseFormat.LOWER_HYPHEN.to(CaseFormat.UPPER_CAMEL, keys);
219                         if (!keys.isEmpty()) {
220                                 keys = "With" + keys;
221                         }
222                 }
223
224                 logicalName = CaseFormat.LOWER_HYPHEN.to(CaseFormat.UPPER_CAMEL, obj.getDbName()) + keys;
225                 
226                 if (endpointToLogicalName.containsKey(uri) && uri.endsWith("}")) {
227                         logicalName = logicalName + "From" + endpointToLogicalName.get(uri);
228                 } else if (endpointToLogicalName.containsKey(uri.substring(0, uri.lastIndexOf("/")))) {
229                         logicalName = logicalName + "From" + endpointToLogicalName.get(uri.substring(0, uri.lastIndexOf("/")));
230                 }
231
232                 endpointToLogicalName.put(currentUri, logicalName);
233                 
234         }
235         
236         /**
237          * Gets the logical names.
238          *
239          * @return the logical names
240          */
241         public Map<String, String> getLogicalNames() {
242                 
243                 return endpointToLogicalName;
244
245         }
246
247         /**
248          * Gets the endpoints.
249          *
250          * @return the endpoints
251          */
252         public List<String> getEndpoints() {
253
254                 return this.getEndpoints("");
255
256         }
257
258         /**
259          * Gets the endpoints.
260          *
261          * @param filterOut the filter out
262          * @return the endpoints
263          */
264         public List<String> getEndpoints(String filterOut) {
265                 List<String> result = new ArrayList<>();
266                 Pattern p = null;
267                 Matcher m = null;
268                 if (!filterOut.equals("")) {
269                         p = Pattern.compile(filterOut);
270                         m = null;
271                 }
272                 for (String s : endpoints) {
273                         if (p != null) {
274                                 m = p.matcher(s);
275                                 if (m.find()) {
276                                         continue;
277                                 }
278                         }
279
280                         result.add(s);
281                 }
282
283                 return result;
284
285         }
286
287         /** 
288          * {@inheritDoc}
289          */
290         @Override
291         public String toString() {
292                 StringBuilder sb = new StringBuilder();
293                 for (String s : endpoints) {
294                         sb.append(s + "\n");
295                 }
296                 return sb.toString();
297
298         }
299
300         /**
301          * To string.
302          *
303          * @param filterOut the filter out
304          * @return the string
305          */
306         public String toString(String filterOut) {
307                 StringBuilder sb = new StringBuilder();
308                 Pattern p = Pattern.compile(filterOut);
309                 Matcher m = null;
310                 for (String s : endpoints) {
311                         m = p.matcher(s);
312                         if (!m.find()) {
313                                 sb.append(s + "\n");
314                         }
315                 }
316                 return sb.toString();
317         }
318
319 }