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 String start = "inventory";
55         private final 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("inventory")) {
101                         currentUri = uri + obj.getGenericURI();
102                 } else {
103                         currentUri = uri;
104                 }
105                 if (obj.getName().equals("relationship-data") || obj.getName().equals("related-to-property")) {
106                         return;
107                 }
108                 if (!obj.isContainer()) {
109                         endpoints.add(currentUri);
110                 }
111                 
112                 String dbName = obj.getDbName();
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("inventory") || 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.equals("")) {
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 }