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