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