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