Merge "Release 1.14.0 maven artifact"
[aai/aai-common.git] / aai-core / src / main / java / org / onap / aai / parsers / relationship / RelationshipToURI.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.relationship;
22
23 import java.io.UnsupportedEncodingException;
24 import java.net.URI;
25 import java.net.URISyntaxException;
26 import java.util.ArrayList;
27 import java.util.HashMap;
28 import java.util.List;
29 import java.util.Optional;
30
31 import javax.ws.rs.core.UriBuilder;
32
33 import org.apache.tinkerpop.gremlin.structure.Direction;
34 import org.onap.aai.config.SpringContextAware;
35 import org.onap.aai.edges.EdgeIngestor;
36 import org.onap.aai.edges.EdgeRule;
37 import org.onap.aai.edges.EdgeRuleQuery;
38 import org.onap.aai.edges.enums.AAIDirection;
39 import org.onap.aai.edges.enums.EdgeType;
40 import org.onap.aai.edges.exceptions.AmbiguousRuleChoiceException;
41 import org.onap.aai.edges.exceptions.EdgeRuleNotFoundException;
42 import org.onap.aai.exceptions.AAIException;
43 import org.onap.aai.introspection.*;
44 import org.onap.aai.introspection.exceptions.AAIUnknownObjectException;
45 import org.onap.aai.parsers.exceptions.AAIIdentityMapParseException;
46 import org.onap.aai.parsers.exceptions.AmbiguousMapAAIException;
47 import org.onap.aai.parsers.uri.URIParser;
48 import org.onap.aai.schema.enums.ObjectMetadata;
49 import org.onap.aai.setup.SchemaVersions;
50 import org.slf4j.Logger;
51 import org.slf4j.LoggerFactory;
52 import org.springframework.context.ApplicationContext;
53
54 /**
55  * The Class RelationshipToURI.
56  */
57 public class RelationshipToURI {
58
59     private static final Logger LOGGER = LoggerFactory.getLogger(RelationshipToURI.class);
60
61     private Introspector relationship = null;
62
63     private Loader loader = null;
64
65     private ModelType modelType = null;
66
67     private EdgeIngestor edgeRules = null;
68
69     private URI uri = null;
70
71     private SchemaVersions schemaVersions;
72
73     /**
74      * Instantiates a new relationship to URI.
75      *
76      * @param loader the loader
77      * @param relationship the relationship
78      * @throws UnsupportedEncodingException the unsupported encoding exception
79      * @throws AAIException the AAI exception
80      */
81     public RelationshipToURI(Loader loader, Introspector relationship)
82             throws UnsupportedEncodingException, AAIException {
83         this.relationship = relationship;
84         this.modelType = relationship.getModelType();
85         this.loader = loader;
86         this.initEdgeIngestor();
87         this.parse();
88
89     }
90
91     protected void initEdgeIngestor() {
92         // TODO proper spring wiring, but that requires a lot of refactoring so for now we have this
93         ApplicationContext ctx = SpringContextAware.getApplicationContext();
94         edgeRules = ctx.getBean(EdgeIngestor.class);
95         schemaVersions = (SchemaVersions) ctx.getBean("schemaVersions");
96     }
97
98     /**
99      * Parses the.
100      * 
101      * @throws
102      *
103      *         @throws UnsupportedEncodingException the unsupported encoding exception
104      * @throws AAIException the AAI exception
105      */
106     protected void parse() throws AAIException {
107         String relatedLink = (String) relationship.getValue("related-link");
108         Optional<URI> result;
109         try {
110             if (loader.getVersion().compareTo(schemaVersions.getRelatedLinkVersion()) >= 0) {
111                 result = processRelatedLink(relatedLink);
112                 if (!result.isPresent()) {
113                     result = processRelationshipData();
114                 }
115             } else {
116                 result = processRelationshipData();
117                 if (!result.isPresent()) {
118                     result = processRelatedLink(relatedLink);
119                 }
120             }
121             if (result.isPresent()) {
122                 this.uri = result.get();
123             } else {
124                 throw new AAIIdentityMapParseException("nothing to parse");
125             }
126         } catch (AAIException e) {
127             throw e;
128         } catch (Exception e) {
129             throw new AAIIdentityMapParseException("Could not parse relationship-list object: " + e.getMessage(), e);
130         }
131
132     }
133
134     private Optional<URI> processRelationshipData() throws AAIException, UnsupportedEncodingException {
135         Optional<URI> result = Optional.empty();
136         StringBuilder uriBuilder = new StringBuilder();
137         List<Object> data = (List<Object>) relationship.getValue("relationship-data");
138         Introspector wrapper;
139         String key;
140         String value;
141         String objectType;
142         String propertyName;
143         String topLevelType = null;
144         String[] split;
145         HashMap<String, Introspector> map = new HashMap<>();
146         for (Object datum : data) {
147             wrapper = IntrospectorFactory.newInstance(modelType, datum);
148             key = (String) wrapper.getValue("relationship-key");
149             value = (String) wrapper.getValue("relationship-value");
150             split = key.split("\\.");
151             if (split == null || split.length != 2) {
152                 throw new AAIIdentityMapParseException(
153                         "incorrect format for key must be of the form {node-type}.{property-name}");
154             }
155             // check node name ok
156             // check prop name ok
157             objectType = split[0];
158             propertyName = split[1];
159
160             try {
161                 Introspector wrappedObj = loader.introspectorFromName(objectType);
162
163                 if (!wrappedObj.hasProperty(propertyName)) {
164                     throw new AAIIdentityMapParseException("invalid property name in map: " + propertyName);
165                 }
166                 if (map.containsKey(objectType)) {
167                     wrappedObj = map.get(objectType);
168                 } else {
169                     map.put(objectType, wrappedObj);
170                 }
171                 if (wrappedObj.getValue(propertyName) == null) {
172                     wrappedObj.setValue(propertyName, value);
173                 } else {
174                     throw new AmbiguousMapAAIException(
175                             "cannot determine where key/value goes: " + propertyName + "/" + value);
176                 }
177
178                 if (wrappedObj.getMetadata(ObjectMetadata.NAMESPACE) != null) {
179                     if (topLevelType == null) {
180                         topLevelType = objectType;
181                     } else if (!topLevelType.equals(objectType)) {
182                         throw new AmbiguousMapAAIException(
183                                 "found two top level nodes of different types: " + topLevelType + " and " + objectType);
184                     }
185                 }
186             } catch (AAIUnknownObjectException e) {
187                 throw new AAIIdentityMapParseException("invalid object name in map: " + objectType, e);
188             }
189
190         }
191         if (!map.isEmpty()) {
192             String startType = (String) relationship.getValue("related-to");
193             List<String> nodeTypes = new ArrayList<>();
194             nodeTypes.addAll(map.keySet());
195
196             String displacedType;
197             for (int i = 0; i < nodeTypes.size(); i++) {
198                 if (nodeTypes.get(i).equals(startType)) {
199                     displacedType = nodeTypes.set(nodeTypes.size() - 1, startType);
200                     nodeTypes.set(i, displacedType);
201                     break;
202                 }
203             }
204             sortRelationships(nodeTypes, startType, 1);
205             int startTypeIndex = nodeTypes.indexOf(startType);
206             int topLevelIndex = 0;
207             if (topLevelType != null) {
208                 topLevelIndex = nodeTypes.indexOf(topLevelType);
209             }
210             // remove additional types not needed if they are there
211             List<String> nodeTypesSubList = nodeTypes;
212             if (topLevelIndex != 0) {
213                 nodeTypesSubList = nodeTypes.subList(topLevelIndex, startTypeIndex + 1);
214             }
215             for (String type : nodeTypesSubList) {
216                 uriBuilder.append(map.get(type).getURI());
217             }
218             if (!nodeTypesSubList.isEmpty()) {
219                 result = Optional.of(UriBuilder.fromPath(uriBuilder.toString()).build());
220             }
221         }
222         return result;
223     }
224
225     private Optional<URI> processRelatedLink(String relatedLink)
226             throws URISyntaxException, UnsupportedEncodingException, AAIIdentityMapParseException {
227         Optional<URI> result = Optional.empty();
228         if (relatedLink != null) {
229             URI resultUri = new URI(relatedLink);
230             String path = resultUri.toString();
231             resultUri = UriBuilder.fromPath(resultUri.getRawPath()).build();
232             URIParser uriParser = new URIParser(this.loader, resultUri);
233             try {
234                 uriParser.validate();
235             } catch (AAIException e) {
236                 throw new AAIIdentityMapParseException("related link is invalid: " + relatedLink, e);
237             }
238             result = Optional.of(resultUri);
239         }
240
241         return result;
242     }
243
244     /**
245      * Sort relationships.
246      *
247      * @param data the data
248      * @param startType the start type
249      * @param i the i
250      * @return true, if successful
251      * @throws AAIException
252      */
253     private boolean sortRelationships(List<String> data, String startType, int i) throws AAIException {
254
255         if (i == data.size()) {
256             return true;
257         }
258         int j;
259         String objectType;
260         String displacedObject;
261         EdgeRule rule;
262         Direction direction;
263         for (j = (data.size() - i) - 1; j >= 0; j--) {
264             objectType = data.get(j);
265             try {
266                 rule = edgeRules
267                         .getRule(new EdgeRuleQuery.Builder(startType, objectType).edgeType(EdgeType.TREE).build());
268                 direction = rule.getDirection();
269                 if (direction != null) {
270                     if ((rule.getContains().equals(AAIDirection.OUT.toString()) && direction.equals(Direction.IN))
271                             || (rule.getContains().equals(AAIDirection.IN.toString())
272                                     && direction.equals(Direction.OUT))) {
273                         displacedObject = data.set((data.size() - i) - 1, data.get(j));
274                         data.set(j, displacedObject);
275                         if (sortRelationships(data, objectType, i + 1)) {
276                             return true;
277                         } else {
278                             // continue to process
279                         }
280                     }
281                 }
282             } catch (AAIException | EdgeRuleNotFoundException | AmbiguousRuleChoiceException e) {
283                 // ignore exceptions generated
284                 continue;
285             }
286         }
287
288         return false;
289     }
290
291     /**
292      * Gets the uri.
293      *
294      * @return the uri
295      */
296     public URI getUri() {
297         return uri;
298     }
299
300 }