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