Fixes in ListEndpoints
[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 static String start = "inventory";
57         private final static 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(start)) {
103                         currentUri = uri + obj.getGenericURI();
104                 } else {
105                         currentUri = uri;
106                 }
107                 if ("relationship-data".equals(obj.getName()) || "related-to-property".equals(obj.getName())) {
108                         return;
109                 }
110                 if (!obj.isContainer()) {
111                         endpoints.add(currentUri);
112                 }
113                 
114                 populateLogicalName(obj, uri, currentUri);
115                 
116                 Set<String> properties = obj.getProperties();
117                 Set<String> props = new LinkedHashSet<>(properties);
118                 if (obj.isContainer()) {
119                         for (String key : visited) {
120                                 if (props.remove(key)) {
121                                         try {
122                                                 endpoints.add(currentUri + obj.getLoader().introspectorFromName(key).getGenericURI());
123                                         } catch (AAIUnknownObjectException e) {
124                                                 LOGGER.warn("Skipping endpoint for " + key + " (Unknown object) " + LogFormatTools.getStackTop(e));
125                                         }
126                                 }
127                         }
128                 }
129                 
130                 outer: for (String propName : props) {
131                         
132                         for (String item : blacklist) {
133                                 if (propName.equals(item)) {
134                                         continue outer;
135                                 }
136                         }
137                         if (obj.isListType(propName)) {
138                                 if (obj.isComplexGenericType(propName)) {
139                                         try {
140                                                 final Introspector nestedObj = obj.newIntrospectorInstanceOfNestedProperty(propName);
141                                                 Set<String> newVisited = new HashSet<>();
142                                                 newVisited.addAll(visited);
143                                                 newVisited.add(nestedObj.getDbName());
144                                                 beginAudit(
145                                                                 nestedObj,
146                                                                 currentUri,
147                                                                 newVisited
148                                                                 );
149                                         } catch (AAIUnknownObjectException e) {
150                                                 LOGGER.warn("Skipping nested endpoint for " + propName + " (Unknown Object) " + LogFormatTools.getStackTop(e));
151                                         }
152                                 }
153                         } else if (obj.isComplexType(propName)) {
154                                 try {
155                                         final Introspector nestedObj = obj.newIntrospectorInstanceOfProperty(propName);
156                                         Set<String> newVisited = new HashSet<>();
157                                         newVisited.addAll(visited);
158                                         newVisited.add(nestedObj.getDbName());
159                                         beginAudit(nestedObj,
160                                                         currentUri,
161                                                         visited
162                                                         );
163                                 } catch (AAIUnknownObjectException e) {
164                                         LOGGER.warn("Skipping nested enpoint for " + propName + " (Unknown Object) "+ LogFormatTools.getStackTop(e));
165                                 }
166                         }
167                 }
168
169         }
170
171         /**
172          * Populate logical name.
173          *
174          * @param obj the obj
175          * @param uri the uri
176          * @param currentUri the current uri
177          */
178         private void populateLogicalName(Introspector obj, String uri, String currentUri) {
179
180                 if (obj.getDbName().equals(start) || currentUri.split("/").length <= 4 || currentUri.endsWith("relationship-list")) {
181                         return;
182                 }
183                 
184                 if (uri.endsWith("/relationship-list")) {
185                         uri = uri.substring(0, uri.lastIndexOf("/"));
186                 }
187
188                 String logicalName = "";
189                 String keys = "";
190                 
191
192                 if (!obj.getAllKeys().isEmpty()) {
193                         
194                         Pattern p = Pattern.compile("/\\{[\\w\\d\\-]+\\}/\\{[\\w\\d\\-]+\\}+$");
195                         Matcher m = p.matcher(currentUri);
196                         
197                         if (m.find()) {
198                                 keys = StringUtils.join(obj.getAllKeys(), "-and-");
199                         } else {
200                                 keys = StringUtils.join(obj.getAllKeys(), "-or-");
201                         }
202                         keys = CaseFormat.LOWER_HYPHEN.to(CaseFormat.UPPER_CAMEL, keys);
203                         if (!keys.isEmpty()) {
204                                 keys = "With" + keys;
205                         }
206                 }
207
208                 logicalName = CaseFormat.LOWER_HYPHEN.to(CaseFormat.UPPER_CAMEL, obj.getDbName()) + keys;
209                 
210                 if (endpointToLogicalName.containsKey(uri) && uri.endsWith("}")) {
211                         logicalName = logicalName + "From" + endpointToLogicalName.get(uri);
212                 } else if (endpointToLogicalName.containsKey(uri.substring(0, uri.lastIndexOf("/")))) {
213                         logicalName = logicalName + "From" + endpointToLogicalName.get(uri.substring(0, uri.lastIndexOf("/")));
214                 }
215
216                 endpointToLogicalName.put(currentUri, logicalName);
217                 
218         }
219         
220         /**
221          * Gets the logical names.
222          *
223          * @return the logical names
224          */
225         public Map<String, String> getLogicalNames() {
226                 
227                 return endpointToLogicalName;
228
229         }
230
231         /**
232          * Gets the endpoints.
233          *
234          * @return the endpoints
235          */
236         public List<String> getEndpoints() {
237
238                 return this.getEndpoints("");
239
240         }
241
242         /**
243          * Gets the endpoints.
244          *
245          * @param filterOut the filter out
246          * @return the endpoints
247          */
248         public List<String> getEndpoints(String filterOut) {
249                 List<String> result = new ArrayList<>();
250                 Pattern p = null;
251                 Matcher m = null;
252                 if (!filterOut.isEmpty()) {
253                         p = Pattern.compile(filterOut);
254                         m = null;
255                 }
256                 for (String s : endpoints) {
257                         if (p != null) {
258                                 m = p.matcher(s);
259                                 if (m.find()) {
260                                         continue;
261                                 }
262                         }
263
264                         result.add(s);
265                 }
266
267                 return result;
268
269         }
270
271         /** 
272          * {@inheritDoc}
273          */
274         @Override
275         public String toString() {
276                 StringBuilder sb = new StringBuilder();
277                 for (String s : endpoints) {
278                         sb.append(s + "\n");
279                 }
280                 return sb.toString();
281
282         }
283
284         /**
285          * To string.
286          *
287          * @param filterOut the filter out
288          * @return the string
289          */
290         public String toString(String filterOut) {
291                 StringBuilder sb = new StringBuilder();
292                 Pattern p = Pattern.compile(filterOut);
293                 Matcher m = null;
294                 for (String s : endpoints) {
295                         m = p.matcher(s);
296                         if (!m.find()) {
297                                 sb.append(s + "\n");
298                         }
299                 }
300                 return sb.toString();
301         }
302
303 }