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