2 * ============LICENSE_START=======================================================
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
11 * http://www.apache.org/licenses/LICENSE-2.0
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=========================================================
21 package org.onap.aai.parsers.relationship;
23 import java.io.UnsupportedEncodingException;
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;
31 import javax.ws.rs.core.UriBuilder;
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;
55 * The Class RelationshipToURI.
57 public class RelationshipToURI {
59 private static final Logger LOGGER = LoggerFactory.getLogger(RelationshipToURI.class);
61 private Introspector relationship = null;
63 private Loader loader = null;
65 private ModelType modelType = null;
67 private EdgeIngestor edgeRules = null;
69 private URI uri = null;
71 private SchemaVersions schemaVersions;
74 * Instantiates a new relationship to URI.
76 * @param loader the loader
77 * @param relationship the relationship
78 * @throws UnsupportedEncodingException the unsupported encoding exception
79 * @throws AAIException the AAI exception
81 public RelationshipToURI(Loader loader, Introspector relationship)
82 throws UnsupportedEncodingException, AAIException {
83 this.relationship = relationship;
84 this.modelType = relationship.getModelType();
86 this.initEdgeIngestor();
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");
103 * @throws UnsupportedEncodingException the unsupported encoding exception
104 * @throws AAIException the AAI exception
106 protected void parse() throws AAIException {
107 String relatedLink = (String) relationship.getValue("related-link");
108 Optional<URI> result;
110 if (loader.getVersion().compareTo(schemaVersions.getRelatedLinkVersion()) >= 0) {
111 result = processRelatedLink(relatedLink);
112 if (!result.isPresent()) {
113 result = processRelationshipData();
116 result = processRelationshipData();
117 if (!result.isPresent()) {
118 result = processRelatedLink(relatedLink);
121 if (result.isPresent()) {
122 this.uri = result.get();
124 throw new AAIIdentityMapParseException("nothing to parse");
126 } catch (AAIException e) {
128 } catch (Exception e) {
129 throw new AAIIdentityMapParseException("Could not parse relationship-list object: " + e.getMessage(), e);
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;
143 String topLevelType = null;
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}");
155 // check node name ok
156 // check prop name ok
157 objectType = split[0];
158 propertyName = split[1];
161 Introspector wrappedObj = loader.introspectorFromName(objectType);
163 if (!wrappedObj.hasProperty(propertyName)) {
164 throw new AAIIdentityMapParseException("invalid property name in map: " + propertyName);
166 if (map.containsKey(objectType)) {
167 wrappedObj = map.get(objectType);
169 map.put(objectType, wrappedObj);
171 if (wrappedObj.getValue(propertyName) == null) {
172 wrappedObj.setValue(propertyName, value);
174 throw new AmbiguousMapAAIException(
175 "cannot determine where key/value goes: " + propertyName + "/" + value);
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);
186 } catch (AAIUnknownObjectException e) {
187 throw new AAIIdentityMapParseException("invalid object name in map: " + objectType, e);
191 if (!map.isEmpty()) {
192 String startType = (String) relationship.getValue("related-to");
193 List<String> nodeTypes = new ArrayList<>();
194 nodeTypes.addAll(map.keySet());
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);
204 sortRelationships(nodeTypes, startType, 1);
205 int startTypeIndex = nodeTypes.indexOf(startType);
206 int topLevelIndex = 0;
207 if (topLevelType != null) {
208 topLevelIndex = nodeTypes.indexOf(topLevelType);
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);
215 for (String type : nodeTypesSubList) {
216 uriBuilder.append(map.get(type).getURI());
218 if (!nodeTypesSubList.isEmpty()) {
219 result = Optional.of(UriBuilder.fromPath(uriBuilder.toString()).build());
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);
234 uriParser.validate();
235 } catch (AAIException e) {
236 throw new AAIIdentityMapParseException("related link is invalid: " + relatedLink, e);
238 result = Optional.of(resultUri);
245 * Sort relationships.
247 * @param data the data
248 * @param startType the start type
250 * @return true, if successful
251 * @throws AAIException
253 private boolean sortRelationships(List<String> data, String startType, int i) throws AAIException {
255 if (i == data.size()) {
260 String displacedObject;
263 for (j = (data.size() - i) - 1; j >= 0; j--) {
264 objectType = data.get(j);
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)) {
278 // continue to process
282 } catch (AAIException | EdgeRuleNotFoundException | AmbiguousRuleChoiceException e) {
283 // ignore exceptions generated
296 public URI getUri() {