Enhancements for the aai-common library
[aai/aai-common.git] / aai-core / src / main / java / org / onap / aai / serialization / queryformats / Formatter.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 org.slf4j.Logger;
24 import org.slf4j.LoggerFactory;
25 import com.google.gson.JsonArray;
26 import com.google.gson.JsonElement;
27 import com.google.gson.JsonObject;
28 import com.google.gson.JsonParser;
29 import org.json.JSONArray;
30 import org.json.simple.JSONObject;
31 import org.json.simple.parser.JSONParser;
32 import org.onap.aai.logging.LogFormatTools;
33 import org.onap.aai.serialization.queryformats.exceptions.AAIFormatQueryResultFormatNotSupported;
34 import org.onap.aai.serialization.queryformats.exceptions.AAIFormatVertexException;
35
36 import javax.ws.rs.core.MultivaluedMap;
37 import java.util.Iterator;
38 import java.util.List;
39 import java.util.Map;
40 import java.util.Optional;
41 import java.util.stream.Stream;
42
43 public class Formatter {
44
45     private static final Logger LOGGER = LoggerFactory.getLogger(Formatter.class);
46
47     protected final FormatMapper format;
48     protected MultivaluedMap<String, String> params;
49
50     public Formatter(FormatMapper format) {
51         this.format = format;
52     }
53
54     public Formatter(FormatMapper format, MultivaluedMap<String, String> params) {
55         this.format = format;
56         this.params = params;
57     }
58
59     public JsonObject output(List<Object> queryResults, Map<String, List<String>> properties) {
60
61         final JsonArray body;
62
63         if (this.format instanceof Count) {
64             JsonObject countResult;
65             body = new JsonArray();
66             try {
67                 countResult = format.formatObject(queryResults).orElseThrow(() -> new AAIFormatVertexException(""));
68                 body.add(countResult);
69             } catch (Exception e) {
70                 LOGGER.warn("Failed to format result type of the query " + LogFormatTools.getStackTop(e));
71             }
72         } else if (this.format instanceof LifecycleFormat) {
73             LifecycleFormat lifecycleFormat = (LifecycleFormat) format;
74             body = lifecycleFormat.process(queryResults);
75         } else if (this.format instanceof Aggregate) {
76             Aggregate aggregateFormat = (Aggregate) format;
77             body = aggregateFormat.process(queryResults, properties);
78             JsonObject result = new JsonObject();
79             if (body != null && body.size() > 0) {
80                 result.add("results", (body.get(0)).getAsJsonObject().get("results"));
81             }
82             return result;
83         } else {
84
85             body = new JsonArray();
86             Stream<Object> stream;
87             if (queryResults.size() >= format.parallelThreshold()) {
88                 stream = queryResults.parallelStream();
89             } else {
90                 stream = queryResults.stream();
91             }
92
93             final boolean isParallel = stream.isParallel();
94
95             stream.map(o -> {
96                 try {
97                     if (properties!= null && !properties.isEmpty()){
98                         return format.formatObject(o, properties);
99                     } else {
100                         return format.formatObject(o);
101                     }
102                 } catch (AAIFormatVertexException e) {
103                     LOGGER.warn("Failed to format vertex, returning a partial list " + LogFormatTools.getStackTop(e));
104                 } catch (AAIFormatQueryResultFormatNotSupported e) {
105                     LOGGER.warn("Failed to format result type of the query " + LogFormatTools.getStackTop(e));
106                 }
107
108                 return Optional.<JsonObject>empty();
109             }).filter(Optional::isPresent)
110                 .map(Optional::get)
111                 .forEach(json -> {
112                     if (isParallel) {
113                         synchronized (body) {
114                             body.add(json);
115                         }
116                     } else {
117                         body.add(json);
118                     }
119                 });
120
121         }
122
123         if (params !=null && params.containsKey("as-tree")) {
124             String isAsTree = params.get("as-tree").get(0);
125             if (isAsTree != null && isAsTree.equalsIgnoreCase("true")
126                 && body != null && body.size() != 0) {
127                 JsonObject jsonObjectBody = body.get(0).getAsJsonObject();
128                 if (jsonObjectBody != null && jsonObjectBody.size() > 0) {
129                     return body.get(0).getAsJsonObject();
130                 }
131             }
132         }
133         JsonObject result = new JsonObject();
134         result.add("results", body);
135         return result.getAsJsonObject();
136
137     }
138
139     public JsonObject output(List<Object> queryResults) {
140         return output(queryResults, null);
141     }
142
143 }