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