ca73535736af6f84adcc4776ff8d12011bfaeea9
[aai/aai-common.git] / aai-core / src / main / java / org / onap / aai / parsers / query / LegacyQueryParser.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
21 package org.onap.aai.parsers.query;
22
23 import org.slf4j.Logger;
24 import org.slf4j.LoggerFactory;
25
26 import java.io.UnsupportedEncodingException;
27 import java.net.URI;
28 import java.net.URISyntaxException;
29 import java.util.*;
30 import java.util.Map.Entry;
31
32 import javax.ws.rs.core.MultivaluedMap;
33
34 import org.onap.aai.edges.enums.EdgeType;
35 import org.onap.aai.exceptions.AAIException;
36 import org.onap.aai.introspection.Introspector;
37 import org.onap.aai.introspection.Loader;
38 import org.onap.aai.introspection.exceptions.AAIUnknownObjectException;
39 import org.onap.aai.logging.LogFormatTools;
40 import org.onap.aai.parsers.uri.Parsable;
41 import org.onap.aai.parsers.uri.URIParser;
42 import org.onap.aai.parsers.uri.URIToObject;
43 import org.onap.aai.query.builder.QueryBuilder;
44 import org.onap.aai.restcore.util.URITools;
45 import org.onap.aai.schema.enums.PropertyMetadata;
46
47 /**
48  * The Class LegacyQueryParser.
49  */
50 public class LegacyQueryParser extends QueryParser implements Parsable {
51
52     private static final Logger LOGGER = LoggerFactory.getLogger(LegacyQueryParser.class);
53
54     private Introspector previous = null;
55
56     /**
57      * Instantiates a new legacy query parser.
58      *
59      * @param loader the loader
60      * @param queryBuilder the query builder
61      * @param uri the uri
62      * @throws UnsupportedEncodingException the unsupported encoding exception
63      * @throws AAIException the AAI exception
64      */
65     public LegacyQueryParser(Loader loader, QueryBuilder queryBuilder, URI uri)
66             throws UnsupportedEncodingException, AAIException {
67         super(loader, queryBuilder, uri);
68         URIParser parser = new URIParser(loader, uri);
69         parser.parse(this);
70     }
71
72     /**
73      * Instantiates a new legacy query parser.
74      *
75      * @param loader the loader
76      * @param queryBuilder the query builder
77      * @param uri the uri
78      * @param queryParams the query params
79      * @throws UnsupportedEncodingException the unsupported encoding exception
80      * @throws AAIException the AAI exception
81      */
82     public LegacyQueryParser(Loader loader, QueryBuilder queryBuilder, URI uri,
83             MultivaluedMap<String, String> queryParams) throws UnsupportedEncodingException, AAIException {
84         super(loader, queryBuilder, uri);
85         URIParser parser = new URIParser(loader, uri, queryParams);
86         parser.parse(this);
87     }
88
89     /**
90      * Instantiates a new legacy query parser.
91      *
92      * @param loader the loader
93      * @param queryBuilder the query builder
94      */
95     public LegacyQueryParser(Loader loader, QueryBuilder queryBuilder) {
96         super(loader, queryBuilder);
97     }
98
99     /**
100      * @throws AAIException
101      * @{inheritDoc}
102      */
103     @Override
104     public void processObject(Introspector obj, EdgeType type, MultivaluedMap<String, String> uriKeys)
105             throws AAIException {
106         if (previous != null) {
107             this.parentResourceType = previous.getDbName();
108             queryBuilder.createEdgeTraversal(type, previous, obj);
109         }
110         if (previous == null) {
111             queryBuilder.createDBQuery(obj);
112             this.handleUriKeys(obj, uriKeys);
113         } else {
114             queryBuilder.createKeyQuery(obj);
115             this.handleUriKeys(obj, uriKeys);
116         }
117         previous = obj;
118         this.resultResource = obj.getDbName();
119     }
120
121     /**
122      * @{inheritDoc}
123      */
124     @Override
125     public void processContainer(Introspector obj, EdgeType type, MultivaluedMap<String, String> uriKeys,
126             boolean isFinalContainer) throws AAIException {
127         if (isFinalContainer) {
128             if (previous != null) {
129                 this.parentResourceType = previous.getDbName();
130                 queryBuilder.createEdgeTraversal(type, previous, obj);
131             }
132
133             if (previous == null) {
134                 queryBuilder.createContainerQuery(obj);
135                 queryBuilder.markParentBoundary();
136             }
137             if (!uriKeys.isEmpty()) {
138
139                 try {
140                     Introspector child = obj.newIntrospectorInstanceOfNestedProperty(obj.getChildName());
141                     this.handleUriKeys(child, uriKeys);
142                 } catch (AAIUnknownObjectException e) {
143                     LOGGER.warn("Skipping container child " + obj.getChildName() + " (Unknown Object) "
144                             + LogFormatTools.getStackTop(e));
145                 }
146             }
147
148             this.resultResource = obj.getChildDBName();
149             this.containerResource = obj.getName();
150         }
151     }
152
153     private void handleUriKeys(Introspector obj, MultivaluedMap<String, String> uriKeys) throws AAIException {
154         for (String key : uriKeys.keySet()) {
155             // to validate whether this property exists
156             if (!obj.hasProperty(key)) {
157                 throw new AAIException("AAI_3000", "property: " + key + " not found on " + obj.getDbName());
158             }
159
160             List<String> values = uriKeys.get(key);
161             String dbPropertyName = key;
162             Map<String, String> linkedProperties = new HashMap<>();
163             final Map<PropertyMetadata, String> metadata = obj.getPropertyMetadata(key);
164             if (metadata.containsKey(PropertyMetadata.DATA_LINK)) {
165                 linkedProperties.put(key, metadata.get(PropertyMetadata.DATA_LINK));
166             }
167             if (metadata.containsKey(PropertyMetadata.DB_ALIAS)) {
168                 dbPropertyName = metadata.get(PropertyMetadata.DB_ALIAS);
169             }
170
171             if (!linkedProperties.containsKey(key)) {
172                 if (values.size() > 1) {
173                     queryBuilder.getVerticesByIndexedProperty(dbPropertyName,
174                             obj.castValueAccordingToSchema(key, values));
175                 } else {
176                     queryBuilder.getVerticesByIndexedProperty(dbPropertyName,
177                             obj.castValueAccordingToSchema(key, values.get(0)));
178                 }
179             }
180             handleLinkedProperties(obj, uriKeys, linkedProperties);
181         }
182     }
183
184     private void handleLinkedProperties(Introspector obj, MultivaluedMap<String, String> uriKeys,
185             Map<String, String> linkedProperties) throws AAIException {
186
187         QueryBuilder[] builders = new QueryBuilder[linkedProperties.keySet().size()];
188         Set<Entry<String, String>> entrySet = linkedProperties.entrySet();
189         int i = 0;
190         Iterator<Entry<String, String>> itr = entrySet.iterator();
191
192         while (itr.hasNext()) {
193             Entry<String, String> entry = itr.next();
194             Introspector child;
195             try {
196                 child = new URIToObject(this.latestLoader, new URI(
197                         URITools.replaceTemplates(obj, entry.getValue(), PropertyMetadata.DATA_LINK, true).orElse("")))
198                                 .getEntity();
199             } catch (IllegalArgumentException | UnsupportedEncodingException | URISyntaxException e) {
200                 throw new AAIException("AAI_4000", e);
201             }
202             List<String> values = uriKeys.get(entry.getKey());
203             QueryBuilder builder = queryBuilder.newInstance();
204             builder.createEdgeTraversal(EdgeType.TREE, obj, child);
205             if (values.size() > 1) {
206                 builder.getVerticesByIndexedProperty(entry.getKey(),
207                         obj.castValueAccordingToSchema(entry.getKey(), values));
208             } else {
209                 builder.getVerticesByIndexedProperty(entry.getKey(),
210                         obj.castValueAccordingToSchema(entry.getKey(), values.get(0)));
211             }
212
213             builders[i] = builder;
214             i++;
215         }
216
217         queryBuilder.where(builders);
218
219     }
220
221     /**
222      * @{inheritDoc}
223      */
224     @Override
225     public void processNamespace(Introspector obj) {
226
227     }
228
229     /**
230      * @{inheritDoc}
231      */
232     @Override
233     public String getCloudRegionTransform() {
234         return "add";
235     }
236
237     /**
238      * @{inheritDoc}
239      */
240     @Override
241     public boolean useOriginalLoader() {
242         return false;
243     }
244 }