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