Merge "[AAI] Fix doc config files"
[aai/aai-common.git] / aai-core / src / main / java / org / onap / aai / introspection / sideeffect / PrivateEdge.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.introspection.sideeffect;
22
23 import com.google.common.collect.Multimap;
24
25 import java.io.UnsupportedEncodingException;
26 import java.net.URI;
27 import java.net.URISyntaxException;
28 import java.util.*;
29 import java.util.Map.Entry;
30
31 import javax.ws.rs.core.MultivaluedMap;
32
33 import org.apache.tinkerpop.gremlin.structure.Edge;
34 import org.apache.tinkerpop.gremlin.structure.Vertex;
35 import org.apache.tinkerpop.gremlin.structure.VertexProperty;
36 import org.onap.aai.config.SpringContextAware;
37 import org.onap.aai.db.props.AAIProperties;
38 import org.onap.aai.edges.EdgeIngestor;
39 import org.onap.aai.edges.EdgeRule;
40 import org.onap.aai.edges.EdgeRuleQuery;
41 import org.onap.aai.edges.enums.EdgeType;
42 import org.onap.aai.edges.exceptions.AmbiguousRuleChoiceException;
43 import org.onap.aai.edges.exceptions.EdgeRuleNotFoundException;
44 import org.onap.aai.exceptions.AAIException;
45 import org.onap.aai.introspection.Introspector;
46 import org.onap.aai.introspection.Loader;
47 import org.onap.aai.introspection.LoaderFactory;
48 import org.onap.aai.introspection.ModelType;
49 import org.onap.aai.introspection.sideeffect.exceptions.AAIMultiplePropertiesException;
50 import org.onap.aai.parsers.query.QueryParser;
51 import org.onap.aai.restcore.util.URITools;
52 import org.onap.aai.schema.enums.PropertyMetadata;
53 import org.onap.aai.serialization.db.DBSerializer;
54 import org.onap.aai.serialization.db.EdgeSerializer;
55 import org.onap.aai.serialization.db.exceptions.EdgeMultiplicityException;
56 import org.onap.aai.serialization.engines.TransactionalGraphEngine;
57
58 public class PrivateEdge extends SideEffect {
59
60     public PrivateEdge(Introspector obj, Vertex self, TransactionalGraphEngine dbEngine, DBSerializer serializer) {
61         super(obj, self, dbEngine, serializer);
62     }
63
64     @Override
65     protected void processURI(Optional<String> completeUri, Entry<String, String> entry) throws URISyntaxException,
66             UnsupportedEncodingException, AAIException, EdgeRuleNotFoundException, AmbiguousRuleChoiceException {
67         if (completeUri.isPresent()) {
68             process(completeUri, entry);
69         } else {
70             // Check if the vertex self has the template keys or the db aliased keys
71             // If it does check if the self vertex has a edge to that model
72             // If it does, then remove the edge since the update happened and doesn't have required props anymore
73             // "service-design-and-creation/models/model/{model-invariant-id}/model-vers/model-ver/{model-version-id}"
74             // If the vertex does have
75             Loader loader = SpringContextAware.getBean(LoaderFactory.class).createLoaderForVersion(ModelType.MOXY,
76                     obj.getVersion());
77             Introspector introspector = loader.introspectorFromName(obj.getDbName());
78             List<Vertex> vertices = new ArrayList<>();
79             vertices.add(self);
80             Introspector curObj = serializer.dbToObject(vertices, introspector, 0, true, "false");
81             Optional<String> populatedUri = this.replaceTemplates(curObj, entry.getValue());
82             process(populatedUri, entry);
83         }
84     }
85
86     private void process(Optional<String> completeUri, Entry<String, String> entry) throws URISyntaxException,
87             UnsupportedEncodingException, AAIException, EdgeRuleNotFoundException, AmbiguousRuleChoiceException {
88         if (completeUri.isPresent()) {
89             URI uri = new URI(completeUri.get());
90             MultivaluedMap<String, String> map = URITools.getQueryMap(uri);
91             QueryParser uriQuery = dbEngine.getQueryBuilder(this.latestLoader).createQueryFromURI(uri, map);
92             List<Vertex> results = uriQuery.getQueryBuilder().toList();
93             if (results.size() == 1) {
94                 Vertex otherVertex = results.get(0);
95                 VertexProperty otherVProperty = otherVertex.property("aai-node-type");
96
97                 if (otherVProperty.isPresent()) {
98
99                     EdgeRuleQuery edgeQuery =
100                             new EdgeRuleQuery.Builder(obj.getName(), otherVProperty.value().toString())
101                                     .edgeType(EdgeType.COUSIN).setPrivate(true).build();
102                     EdgeIngestor edgeIngestor = serializer.getEdgeIngestor();
103                     EdgeSerializer edgeSerializer = serializer.getEdgeSeriailizer();
104
105                     Multimap<String, EdgeRule> edgeRulesMap = edgeIngestor.getRules(edgeQuery);
106
107                     if (edgeRulesMap.isEmpty()) {
108                         String message = String.format("Unable to find edge between %s and %s", obj.getName(),
109                                 otherVProperty.value().toString());
110                         throw new AAIException("AAI_6127", message);
111                     } else if (edgeRulesMap.size() > 1) {
112                         String message = String.format("Found multiple edges between %s and %s", obj.getName(),
113                                 otherVProperty.value().toString());
114                         throw new EdgeMultiplicityException(message);
115                     }
116
117                     EdgeRule edgeRule = edgeIngestor.getRule(edgeQuery);
118                     Iterator<Edge> edges = self.edges(edgeRule.getDirection(), edgeRule.getLabel());
119                     if (edges.hasNext()) {
120                         Edge edge = edges.next();
121                         EdgeStatus status = checkStatus(obj, self);
122                         switch (status) {
123                             case CREATED:
124                                 edgeSerializer.addPrivateEdge(this.dbEngine.asAdmin().getTraversalSource(), self,
125                                         otherVertex, edgeRule.getLabel());
126                                 break;
127                             case MODIFIED:
128                                 edge.remove();
129                                 edgeSerializer.addPrivateEdge(this.dbEngine.asAdmin().getTraversalSource(), self,
130                                         otherVertex, edgeRule.getLabel());
131                                 break;
132                             case REMOVED:
133                                 edge.remove();
134                                 break;
135                             case UNCHANGED:
136                                 break;
137                         }
138                     } else {
139                         edgeSerializer.addPrivateEdge(this.dbEngine.asAdmin().getTraversalSource(), self, otherVertex,
140                                 edgeRule.getLabel());
141                     }
142                 }
143             } else {
144                 if (results.isEmpty()) {
145                     throw new AAIException("AAI_6114", "object located at " + uri + " not found");
146                 } else {
147                     throw new AAIMultiplePropertiesException(
148                             "multiple values of " + entry.getKey() + " found when searching " + uri);
149                 }
150             }
151         }
152     }
153
154     public enum EdgeStatus {
155         CREATED, REMOVED, MODIFIED, UNCHANGED
156     }
157
158     private EdgeStatus checkStatus(Introspector obj, Vertex self) {
159
160         for (String key : templateKeys) {
161             String currentObjValue = obj.getValue(key);
162             Map<PropertyMetadata, String> map = obj.getPropertyMetadata(key);
163             String oldVertexValue;
164
165             if (map.containsKey(PropertyMetadata.DB_ALIAS)) {
166                 oldVertexValue = self.<String>property(key + AAIProperties.DB_ALIAS_SUFFIX).orElse(null);
167             } else {
168                 oldVertexValue = self.<String>property(key).orElse(null);
169             }
170
171             if (currentObjValue == null && oldVertexValue == null) {
172                 continue;
173             }
174
175             if (currentObjValue == null) {
176                 if (oldVertexValue != null) {
177                     return EdgeStatus.REMOVED;
178                 }
179             }
180
181             if (oldVertexValue == null) {
182                 if (currentObjValue != null) {
183                     return EdgeStatus.CREATED;
184                 }
185             }
186
187             if (!oldVertexValue.equals(currentObjValue)) {
188                 return EdgeStatus.MODIFIED;
189             }
190         }
191
192         return EdgeStatus.UNCHANGED;
193     }
194
195     @Override
196     protected PropertyMetadata getPropertyMetadata() {
197         return PropertyMetadata.PRIVATE_EDGE;
198     }
199
200     @Override
201     protected boolean replaceWithWildcard() {
202         return false;
203     }
204
205 }