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