1710 Rebase - Second Attempt
[so.git] / mso-api-handlers / mso-api-handler-infra / src / main / java / org / openecomp / mso / apihandlerinfra / TasksHandler.java
1 /*-
2  * #%L
3  * MSO
4  * %%
5  * Copyright (C) 2016 OPENECOMP - MSO
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  * #L%
19  */
20
21 package org.openecomp.mso.apihandlerinfra;
22
23 import org.openecomp.mso.apihandlerinfra.tasksbeans.*;
24
25 import java.util.ArrayList;
26 import java.util.List;
27
28 import javax.ws.rs.GET;
29 import javax.ws.rs.Path;
30 import javax.ws.rs.PathParam;
31 import javax.ws.rs.QueryParam;
32 import javax.ws.rs.core.Response;
33
34 import org.apache.http.HttpResponse;
35 import org.apache.http.HttpStatus;
36 import org.json.JSONArray;
37 import org.json.JSONObject;
38 import org.codehaus.jackson.map.ObjectMapper;
39
40 import org.openecomp.mso.apihandler.common.ErrorNumbers;
41 import org.openecomp.mso.apihandler.common.RequestClient;
42 import org.openecomp.mso.apihandler.common.RequestClientFactory;
43 import org.openecomp.mso.apihandler.common.ResponseHandler;
44 import org.openecomp.mso.logger.MessageEnum;
45 import org.openecomp.mso.logger.MsoAlarmLogger;
46 import org.openecomp.mso.logger.MsoLogger;
47 import org.openecomp.mso.utils.UUIDChecker;
48
49 import com.wordnik.swagger.annotations.Api;
50 import com.wordnik.swagger.annotations.ApiOperation;
51
52 @Path("/tasks")
53 @Api(value="/tasks/{version: [vV]1}",description="Queries of Manual Tasks")
54 public class TasksHandler {
55
56     private static MsoAlarmLogger alarmLogger = new MsoAlarmLogger ();
57     private static MsoLogger msoLogger = MsoLogger.getMsoLogger (MsoLogger.Catalog.APIH);
58     public final static String MSO_PROP_APIHANDLER_INFRA = "MSO_PROP_APIHANDLER_INFRA";
59     public final static String requestUrl = "mso/task/";        
60
61     @Path("/{version:[vV]1}")
62     @GET
63     @ApiOperation(value="Finds Manual Tasks",response=Response.class)
64     public Response queryFilters (@QueryParam("taskId") String taskId,
65                                   @QueryParam("originalRequestId") String originalRequestId,
66                                   @QueryParam("subscriptionServiceType") String subscriptionServiceType,
67                                   @QueryParam("nfRole") String nfRole,
68                                   @QueryParam("buildingBlockName") String buildingBlockName,
69                                   @QueryParam("originalRequestDate") String originalRequestDate,
70                                   @QueryParam("originalRequestorId") String originalRequestorId,
71                                   @PathParam("version") String version) {
72         Response responseBack = null;
73         long startTime = System.currentTimeMillis ();
74         String requestId = UUIDChecker.generateUUID(msoLogger);
75         MsoLogger.setServiceName ("ManualTasksQuery");
76         // Generate a Request Id
77         UUIDChecker.generateUUID(msoLogger);
78         msoLogger.debug ("Incoming request received for queryFilter with taskId:" + taskId
79                                                                 + " originalRequestId:" + originalRequestId
80                                                                 + " subscriptionServiceType:" + subscriptionServiceType
81                                                                 + " nfRole:" + nfRole
82                                                                 + " buildingBlockName:" + buildingBlockName
83                                                                 + " originalRequestDate:" + originalRequestDate
84                                                                 + " originalRequestorId: " + originalRequestorId);
85         
86         // Prepare the query string to /task interface
87         TaskVariables tv = new TaskVariables();
88         
89         List<TaskVariableValue> tvvList = new ArrayList<TaskVariableValue>();
90         
91         if (originalRequestId != null) {
92                 TaskVariableValue tvv = new TaskVariableValue();
93                 tvv.setName("originalRequestId");
94                 tvv.setValue(originalRequestId);
95                 tvv.setOperator("eq");
96                 tvvList.add(tvv);        
97         }
98         if (subscriptionServiceType != null) {
99                 TaskVariableValue tvv = new TaskVariableValue();
100                 tvv.setName("subscriptionServiceType");
101                 tvv.setValue(subscriptionServiceType);
102                 tvv.setOperator("eq");
103                 tvvList.add(tvv);        
104         }
105         if (nfRole != null) {
106                 TaskVariableValue tvv = new TaskVariableValue();
107                 tvv.setName("nfRole");
108                 tvv.setValue(nfRole);
109                 tvv.setOperator("eq");
110                 tvvList.add(tvv);        
111         }
112         if (buildingBlockName != null) {
113                 TaskVariableValue tvv = new TaskVariableValue();
114                 tvv.setName("buildingBlockName");
115                 tvv.setValue(buildingBlockName);
116                 tvv.setOperator("eq");
117                 tvvList.add(tvv);        
118         }
119         if (originalRequestDate != null) {
120                 TaskVariableValue tvv = new TaskVariableValue();
121                 tvv.setName("originalRequestDate");
122                 tvv.setValue(originalRequestDate);
123                 tvv.setOperator("eq");
124                 tvvList.add(tvv);        
125         }
126         if (originalRequestorId != null) {
127                 TaskVariableValue tvv = new TaskVariableValue();
128                 tvv.setName("originalRequestorId");
129                 tvv.setValue(originalRequestorId);
130                 tvv.setOperator("eq");
131                 tvvList.add(tvv);        
132         }       
133       
134         tv.setTaskVariables(tvvList);
135        
136         RequestClient requestClient = null;
137         MsoRequest msoRequest = new MsoRequest(requestId);
138                 HttpResponse response = null;
139                 long subStartTime = System.currentTimeMillis();         
140                                 
141                 try {
142                         requestClient = RequestClientFactory.getRequestClient (requestUrl, MsoPropertiesUtils.loadMsoProperties ());
143                         // Capture audit event
144                         msoLogger.debug ("MSO API Handler Post call to Camunda engine for url: " + requestClient.getUrl ());
145
146                         System.out.println("URL : " + requestClient.getUrl ());
147                         ObjectMapper mapper = new ObjectMapper();                       
148                         String camundaJsonReq = mapper.writeValueAsString(tv);
149                         msoLogger.debug("Camunda Json Request: " + camundaJsonReq);
150                         response = requestClient.post(camundaJsonReq);
151
152                         msoLogger.recordMetricEvent (subStartTime, MsoLogger.StatusCode.COMPLETE, MsoLogger.ResponseCode.Suc, "Successfully received response from BPMN engine", "BPMN", requestUrl, null);
153                 } catch (Exception e) {
154                         msoLogger.recordMetricEvent (subStartTime, MsoLogger.StatusCode.ERROR, MsoLogger.ResponseCode.CommunicationError, "Exception while communicate with BPMN engine", "BPMN", requestUrl, null);
155                         msoRequest.setStatus (org.openecomp.mso.apihandlerinfra.vnfbeans.RequestStatusType.FAILED);
156                         Response resp = msoRequest.buildServiceErrorResponse (HttpStatus.SC_BAD_GATEWAY,
157                                         MsoException.ServiceException,
158                                         "Failed calling bpmn " + e.getMessage (),
159                                         ErrorNumbers.SVC_NO_SERVER_RESOURCES,
160                                         null);
161                                 alarmLogger.sendAlarm ("MsoConfigurationError",
162                                         MsoAlarmLogger.CRITICAL,
163                                         Messages.errors.get (ErrorNumbers.NO_COMMUNICATION_TO_BPEL));
164                         msoRequest.updateFinalStatus (Status.FAILED);
165                         msoLogger.error (MessageEnum.APIH_BPEL_COMMUNICATE_ERROR, MSO_PROP_APIHANDLER_INFRA, "", "", MsoLogger.ErrorCode.AvailabilityError, "Exception while communicate with BPMN engine");
166                         msoLogger.recordAuditEvent (startTime, MsoLogger.StatusCode.ERROR, MsoLogger.ResponseCode.CommunicationError, "Exception while communicate with BPMN engine");
167                         msoLogger.debug ("End of the transaction, the final response is: " + (String) resp.getEntity ());
168                         return resp;
169                 }
170                 TasksGetResponse trr = new TasksGetResponse();
171                 List<TaskList> taskList = new ArrayList<TaskList>();
172                 
173                 ResponseHandler respHandler = new ResponseHandler (response, requestClient.getType ());
174                 int bpelStatus = respHandler.getStatus ();
175                 if (bpelStatus == HttpStatus.SC_NO_CONTENT || bpelStatus == HttpStatus.SC_ACCEPTED) {                   
176                         msoLogger.debug ("Received good response from Camunda");
177                                                 
178                         msoLogger.recordAuditEvent (startTime, MsoLogger.StatusCode.COMPLETE, MsoLogger.ResponseCode.Suc, "BPMN completed the request");
179                         String respBody = respHandler.getResponseBody();                
180                         if (respBody != null) {                         
181                                 JSONArray data = new JSONArray(respBody);
182                                 
183                                 for (int i=0; i<data.length();i++) {
184                                         JSONObject taskEntry = data.getJSONObject(i);
185                                         String id = taskEntry.getString("id");
186                                         msoLogger.debug("taskId is: " + id);
187                                         if (taskId != null && !taskId.equals(id)) {
188                                                 continue;                                               
189                                         }
190                                         // Get variables info for each task ID
191                                         TaskList taskListEntry = null;
192                                         try {
193                                                 taskListEntry = getTaskInfo(id);
194                                                 msoLogger.recordMetricEvent (subStartTime, MsoLogger.StatusCode.COMPLETE, MsoLogger.ResponseCode.Suc, "Successfully received response from BPMN engine", "BPMN", requestUrl, null);
195                                         } catch (Exception e) {
196                                                 msoLogger.recordMetricEvent (subStartTime, MsoLogger.StatusCode.ERROR, MsoLogger.ResponseCode.CommunicationError, "Exception while communicate with BPMN engine", "BPMN", requestUrl, null);
197                                                 msoRequest.setStatus (org.openecomp.mso.apihandlerinfra.vnfbeans.RequestStatusType.FAILED);
198                                                 Response resp = msoRequest.buildServiceErrorResponse (HttpStatus.SC_BAD_GATEWAY,
199                                                         MsoException.ServiceException,
200                                                         "Failed calling bpmn " + e.getMessage (),
201                                                         ErrorNumbers.SVC_NO_SERVER_RESOURCES,
202                                                         null);
203                                                 alarmLogger.sendAlarm ("MsoConfigurationError",
204                                                         MsoAlarmLogger.CRITICAL,
205                                                         Messages.errors.get (ErrorNumbers.NO_COMMUNICATION_TO_BPEL));
206                                                 
207                                                 msoLogger.error (MessageEnum.APIH_BPEL_COMMUNICATE_ERROR, MSO_PROP_APIHANDLER_INFRA, "", "", MsoLogger.ErrorCode.AvailabilityError, "Exception while communicate with BPMN engine");
208                                                 msoLogger.recordAuditEvent (startTime, MsoLogger.StatusCode.ERROR, MsoLogger.ResponseCode.CommunicationError, "Exception while communicate with BPMN engine");
209                                                 msoLogger.debug ("End of the transaction, the final response is: " + (String) resp.getEntity ());
210                                                 return resp;
211                                         }
212                                         taskList.add(taskListEntry);                            
213                                         
214                                 }
215                                 trr.setTaskList(taskList);                              
216                         }
217                 
218                 } else {                        
219                                 msoRequest.setStatus (org.openecomp.mso.apihandlerinfra.vnfbeans.RequestStatusType.FAILED);
220                                 Response resp = msoRequest.buildServiceErrorResponse(bpelStatus,
221                                                 MsoException.ServiceException,
222                                                 "Request Failed due to BPEL error with HTTP Status= %1" ,
223                                                 ErrorNumbers.SVC_DETAILED_SERVICE_ERROR,
224                                                 null);                          
225                                 msoLogger.error (MessageEnum.APIH_BPEL_RESPONSE_ERROR, requestClient.getUrl (), "", "", MsoLogger.ErrorCode.BusinessProcesssError, "Response from BPEL engine is empty");
226                                 msoLogger.recordAuditEvent (startTime, MsoLogger.StatusCode.ERROR, MsoLogger.ResponseCode.InternalError, "Response from BPEL engine is empty");
227                                 msoLogger.debug ("End of the transaction, the final response is: " + (String) resp.getEntity ());
228                                 return resp;
229                 }       
230                         
231                 
232                 String jsonResponse = null;
233                 try {
234                         ObjectMapper mapper = new ObjectMapper();                       
235                         jsonResponse = mapper.writeValueAsString(trr);
236                 }
237                 catch (Exception e) {
238                         msoLogger.debug("Unable to format response");
239                         Response resp = msoRequest.buildServiceErrorResponse(500,
240                                         MsoException.ServiceException,
241                                         "Request Failed due to bad response format" ,
242                                         ErrorNumbers.SVC_DETAILED_SERVICE_ERROR,
243                                         null);                          
244                         msoLogger.error (MessageEnum.APIH_BPEL_RESPONSE_ERROR, requestClient.getUrl (), "", "", MsoLogger.ErrorCode.BusinessProcesssError, "Bad response format");
245                         msoLogger.recordAuditEvent (startTime, MsoLogger.StatusCode.ERROR, MsoLogger.ResponseCode.InternalError, "Bad response format");
246                         msoLogger.debug ("End of the transaction, the final response is: " + (String) resp.getEntity ());
247                         return resp;
248                 }
249                 
250         
251         msoLogger.recordAuditEvent (startTime, MsoLogger.StatusCode.COMPLETE, MsoLogger.ResponseCode.Suc, "Successful");
252         responseBack = Response.status (HttpStatus.SC_ACCEPTED).entity (jsonResponse).build ();
253        // msoLogger.debug ("End of the transaction, the final response is: " + (String) response.getEntity ());
254         return responseBack;
255                 
256     }    
257
258     protected MsoLogger getMsoLogger () {
259         return msoLogger;
260     }
261     
262     // Makes a GET call to Camunda to get variables for this task
263     private TaskList getTaskInfo(String taskId) throws Exception {
264         TaskList taskList = null;
265         String getRequestUrl = requestUrl + taskId + "/variables";
266                 HttpResponse getResponse = null;
267                 long subStartTime = System.currentTimeMillis();
268                 
269                 RequestClient requestClient = RequestClientFactory.getRequestClient (getRequestUrl, MsoPropertiesUtils.loadMsoProperties ());                                           
270                 // Capture audit event                                          
271                 msoLogger.debug ("MSO API Handler Get call to Camunda engine for url: " + requestClient.getUrl ());
272                 getResponse = requestClient.get();
273                 
274                 ResponseHandler respHandler = new ResponseHandler (getResponse, requestClient.getType ());
275                 int bpelStatus = respHandler.getStatus ();
276                 if (bpelStatus == HttpStatus.SC_ACCEPTED) {                     
277                         msoLogger.debug ("Received good response from Camunda");
278                                                 
279                         msoLogger.recordAuditEvent (subStartTime, MsoLogger.StatusCode.COMPLETE, MsoLogger.ResponseCode.Suc, "BPMN completed the request");
280                         String respBody = respHandler.getResponseBody();                
281                         if (respBody != null) {
282                                 taskList = buildTaskList(taskId, respBody);                             
283                         }
284                         else {
285                                 throw new Exception("Null task info from Camunda");
286                         }
287                         
288                 }
289                 else {
290                         throw new Exception ("Bad GET response from Camunda. Status is " + bpelStatus);
291                 }               
292                 
293         return taskList;
294         
295     }
296     
297     private TaskList buildTaskList(String taskId, String respBody) {
298         TaskList taskList = new TaskList();
299         JSONObject variables = new JSONObject(respBody);
300         
301         taskList.setTaskId(taskId);
302         taskList.setType(getOptVariableValue(variables, "type"));
303         taskList.setNfRole(getOptVariableValue(variables, "nfRole"));
304         taskList.setSubscriptionServiceType(getOptVariableValue(variables, "subscriptionServiceType"));
305         taskList.setOriginalRequestId(getOptVariableValue(variables, "originalRequestId"));
306         taskList.setOriginalRequestorId(getOptVariableValue(variables, "originalRequestorId"));
307         taskList.setErrorSource(getOptVariableValue(variables, "errorSource"));
308         taskList.setErrorCode(getOptVariableValue(variables, "errorCode"));
309         taskList.setErrorMessage(getOptVariableValue(variables, "errorMessage"));
310         taskList.setBuildingBlockName(getOptVariableValue(variables, "buildingBlockName"));
311         taskList.setBuildingBlockStep(getOptVariableValue(variables, "buildingBlockStep"));  
312         taskList.setValidResponses(new JSONArray("[" + getOptVariableValue(variables, "validResponses").toLowerCase() + "]"));
313         
314         return taskList;        
315     }
316     
317     private String getOptVariableValue(JSONObject variables, String name) {
318         String variableEntry = variables.optString(name);
319         String value = "";
320         if (!variableEntry.isEmpty()) {
321                 JSONObject variableEntryJson = new JSONObject(variableEntry);
322                 value = variableEntryJson.optString("value");                   
323         }
324         return value;
325     }
326    
327    
328 }