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