AAI-1523 Batch reformat aai-core
[aai/aai-common.git] / aai-core / src / main / java / org / onap / aai / db / DbMethHelper.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.db;
22
23 import java.io.UnsupportedEncodingException;
24 import java.net.URI;
25 import java.util.ArrayList;
26 import java.util.Iterator;
27 import java.util.List;
28 import java.util.Map;
29 import java.util.Map.Entry;
30 import java.util.Optional;
31
32 import org.apache.tinkerpop.gremlin.structure.Vertex;
33 import org.apache.tinkerpop.gremlin.structure.VertexProperty;
34 import org.onap.aai.exceptions.AAIException;
35 import org.onap.aai.introspection.Introspector;
36 import org.onap.aai.introspection.Loader;
37 import org.onap.aai.introspection.exceptions.AAIUnknownObjectException;
38 import org.onap.aai.parsers.query.QueryParser;
39 import org.onap.aai.parsers.relationship.RelationshipToURI;
40 import org.onap.aai.query.builder.QueryBuilder;
41 import org.onap.aai.serialization.engines.TransactionalGraphEngine;
42
43 public class DbMethHelper {
44
45     private final Loader loader;
46     private final TransactionalGraphEngine engine;
47
48     protected DbMethHelper() {
49         this.loader = null;
50         this.engine = null;
51     }
52
53     public DbMethHelper(Loader loader, TransactionalGraphEngine engine) {
54         this.loader = loader;
55         this.engine = engine;
56     }
57
58     /**
59      * 
60      * @param type
61      * @param map - form [{type}.{propname}:{value}]
62      * @return
63      * @throws UnsupportedEncodingException
64      * @throws AAIException
65      */
66     public Optional<Vertex> searchVertexByIdentityMap(String type, Map<String, Object> map) throws AAIException {
67
68         Introspector relationship = constructRelationship(type, map);
69         RelationshipToURI parser;
70         URI uri;
71         QueryParser queryParser;
72         try {
73             parser = new RelationshipToURI(loader, relationship);
74             uri = parser.getUri();
75             queryParser = this.engine.getQueryBuilder().createQueryFromURI(uri);
76         } catch (UnsupportedEncodingException e) {
77             throw new AAIException("AAI_3000");
78         }
79
80         List<Vertex> results = queryParser.getQueryBuilder().toList();
81
82         return reduceToSingleVertex(results, map);
83     }
84
85     /**
86      * @param type
87      * @param map - form [{propname}:{value}]
88      * @return
89      * @throws AAIException
90      */
91     public Optional<Vertex> locateUniqueVertex(String type, Map<String, Object> map) throws AAIException {
92
93         return reduceToSingleVertex(locateUniqueVertices(type, map), map);
94     }
95
96     public List<Vertex> locateUniqueVertices(String type, Map<String, Object> map) throws AAIException {
97         Introspector obj = this.createIntrospectorFromMap(type, map);
98         QueryBuilder builder = this.engine.getQueryBuilder().exactMatchQuery(obj);
99
100         return builder.toList();
101     }
102
103     private Introspector constructRelationship(String type, Map<String, Object> map) throws AAIUnknownObjectException {
104         final Introspector relationship = loader.introspectorFromName("relationship");
105         relationship.setValue("related-to", type);
106         final List<Object> data = relationship.getValue("relationship-data");
107         for (Entry<String, Object> entry : map.entrySet()) {
108             final Introspector dataObj = loader.introspectorFromName("relationship-data");
109             dataObj.setValue("relationship-key", entry.getKey());
110             dataObj.setValue("relationship-value", entry.getValue());
111             data.add(dataObj.getUnderlyingObject());
112         }
113
114         return relationship;
115     }
116
117     private Introspector createIntrospectorFromMap(String targetNodeType, Map<String, Object> propHash)
118             throws AAIUnknownObjectException {
119         final Introspector result = loader.introspectorFromName(targetNodeType);
120         for (Entry<String, Object> entry : propHash.entrySet()) {
121             result.setValue(entry.getKey(), entry.getValue());
122         }
123         return result;
124     }
125
126     private Optional<Vertex> reduceToSingleVertex(List<Vertex> vertices, Map<String, Object> map) throws AAIException {
127         if (vertices.isEmpty()) {
128             return Optional.empty();
129         } else if (vertices.size() > 1) {
130             throw new AAIException("AAI_6112", "More than one Node found by getUniqueNode for params: " + map);
131         }
132
133         return Optional.of(vertices.get(0));
134     }
135
136     public List<String> getVertexProperties(Vertex v) {
137         List<String> retArr = new ArrayList<>();
138         if (v == null) {
139             retArr.add("null Node object passed to showPropertiesForNode()\n");
140         } else {
141             String nodeType;
142             Object ob = v.<Object>property("aai-node-type").orElse(null);
143             if (ob == null) {
144                 nodeType = "null";
145             } else {
146                 nodeType = ob.toString();
147             }
148
149             retArr.add(" AAINodeType/VtxID for this Node = [" + nodeType + "/" + v.id() + "]");
150             retArr.add(" Property Detail: ");
151             Iterator<VertexProperty<Object>> pI = v.properties();
152             while (pI.hasNext()) {
153                 VertexProperty<Object> tp = pI.next();
154                 Object val = tp.value();
155                 retArr.add("Prop: [" + tp.key() + "], val = [" + val + "] ");
156             }
157         }
158         return retArr;
159     }
160 }