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