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