5aece21ce16e73fd702e782c87a8785af5aae04c
[aai/aai-common.git] / aai-core / src / main / java / org / onap / aai / parsers / uri / URIParser.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.parsers.uri;
21
22 import org.onap.aai.config.SpringContextAware;
23 import org.onap.aai.exceptions.AAIException;
24 import org.onap.aai.introspection.Introspector;
25 import org.onap.aai.introspection.Loader;
26 import org.onap.aai.introspection.LoaderFactory;
27 import org.onap.aai.setup.SchemaVersion;
28 import org.onap.aai.logging.ErrorLogHelper;
29 import org.onap.aai.parsers.exceptions.DoesNotStartWithValidNamespaceException;
30 import org.onap.aai.rest.RestTokens;
31 import org.onap.aai.schema.enums.ObjectMetadata;
32 import org.onap.aai.edges.enums.EdgeType;
33 import org.onap.aai.util.AAIConfig;
34 import org.springframework.web.util.UriUtils;
35
36 import javax.ws.rs.core.MultivaluedHashMap;
37 import javax.ws.rs.core.MultivaluedMap;
38 import javax.ws.rs.core.UriBuilder;
39 import java.io.UnsupportedEncodingException;
40 import java.net.URI;
41 import java.util.Set;
42
43
44 /**
45  * The Class URIParser.
46  */
47 public class URIParser {
48         
49         private URI uri = null;
50
51         protected Loader loader = null;
52         
53         protected Loader originalLoader = null;
54         
55         private URI originalURI = null;
56         
57         private MultivaluedMap<String, String> queryParams = null;
58         
59         
60         /**
61          * Instantiates a new URI parser.
62          *
63          * @param loader the loader
64          * @param uri the uri
65          */
66         public URIParser(Loader loader, URI uri) {
67                 this.uri = uri;
68
69                 this.originalLoader = loader;
70                 //Load the latest version because we need it for cloud region
71
72                         this.loader = loader;
73         }
74         
75         /**
76          * Instantiates a new URI parser.
77          *
78          * @param loader the loader
79          * @param uri the uri
80          * @param queryParams the query params
81          */
82         public URIParser(Loader loader, URI uri, MultivaluedMap<String, String> queryParams) {
83                 this(loader, uri);
84                 this.queryParams = queryParams;
85         }
86
87         public Loader getLoader() {
88                 
89                 return this.loader;
90                 
91         }
92         
93         /**
94          * Gets the original URI.
95          *
96          * @return the original URI
97          */
98         public URI getOriginalURI() {
99                 return this.originalURI;
100         }
101         
102         /**
103          * Parses the.
104          *
105          * @param p the p
106          * @throws UnsupportedEncodingException the unsupported encoding exception
107          * @throws AAIException the AAI exception
108          */
109         public void parse(Parsable p) throws UnsupportedEncodingException, AAIException {
110                 try {
111                         boolean isRelative = false;
112                         uri = this.trimURI(uri);
113                         uri = handleCloudRegion(p.getCloudRegionTransform(), uri);
114                         if (p.useOriginalLoader()) {
115                                 this.loader = this.originalLoader;
116                         }
117                         this.originalURI  = UriBuilder.fromPath(uri.getRawPath()).build();
118                         if (uri.getRawPath().startsWith("./")) {
119                                 uri = new URI(uri.getRawPath().replaceFirst("\\./", ""));
120                                 isRelative = true;
121                         }
122                         String[] parts = uri.getRawPath().split("/");
123                         Introspector validNamespaces = loader.introspectorFromName("inventory");
124                         Set<String> keys = null;
125                         String part = "";
126                         Introspector previousObj = null;
127                         EdgeType type = EdgeType.TREE;
128                         for (int i = 0; i < parts.length;) {
129                                 part = parts[i];
130                                 Introspector introspector = null;
131                                 if (part.equals(RestTokens.COUSIN.toString())) {
132                                         if (i == parts.length-1) {
133                                                 throw new AAIException("AAI_3000", uri + " not a valid path. Cannot end in " + RestTokens.COUSIN);
134                                         }
135                                         introspector = loader.introspectorFromName(parts[i+1]);
136                                         if(null == previousObj) {
137                                                 throw new AAIException("AAI_3001");
138                                         }
139                                         if (previousObj.isContainer() && introspector.isContainer()) {
140                                                 throw new AAIException("AAI_3000", uri + " not a valid path. Cannot chain plurals together");
141                                         }
142                                         MultivaluedMap<String, String> uriKeys = new MultivaluedHashMap<>();
143                                         if (i == parts.length-2 && queryParams != null) {
144                                                 Set<String> queryKeys = queryParams.keySet();
145                                                 for (String key : queryKeys) {
146                                                         uriKeys.put(key, queryParams.get(key));
147                                                         
148                                                 }
149                                         }
150                                         if (introspector.isContainer()) {
151                                                 boolean isFinalContainer = i == parts.length-2;
152                                                 /*
153                                                  * Related-to could be COUSIN OR TREE and in some cases BOTH. So Let EdgeRuleBuilder use all the edgeTypes
154                                                  */
155                                                 p.processContainer(introspector, EdgeType.ALL, uriKeys, isFinalContainer);
156                                         }
157                                         previousObj = introspector;
158                                         type = EdgeType.ALL;
159                                         i+=2;
160                                         continue;
161                                 }
162                                 introspector = loader.introspectorFromName(part);
163                                 if (introspector != null) {
164                                         
165                                         //previous has current as property
166                                         if (previousObj != null && !previousObj.hasChild(introspector) && !previousObj.getDbName().equals("nodes")) {
167                                                 throw new AAIException("AAI_3001", uri + " not a valid path. " + part + " not valid");
168                                         } else if (previousObj == null) {
169                                                 String abstractType = introspector.getMetadata(ObjectMetadata.ABSTRACT);
170                                                 if (abstractType == null) {
171                                                         abstractType = "";
172                                                 }
173                                                 //first time through, make sure it starts from a namespace
174                                                 //ignore abstract types
175                                                 if (!isRelative && !abstractType.equals("true") && !validNamespaces.hasChild(introspector)) {
176                                                         throw new DoesNotStartWithValidNamespaceException( uri + " not a valid path. It does not start from a valid namespace");
177                                                 }
178                                         }
179                                         
180                                         keys = introspector.getKeys();
181                                         if (keys.size() > 0) {
182                                                 MultivaluedMap<String, String> uriKeys = new MultivaluedHashMap<>();
183                                                 i++;
184                                                 if (i == parts.length && queryParams != null) {
185                                                         Set<String> queryKeys = queryParams.keySet();
186                                                         for (String key : queryKeys) {
187                                                                 uriKeys.put(key, queryParams.get(key));
188                                                         }
189                                                 } else {
190                                                         for (String key : keys) {
191                                                                 part =  UriUtils.decode(parts[i], "UTF-8");
192                                                                 
193                                                                 introspector.setValue(key, part);
194                                                                 
195                                                                 //skip this for further processing
196                                                                 i++;
197                                                         }
198                                                 }
199                                                 
200                                                 p.processObject(introspector, type, uriKeys);
201                                                 type = EdgeType.TREE;
202                                         } else if (introspector.isContainer()) {
203                                                 boolean isFinalContainer = i == parts.length-1;
204                                                 MultivaluedMap<String, String> uriKeys = new MultivaluedHashMap<>();
205                                                 
206                                                 if (isFinalContainer && queryParams != null) {
207                                                         Set<String> queryKeys = queryParams.keySet();
208                                                         for (String key : queryKeys) {
209                                                                 uriKeys.put(key, queryParams.get(key));
210                                                                 
211                                                         }
212                                                 }
213                                                 p.processContainer(introspector, type, uriKeys, isFinalContainer);
214                                                 i++; 
215                                         } else {
216                                                 p.processNamespace(introspector);
217                                                 //namespace case
218                                                 i++;
219                                         }
220                                         previousObj = introspector;
221                                 } else {
222                                         //invalid item found should log
223                                         //original said bad path
224                                         throw new AAIException("AAI_3001", "invalid item found in path: " + part);
225                                 }
226                         }
227                 } catch (AAIException e) {
228                         throw e;
229                 } catch (Exception e) {
230                         throw new AAIException("AAI_3001", e);
231                 }
232         }
233         
234         public boolean validate() throws UnsupportedEncodingException, AAIException {
235                 this.parse(new URIValidate());
236                 return true;
237         }
238         /**
239          * Handle cloud region.
240          *
241          * @param action the action
242          * @param uri the uri
243          * @return the uri
244          */
245         protected URI handleCloudRegion(String action, URI uri) {
246
247                         return uri;
248
249         }
250         
251         /**
252          * Trim URI.
253          *
254          * @param uri the uri
255          * @return the uri
256          */
257         protected URI trimURI(URI uri) {
258                 
259                 String result = uri.getRawPath();
260                 if (result.startsWith("/")) {
261                         result = result.substring(1, result.length());
262                 }
263                 
264                 if (result.endsWith("/")) {
265                         result = result.substring(0, result.length() - 1);
266                 }
267
268                 // TODO - Check if this makes to do for model driven for base uri path
269                 result = result.replaceFirst("[a-z][a-z]*/v\\d+/", "");
270                 
271                 return UriBuilder.fromPath(result).build();
272         }
273
274 }