Replaced all tabs with spaces in java and pom.xml
[so.git] / mso-api-handlers / mso-api-handler-infra / src / main / java / org / onap / so / apihandlerinfra / TasksHandler.java
1 /*-
2  * ============LICENSE_START=======================================================
3  * ONAP - SO
4  * ================================================================================
5  * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved.
6  * ================================================================================
7  * Modifications Copyright (c) 2019 Samsung
8  * ================================================================================
9  * Licensed under the Apache License, Version 2.0 (the "License");
10  * you may not use this file except in compliance with the License.
11  * You may obtain a copy of the License at
12  * 
13  *      http://www.apache.org/licenses/LICENSE-2.0
14  * 
15  * Unless required by applicable law or agreed to in writing, software
16  * distributed under the License is distributed on an "AS IS" BASIS,
17  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
18  * See the License for the specific language governing permissions and
19  * limitations under the License.
20  * ============LICENSE_END=========================================================
21  */
22
23 package org.onap.so.apihandlerinfra;
24
25 import java.io.IOException;
26 import java.util.ArrayList;
27 import java.util.Arrays;
28 import java.util.List;
29 import javax.transaction.Transactional;
30 import javax.ws.rs.GET;
31 import javax.ws.rs.Path;
32 import javax.ws.rs.PathParam;
33 import javax.ws.rs.QueryParam;
34 import javax.ws.rs.core.Response;
35 import javax.ws.rs.core.UriBuilder;
36 import org.apache.http.HttpResponse;
37 import org.apache.http.HttpStatus;
38 import org.json.JSONArray;
39 import org.json.JSONException;
40 import org.json.JSONObject;
41 import org.onap.so.apihandler.common.ErrorNumbers;
42 import org.onap.so.apihandler.common.RequestClient;
43 import org.onap.so.apihandler.common.RequestClientFactory;
44 import org.onap.so.apihandler.common.ResponseBuilder;
45 import org.onap.so.apihandler.common.ResponseHandler;
46 import org.onap.so.apihandlerinfra.exceptions.ApiException;
47 import org.onap.so.apihandlerinfra.exceptions.BPMNFailureException;
48 import org.onap.so.apihandlerinfra.exceptions.ValidateException;
49 import org.onap.so.apihandlerinfra.logging.ErrorLoggerInfo;
50 import org.onap.so.apihandlerinfra.tasksbeans.TaskList;
51 import org.onap.so.apihandlerinfra.tasksbeans.TaskVariableValue;
52 import org.onap.so.apihandlerinfra.tasksbeans.TaskVariables;
53 import org.onap.so.apihandlerinfra.tasksbeans.TasksGetResponse;
54 import org.onap.so.logger.ErrorCode;
55 import org.onap.so.logger.MessageEnum;
56 import org.slf4j.Logger;
57 import org.slf4j.LoggerFactory;
58 import org.springframework.beans.factory.annotation.Autowired;
59 import org.springframework.beans.factory.annotation.Value;
60 import org.springframework.stereotype.Component;
61 import com.fasterxml.jackson.core.JsonProcessingException;
62 import com.fasterxml.jackson.databind.ObjectMapper;
63 import io.swagger.annotations.Api;
64 import io.swagger.annotations.ApiOperation;
65
66 @Path("onap/so/infra/tasks")
67 @Api(value = "onap/so/infra/tasks", description = "Queries of Manual Tasks")
68 @Component
69 public class TasksHandler {
70
71
72     private static Logger logger = LoggerFactory.getLogger(TasksHandler.class);
73
74     @Value("${mso.camunda.rest.task.uri}")
75     private String requestUrl;
76
77     @Autowired
78     private RequestClientFactory reqClientFactory;
79
80     @Autowired
81     private ResponseBuilder builder;
82
83     @Path("/{version:[vV]1}")
84     @GET
85     @ApiOperation(value = "Finds Manual Tasks", response = Response.class)
86     @Transactional
87     public Response queryFilters(@QueryParam("taskId") String taskId,
88             @QueryParam("originalRequestId") String originalRequestId,
89             @QueryParam("subscriptionServiceType") String subscriptionServiceType, @QueryParam("nfRole") String nfRole,
90             @QueryParam("buildingBlockName") String buildingBlockName,
91             @QueryParam("originalRequestDate") String originalRequestDate,
92             @QueryParam("originalRequestorId") String originalRequestorId, @PathParam("version") String version)
93             throws ApiException {
94         Response responseBack = null;
95         String apiVersion = version.substring(1);
96
97         // Prepare the query string to /task interface
98         TaskVariables tv = new TaskVariables();
99
100         List<TaskVariableValue> tvvList = new ArrayList<>();
101
102         if (originalRequestId != null) {
103             TaskVariableValue tvv = new TaskVariableValue();
104             tvv.setName("originalRequestId");
105             tvv.setValue(originalRequestId);
106             tvv.setOperator("eq");
107             tvvList.add(tvv);
108         }
109         if (subscriptionServiceType != null) {
110             TaskVariableValue tvv = new TaskVariableValue();
111             tvv.setName("subscriptionServiceType");
112             tvv.setValue(subscriptionServiceType);
113             tvv.setOperator("eq");
114             tvvList.add(tvv);
115         }
116         if (nfRole != null) {
117             TaskVariableValue tvv = new TaskVariableValue();
118             tvv.setName("nfRole");
119             tvv.setValue(nfRole);
120             tvv.setOperator("eq");
121             tvvList.add(tvv);
122         }
123         if (buildingBlockName != null) {
124             TaskVariableValue tvv = new TaskVariableValue();
125             tvv.setName("buildingBlockName");
126             tvv.setValue(buildingBlockName);
127             tvv.setOperator("eq");
128             tvvList.add(tvv);
129         }
130         if (originalRequestDate != null) {
131             TaskVariableValue tvv = new TaskVariableValue();
132             tvv.setName("originalRequestDate");
133             tvv.setValue(originalRequestDate);
134             tvv.setOperator("eq");
135             tvvList.add(tvv);
136         }
137         if (originalRequestorId != null) {
138             TaskVariableValue tvv = new TaskVariableValue();
139             tvv.setName("originalRequestorId");
140             tvv.setValue(originalRequestorId);
141             tvv.setOperator("eq");
142             tvvList.add(tvv);
143         }
144
145         tv.setTaskVariables(tvvList);
146
147         RequestClient requestClient = null;
148
149         HttpResponse response = null;
150
151         try {
152             requestClient = reqClientFactory.getRequestClient(requestUrl);
153             // Capture audit event
154             ObjectMapper mapper = new ObjectMapper();
155             String camundaJsonReq = mapper.writeValueAsString(tv);
156             response = requestClient.post(camundaJsonReq);
157
158         } catch (JsonProcessingException e) {
159             ErrorLoggerInfo errorLoggerInfo =
160                     new ErrorLoggerInfo.Builder(MessageEnum.APIH_REQUEST_VALIDATION_ERROR, ErrorCode.SchemaError)
161                             .build();
162
163
164             ValidateException validateException =
165                     new ValidateException.Builder("Mapping of request to JSON object failed : " + e.getMessage(),
166                             HttpStatus.SC_BAD_REQUEST, ErrorNumbers.SVC_BAD_PARAMETER).cause(e)
167                                     .errorInfo(errorLoggerInfo).build();
168
169             throw validateException;
170         } catch (IOException e) {
171             ErrorLoggerInfo errorLoggerInfo =
172                     new ErrorLoggerInfo.Builder(MessageEnum.APIH_BPEL_COMMUNICATE_ERROR, ErrorCode.AvailabilityError)
173                             .build();
174             BPMNFailureException bpmnFailureException =
175                     new BPMNFailureException.Builder(String.valueOf(HttpStatus.SC_BAD_GATEWAY),
176                             HttpStatus.SC_BAD_GATEWAY, ErrorNumbers.SVC_NO_SERVER_RESOURCES).build();
177             throw bpmnFailureException;
178         }
179         TasksGetResponse trr = new TasksGetResponse();
180         List<TaskList> taskList = new ArrayList<>();
181
182         ResponseHandler respHandler = new ResponseHandler(response, requestClient.getType());
183         int bpelStatus = respHandler.getStatus();
184         if (bpelStatus == HttpStatus.SC_NO_CONTENT || bpelStatus == HttpStatus.SC_ACCEPTED) {
185             String respBody = respHandler.getResponseBody();
186             if (respBody != null) {
187                 JSONArray data = new JSONArray(respBody);
188
189                 for (int i = 0; i < data.length(); i++) {
190                     JSONObject taskEntry = data.getJSONObject(i);
191                     String id = taskEntry.getString("id");
192                     if (taskId != null && !taskId.equals(id)) {
193                         continue;
194                     }
195                     // Get variables info for each task ID
196                     TaskList taskListEntry = null;
197                     taskListEntry = getTaskInfo(id);
198
199                     taskList.add(taskListEntry);
200
201                 }
202                 trr.setTaskList(taskList);
203             }
204
205         } else {
206
207             ErrorLoggerInfo errorLoggerInfo =
208                     new ErrorLoggerInfo.Builder(MessageEnum.APIH_BPEL_RESPONSE_ERROR, ErrorCode.BusinessProcesssError)
209                             .build();
210
211
212             BPMNFailureException bpmnFailureException = new BPMNFailureException.Builder(String.valueOf(bpelStatus),
213                     bpelStatus, ErrorNumbers.SVC_DETAILED_SERVICE_ERROR).errorInfo(errorLoggerInfo).build();
214
215             throw bpmnFailureException;
216         }
217
218         String jsonResponse = null;
219         try {
220             ObjectMapper mapper = new ObjectMapper();
221             jsonResponse = mapper.writeValueAsString(trr);
222         } catch (JsonProcessingException e) {
223             ErrorLoggerInfo errorLoggerInfo =
224                     new ErrorLoggerInfo.Builder(MessageEnum.APIH_REQUEST_VALIDATION_ERROR, ErrorCode.SchemaError)
225                             .build();
226
227
228             ValidateException validateException =
229                     new ValidateException.Builder("Mapping of request to JSON object failed : " + e.getMessage(),
230                             HttpStatus.SC_BAD_REQUEST, ErrorNumbers.SVC_BAD_PARAMETER).cause(e)
231                                     .errorInfo(errorLoggerInfo).build();
232
233             throw validateException;
234         }
235
236         return builder.buildResponse(HttpStatus.SC_ACCEPTED, "", jsonResponse, apiVersion);
237     }
238
239     // Makes a GET call to Camunda to get variables for this task
240     private TaskList getTaskInfo(String taskId) throws ApiException {
241         TaskList taskList;
242         String getRequestUrl = UriBuilder.fromUri(requestUrl).path(taskId).path("variables").build().toString();
243         HttpResponse getResponse;
244
245         RequestClient requestClient = reqClientFactory.getRequestClient(getRequestUrl);
246         // Capture audit event
247         try {
248             getResponse = requestClient.get();
249         } catch (IOException e) {
250             ErrorLoggerInfo errorLoggerInfo =
251                     new ErrorLoggerInfo.Builder(MessageEnum.APIH_BPEL_COMMUNICATE_ERROR, ErrorCode.AvailabilityError)
252                             .build();
253             BPMNFailureException validateException =
254                     new BPMNFailureException.Builder(String.valueOf(HttpStatus.SC_BAD_GATEWAY),
255                             HttpStatus.SC_BAD_GATEWAY, ErrorNumbers.SVC_NO_SERVER_RESOURCES).build();
256             throw validateException;
257         }
258         ResponseHandler respHandler = new ResponseHandler(getResponse, requestClient.getType());
259         int bpelStatus = respHandler.getStatus();
260         if (bpelStatus == HttpStatus.SC_ACCEPTED) {
261             String respBody = respHandler.getResponseBody();
262             if (respBody != null) {
263                 taskList = buildTaskList(taskId, respBody);
264             } else {
265                 ErrorLoggerInfo errorLoggerInfo = new ErrorLoggerInfo.Builder(MessageEnum.APIH_BPEL_COMMUNICATE_ERROR,
266                         ErrorCode.AvailabilityError).build();
267
268
269
270                 BPMNFailureException bpmnFailureException =
271                         new BPMNFailureException.Builder(String.valueOf(HttpStatus.SC_BAD_GATEWAY),
272                                 HttpStatus.SC_BAD_GATEWAY, ErrorNumbers.SVC_NO_SERVER_RESOURCES).build();
273
274                 throw bpmnFailureException;
275             }
276
277         } else {
278             ErrorLoggerInfo errorLoggerInfo =
279                     new ErrorLoggerInfo.Builder(MessageEnum.APIH_BPEL_COMMUNICATE_ERROR, ErrorCode.AvailabilityError)
280                             .build();
281
282
283
284             BPMNFailureException bpmnFailureException = new BPMNFailureException.Builder(String.valueOf(bpelStatus),
285                     bpelStatus, ErrorNumbers.SVC_NO_SERVER_RESOURCES).build();
286
287
288             throw bpmnFailureException;
289         }
290
291         return taskList;
292
293     }
294
295     private TaskList buildTaskList(String taskId, String respBody) throws JSONException {
296         TaskList taskList = new TaskList();
297         JSONObject variables = new JSONObject(respBody);
298
299         taskList.setTaskId(taskId);
300         taskList.setType(getOptVariableValue(variables, "type"));
301         taskList.setNfRole(getOptVariableValue(variables, "nfRole"));
302         taskList.setSubscriptionServiceType(getOptVariableValue(variables, "subscriptionServiceType"));
303         taskList.setOriginalRequestId(getOptVariableValue(variables, "originalRequestId"));
304         taskList.setOriginalRequestorId(getOptVariableValue(variables, "originalRequestorId"));
305         taskList.setErrorSource(getOptVariableValue(variables, "errorSource"));
306         taskList.setErrorCode(getOptVariableValue(variables, "errorCode"));
307         taskList.setErrorMessage(getOptVariableValue(variables, "errorMessage"));
308         taskList.setBuildingBlockName(getOptVariableValue(variables, "buildingBlockName"));
309         taskList.setBuildingBlockStep(getOptVariableValue(variables, "buildingBlockStep"));
310         taskList.setDescription(getOptVariableValue(variables, "description"));
311         taskList.setTimeout(getOptVariableValue(variables, "timeout"));
312
313         String validResponses = getOptVariableValue(variables, "validResponses").toLowerCase();
314         List<String> items = Arrays.asList(validResponses.split("\\s*,\\s*"));
315         taskList.setValidResponses(items);
316
317         return taskList;
318     }
319
320     private String getOptVariableValue(JSONObject variables, String name) throws JSONException {
321         String variableEntry = variables.optString(name);
322         String value = "";
323         if (!variableEntry.isEmpty()) {
324             JSONObject variableEntryJson = new JSONObject(variableEntry);
325             value = variableEntryJson.optString("value");
326         }
327         return value;
328     }
329
330
331 }