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