AT&T 1712 and 1802 release code
[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 ONAP - SO
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.text.ParseException;
26 import java.util.ArrayList;
27 import java.util.List;
28
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
35 import org.apache.http.HttpResponse;
36 import org.apache.http.HttpStatus;
37 import org.json.JSONArray;
38 import org.json.JSONObject;
39 import com.fasterxml.jackson.databind.ObjectMapper;
40
41 import org.openecomp.mso.apihandler.common.ErrorNumbers;
42 import org.openecomp.mso.apihandler.common.RequestClient;
43 import org.openecomp.mso.apihandler.common.RequestClientFactory;
44 import org.openecomp.mso.apihandler.common.ResponseHandler;
45 import org.openecomp.mso.logger.MessageEnum;
46 import org.openecomp.mso.logger.MsoAlarmLogger;
47 import org.openecomp.mso.logger.MsoLogger;
48 import org.openecomp.mso.utils.UUIDChecker;
49
50 import com.wordnik.swagger.annotations.Api;
51 import com.wordnik.swagger.annotations.ApiOperation;
52
53 @Path("/tasks")
54 @Api(value="/tasks/{version: [vV]1}",description="Queries of Manual Tasks")
55 public class TasksHandler {
56
57     private static MsoAlarmLogger alarmLogger = new MsoAlarmLogger ();
58     private static MsoLogger msoLogger = MsoLogger.getMsoLogger (MsoLogger.Catalog.APIH);
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) throws ParseException {
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<>();
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, Constants.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 (),e);
168                         return resp;
169                 }
170                 TasksGetResponse trr = new TasksGetResponse();
171                 List<TaskList> taskList = new ArrayList<>();
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, Constants.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 (),e);
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",e);
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         return responseBack;
254                 
255     }    
256
257     protected MsoLogger getMsoLogger () {
258         return msoLogger;
259     }
260     
261     // Makes a GET call to Camunda to get variables for this task
262     private TaskList getTaskInfo(String taskId) throws Exception {
263         TaskList taskList;
264         String getRequestUrl = requestUrl + taskId + "/variables";
265                 HttpResponse getResponse;
266                 long subStartTime = System.currentTimeMillis();
267                 
268                 RequestClient requestClient = RequestClientFactory.getRequestClient (getRequestUrl, MsoPropertiesUtils.loadMsoProperties ());                                           
269                 // Capture audit event                                          
270                 msoLogger.debug ("MSO API Handler Get call to Camunda engine for url: " + requestClient.getUrl ());
271                 getResponse = requestClient.get();
272                 
273                 ResponseHandler respHandler = new ResponseHandler (getResponse, requestClient.getType ());
274                 int bpelStatus = respHandler.getStatus ();
275                 if (bpelStatus == HttpStatus.SC_ACCEPTED) {                     
276                         msoLogger.debug ("Received good response from Camunda");
277                                                 
278                         msoLogger.recordAuditEvent (subStartTime, MsoLogger.StatusCode.COMPLETE, MsoLogger.ResponseCode.Suc, "BPMN completed the request");
279                         String respBody = respHandler.getResponseBody();                
280                         if (respBody != null) {
281                                 taskList = buildTaskList(taskId, respBody);                             
282                         }
283                         else {
284                                 throw new Exception("Null task info from Camunda");
285                         }
286                         
287                 }
288                 else {
289                         throw new Exception ("Bad GET response from Camunda. Status is " + bpelStatus);
290                 }               
291                 
292         return taskList;
293         
294     }
295     
296     private TaskList buildTaskList(String taskId, String respBody) throws ParseException {
297         TaskList taskList = new TaskList();
298         JSONObject variables = new JSONObject(respBody);
299         
300         taskList.setTaskId(taskId);
301         taskList.setType(getOptVariableValue(variables, "type"));
302         taskList.setNfRole(getOptVariableValue(variables, "nfRole"));
303         taskList.setSubscriptionServiceType(getOptVariableValue(variables, "subscriptionServiceType"));
304         taskList.setOriginalRequestId(getOptVariableValue(variables, "originalRequestId"));
305         taskList.setOriginalRequestorId(getOptVariableValue(variables, "originalRequestorId"));
306         taskList.setErrorSource(getOptVariableValue(variables, "errorSource"));
307         taskList.setErrorCode(getOptVariableValue(variables, "errorCode"));
308         taskList.setErrorMessage(getOptVariableValue(variables, "errorMessage"));
309         taskList.setBuildingBlockName(getOptVariableValue(variables, "buildingBlockName"));
310         taskList.setBuildingBlockStep(getOptVariableValue(variables, "buildingBlockStep"));  
311         taskList.setValidResponses(new JSONArray("[" + getOptVariableValue(variables, "validResponses").toLowerCase() + "]"));
312         
313         return taskList;        
314     }
315     
316     private String getOptVariableValue(JSONObject variables, String name) throws ParseException {
317         String variableEntry = variables.optString(name);
318         String value = "";
319         if (!variableEntry.isEmpty()) {
320                 JSONObject variableEntryJson = new JSONObject(variableEntry);
321                 value = variableEntryJson.optString("value");                   
322         }
323         return value;
324     }
325    
326    
327 }