fc3316d4b6f95b9f9decd379c1e49899d2c213fe
[aai/aai-common.git] / aai-core / src / main / java / org / onap / aai / serialization / queryformats / GraphSON.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.serialization.queryformats;
22
23 import com.google.gson.JsonArray;
24 import com.google.gson.JsonElement;
25 import com.google.gson.JsonObject;
26 import com.google.gson.JsonParser;
27
28 import java.io.ByteArrayOutputStream;
29 import java.io.IOException;
30 import java.io.OutputStream;
31 import java.util.Iterator;
32 import java.util.List;
33 import java.util.Map;
34 import java.util.Optional;
35
36 import org.apache.tinkerpop.gremlin.structure.Direction;
37 import org.apache.tinkerpop.gremlin.structure.Vertex;
38 import org.apache.tinkerpop.gremlin.structure.io.graphson.GraphSONMapper;
39 import org.apache.tinkerpop.gremlin.structure.io.graphson.GraphSONWriter;
40 import org.janusgraph.graphdb.tinkerpop.JanusGraphIoRegistry;
41 import org.onap.aai.serialization.queryformats.exceptions.AAIFormatQueryResultFormatNotSupported;
42 import org.onap.aai.serialization.queryformats.exceptions.AAIFormatVertexException;
43 import org.slf4j.Logger;
44 import org.slf4j.LoggerFactory;
45
46 public class GraphSON implements FormatMapper {
47
48     private static final Logger logger = LoggerFactory.getLogger(GraphSON.class);
49
50     private final GraphSONMapper mapper =
51             GraphSONMapper.build().addRegistry(JanusGraphIoRegistry.getInstance()).create();
52     private final GraphSONWriter writer = GraphSONWriter.build().mapper(mapper).create();
53     protected JsonParser parser = new JsonParser();
54
55     @Override
56     public Optional<JsonObject> formatObject(Object v) {
57         OutputStream os = new ByteArrayOutputStream();
58         String result = "";
59         try {
60             writer.writeVertex(os, (Vertex) v, Direction.BOTH);
61
62             result = os.toString();
63         } catch (IOException e) {
64             logger.debug("GraphSON writeVertex error : {}", e.getMessage());
65         }
66
67         JsonObject jsonObject = parser.parse(result).getAsJsonObject();
68
69         if (jsonObject != null) {
70
71             if (jsonObject.has("outE")) {
72                 JsonObject outEdges = jsonObject.get("outE").getAsJsonObject();
73                 removePrivateEdges(jsonObject, outEdges, "outE");
74             }
75
76             if (jsonObject.has("inE")) {
77                 JsonObject inEdges = jsonObject.get("inE").getAsJsonObject();
78                 removePrivateEdges(jsonObject, inEdges, "inE");
79             }
80
81         }
82
83         return Optional.of(jsonObject);
84
85     }
86
87     @Override
88     public Optional<JsonObject> formatObject(Object obj, Map<String, List<String>> properties)
89             throws AAIFormatVertexException, AAIFormatQueryResultFormatNotSupported {
90         return Optional.empty();
91     }
92
93     /**
94      * Removes the private edges from the json object
95      *
96      * Please note that the reason to choose to remove the private
97      * edges from the json object instead of removing it from the vertex
98      * itself is the fact that even though the transaction will be rolled back
99      * is because of the possible incosistent behavior where the actual edge
100      * might actually be removed in a long running transaction and is not worth the risk
101      *
102      * @param jsonObject - JSON Object from which we are removing the private edges for
103      * @param edges - JSONObject HashMap representing all of the edges
104      * @param edgeDirection - a string indicating the direction of the edge
105      */
106     private void removePrivateEdges(JsonObject jsonObject, JsonObject edges, String edgeDirection) {
107
108         Iterator it = edges.entrySet().iterator();
109         while (it.hasNext()) {
110             Map.Entry<String, JsonElement> outEntry = (Map.Entry<String, JsonElement>) it.next();
111             JsonArray edgePropertiesArray = outEntry.getValue().getAsJsonArray();
112             for (int index = 0; index < edgePropertiesArray.size(); ++index) {
113                 JsonElement jsonElement = edgePropertiesArray.get(index);
114                 JsonObject obj = jsonElement.getAsJsonObject();
115                 if (obj.has("properties")) {
116                     JsonObject objProperties = obj.get("properties").getAsJsonObject();
117                     if (objProperties.has("private")) {
118                         boolean isPrivate = objProperties.get("private").getAsBoolean();
119                         if (isPrivate) {
120                             if (edges.size() == 1) {
121                                 if (edgePropertiesArray.size() == 1) {
122                                     jsonObject.remove(edgeDirection);
123                                 } else {
124                                     edgePropertiesArray.remove(jsonElement);
125                                 }
126                             } else {
127                                 edgePropertiesArray.remove(jsonElement);
128                             }
129                         }
130                     }
131                 }
132             }
133             if (edgePropertiesArray.size() == 0) {
134                 it.remove();
135             }
136         }
137     }
138
139     @Override
140     public int parallelThreshold() {
141         return 50;
142     }
143 }