5 * Copyright (C) 2016 ONAP - SO
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
11 * http://www.apache.org/licenses/LICENSE-2.0
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.
21 package org.openecomp.mso.apihandlerinfra;
23 import org.openecomp.mso.apihandlerinfra.tasksbeans.*;
25 import java.text.ParseException;
26 import java.util.ArrayList;
27 import java.util.List;
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;
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;
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;
50 import com.wordnik.swagger.annotations.Api;
51 import com.wordnik.swagger.annotations.ApiOperation;
54 @Api(value="/tasks/{version: [vV]1}",description="Queries of Manual Tasks")
55 public class TasksHandler {
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/";
61 @Path("/{version:[vV]1}")
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
82 + " buildingBlockName:" + buildingBlockName
83 + " originalRequestDate:" + originalRequestDate
84 + " originalRequestorId: " + originalRequestorId);
86 // Prepare the query string to /task interface
87 TaskVariables tv = new TaskVariables();
89 List<TaskVariableValue> tvvList = new ArrayList<>();
91 if (originalRequestId != null) {
92 TaskVariableValue tvv = new TaskVariableValue();
93 tvv.setName("originalRequestId");
94 tvv.setValue(originalRequestId);
95 tvv.setOperator("eq");
98 if (subscriptionServiceType != null) {
99 TaskVariableValue tvv = new TaskVariableValue();
100 tvv.setName("subscriptionServiceType");
101 tvv.setValue(subscriptionServiceType);
102 tvv.setOperator("eq");
105 if (nfRole != null) {
106 TaskVariableValue tvv = new TaskVariableValue();
107 tvv.setName("nfRole");
108 tvv.setValue(nfRole);
109 tvv.setOperator("eq");
112 if (buildingBlockName != null) {
113 TaskVariableValue tvv = new TaskVariableValue();
114 tvv.setName("buildingBlockName");
115 tvv.setValue(buildingBlockName);
116 tvv.setOperator("eq");
119 if (originalRequestDate != null) {
120 TaskVariableValue tvv = new TaskVariableValue();
121 tvv.setName("originalRequestDate");
122 tvv.setValue(originalRequestDate);
123 tvv.setOperator("eq");
126 if (originalRequestorId != null) {
127 TaskVariableValue tvv = new TaskVariableValue();
128 tvv.setName("originalRequestorId");
129 tvv.setValue(originalRequestorId);
130 tvv.setOperator("eq");
134 tv.setTaskVariables(tvvList);
136 RequestClient requestClient = null;
137 MsoRequest msoRequest = new MsoRequest(requestId);
138 HttpResponse response = null;
139 long subStartTime = System.currentTimeMillis();
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 ());
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);
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,
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);
170 TasksGetResponse trr = new TasksGetResponse();
171 List<TaskList> taskList = new ArrayList<>();
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");
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);
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)) {
190 // Get variables info for each task ID
191 TaskList taskListEntry = null;
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,
203 alarmLogger.sendAlarm ("MsoConfigurationError",
204 MsoAlarmLogger.CRITICAL,
205 Messages.errors.get (ErrorNumbers.NO_COMMUNICATION_TO_BPEL));
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);
212 taskList.add(taskListEntry);
215 trr.setTaskList(taskList);
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,
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 ());
232 String jsonResponse = null;
234 ObjectMapper mapper = new ObjectMapper();
235 jsonResponse = mapper.writeValueAsString(trr);
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,
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 ());
251 msoLogger.recordAuditEvent (startTime, MsoLogger.StatusCode.COMPLETE, MsoLogger.ResponseCode.Suc, "Successful");
252 responseBack = Response.status (HttpStatus.SC_ACCEPTED).entity (jsonResponse).build ();
257 protected MsoLogger getMsoLogger () {
261 // Makes a GET call to Camunda to get variables for this task
262 private TaskList getTaskInfo(String taskId) throws Exception {
264 String getRequestUrl = requestUrl + taskId + "/variables";
265 HttpResponse getResponse;
266 long subStartTime = System.currentTimeMillis();
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();
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");
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);
284 throw new Exception("Null task info from Camunda");
289 throw new Exception ("Bad GET response from Camunda. Status is " + bpelStatus);
296 private TaskList buildTaskList(String taskId, String respBody) throws ParseException {
297 TaskList taskList = new TaskList();
298 JSONObject variables = new JSONObject(respBody);
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() + "]"));
316 private String getOptVariableValue(JSONObject variables, String name) throws ParseException {
317 String variableEntry = variables.optString(name);
319 if (!variableEntry.isEmpty()) {
320 JSONObject variableEntryJson = new JSONObject(variableEntry);
321 value = variableEntryJson.optString("value");