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