AT&T 1712 and 1802 release code
[so.git] / mso-api-handlers / mso-api-handler-infra / src / main / java / org / openecomp / mso / apihandlerinfra / ManualTasks.java
1 /*-\r
2  * ============LICENSE_START=======================================================\r
3  * ONAP - SO\r
4  * ================================================================================\r
5  * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved.\r
6  * Copyright (C) 2017 Huawei Technologies Co., Ltd. All rights reserved.\r
7  * ================================================================================\r
8  * Licensed under the Apache License, Version 2.0 (the "License");\r
9  * you may not use this file except in compliance with the License.\r
10  * You may obtain a copy of the License at\r
11  *\r
12  *      http://www.apache.org/licenses/LICENSE-2.0\r
13  *\r
14  * Unless required by applicable law or agreed to in writing, software\r
15  * distributed under the License is distributed on an "AS IS" BASIS,\r
16  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r
17  * See the License for the specific language governing permissions and\r
18  * limitations under the License.\r
19  * ============LICENSE_END=========================================================\r
20  */\r
21 package org.openecomp.mso.apihandlerinfra;\r
22 \r
23 import org.openecomp.mso.logger.MessageEnum;\r
24 import org.openecomp.mso.logger.MsoAlarmLogger;\r
25 import org.openecomp.mso.logger.MsoLogger;\r
26 import org.openecomp.mso.utils.UUIDChecker;\r
27 \r
28 import com.wordnik.swagger.annotations.ApiOperation;\r
29 \r
30 import org.apache.http.HttpResponse;\r
31 import org.apache.http.HttpStatus;\r
32 import org.openecomp.mso.apihandler.common.ValidationException;\r
33 import org.openecomp.mso.apihandler.common.ErrorNumbers;\r
34 import org.openecomp.mso.apihandler.common.RequestClient;\r
35 import org.openecomp.mso.apihandler.common.RequestClientFactory;\r
36 import org.openecomp.mso.apihandler.common.ResponseHandler;\r
37 import org.openecomp.mso.apihandlerinfra.tasksbeans.*;\r
38 \r
39 import javax.ws.rs.Consumes;\r
40 import javax.ws.rs.POST;\r
41 import javax.ws.rs.Path;\r
42 import javax.ws.rs.PathParam;\r
43 import javax.ws.rs.Produces;\r
44 import javax.ws.rs.core.MediaType;\r
45 import javax.ws.rs.core.Response;\r
46 \r
47 import com.fasterxml.jackson.databind.ObjectMapper;\r
48 import com.fasterxml.jackson.databind.SerializationFeature;\r
49 \r
50 \r
51 @Path("/tasks")\r
52 public class ManualTasks {\r
53         private static MsoLogger msoLogger = MsoLogger.getMsoLogger (MsoLogger.Catalog.APIH);\r
54         private static MsoAlarmLogger alarmLogger = new MsoAlarmLogger ();\r
55         \r
56         @POST\r
57         @Path("/{version:[vV]1}/{taskId}/complete")\r
58         @Consumes(MediaType.APPLICATION_JSON)\r
59         @Produces(MediaType.APPLICATION_JSON)\r
60         @ApiOperation(value="Complete specified task",response=Response.class)\r
61         public Response completeTask(String request, @PathParam("version") String version, @PathParam("taskId") String taskId) {\r
62                 \r
63                 String requestId = UUIDChecker.generateUUID(msoLogger);\r
64                 long startTime = System.currentTimeMillis ();\r
65                 msoLogger.debug ("requestId is: " + requestId);\r
66                 TasksRequest tr = null;\r
67                 \r
68                 MsoRequest msoRequest = new MsoRequest (requestId);\r
69                 \r
70                 try{\r
71                         ObjectMapper mapper = new ObjectMapper();\r
72                         tr= mapper.readValue(request, TasksRequest.class);\r
73                         \r
74                         if (tr.getRequestDetails() == null) {\r
75                                 throw new ValidationException("requestDetails");                                \r
76                         }\r
77                         if (tr.getRequestDetails().getRequestInfo() == null) {\r
78                                 throw new ValidationException("requestInfo");\r
79                         }\r
80                         if (empty(tr.getRequestDetails().getRequestInfo().getSource())) {\r
81                                 throw new ValidationException("source");\r
82                         }\r
83                         if (empty(tr.getRequestDetails().getRequestInfo().getRequestorId())) {\r
84                                 throw new ValidationException("requestorId");\r
85                         }\r
86 \r
87                 } catch(Exception e){\r
88                         msoLogger.debug ("Mapping of request to JSON object failed : ", e);\r
89                         Response response = msoRequest.buildServiceErrorResponse(HttpStatus.SC_BAD_REQUEST, MsoException.ServiceException,\r
90                                         "Mapping of request to JSON object failed.  " + e.getMessage(),\r
91                                         ErrorNumbers.SVC_BAD_PARAMETER, null);\r
92                         \r
93                         msoLogger.error (MessageEnum.APIH_REQUEST_VALIDATION_ERROR, Constants.MSO_PROP_APIHANDLER_INFRA, "", "", MsoLogger.ErrorCode.SchemaError, request, e);\r
94                         msoLogger.recordAuditEvent (startTime, MsoLogger.StatusCode.ERROR, MsoLogger.ResponseCode.SchemaError, "Mapping of request to JSON object failed");\r
95                         msoLogger.debug ("End of the transaction, the final response is: " + (String) response.getEntity ());\r
96                         return response;\r
97                 }               \r
98                 \r
99                 // Transform the request to Camunda-style Complete request\r
100                 Variables variablesForComplete = new Variables();\r
101                 Value sourceValue = new Value(); \r
102                 sourceValue.setValue(tr.getRequestDetails().getRequestInfo().getSource());\r
103                 Value responseValue = new Value(); \r
104                 responseValue.setValue(tr.getRequestDetails().getRequestInfo().getResponseValue().name());\r
105                 Value requestorIdValue = new Value(); \r
106                 requestorIdValue.setValue(tr.getRequestDetails().getRequestInfo().getRequestorId());\r
107                 variablesForComplete.setSource(sourceValue);\r
108                 variablesForComplete.setResponseValue(responseValue);\r
109                 variablesForComplete.setRequestorId(requestorIdValue);\r
110                 \r
111                 String camundaJsonReq = null;\r
112                 try {\r
113                         ObjectMapper mapper = new ObjectMapper();\r
114                         mapper.configure(SerializationFeature.WRAP_ROOT_VALUE, true);\r
115                         camundaJsonReq = mapper.writeValueAsString(variablesForComplete);\r
116                         msoLogger.debug("Camunda Json Request: " + camundaJsonReq);\r
117                 } catch(Exception e){\r
118                         msoLogger.debug ("Mapping of JSON object to Camunda request failed : ", e);\r
119                         Response response = msoRequest.buildServiceErrorResponse(HttpStatus.SC_INTERNAL_SERVER_ERROR, MsoException.ServiceException,\r
120                                 "Mapping of JSON object to Camunda Request failed.  " + e.getMessage(),\r
121                                 ErrorNumbers.SVC_GENERAL_SERVICE_ERROR, null);\r
122                 \r
123                         msoLogger.error (MessageEnum.APIH_GENERAL_EXCEPTION, Constants.MSO_PROP_APIHANDLER_INFRA, "", "", MsoLogger.ErrorCode.UnknownError, request, e);\r
124                         msoLogger.recordAuditEvent (startTime, MsoLogger.StatusCode.ERROR, MsoLogger.ResponseCode.InternalError, "Mapping of JSON object to Camunda request failed");\r
125                         msoLogger.debug ("End of the transaction, the final response is: " + (String) response.getEntity ());\r
126                         return response;\r
127                 }               \r
128                 \r
129                 RequestClient requestClient = null;\r
130                 HttpResponse response = null;\r
131                 long subStartTime = System.currentTimeMillis();\r
132                 String requestUrl = "/mso/task/" + taskId + "/complete";\r
133                 try {\r
134                         requestClient = RequestClientFactory.getRequestClient (requestUrl, MsoPropertiesUtils.loadMsoProperties ());\r
135                         // Capture audit event\r
136                         msoLogger.debug ("MSO API Handler Posting call to Camunda engine for url: " + requestClient.getUrl ());\r
137 \r
138                         System.out.println("URL : " + requestClient.getUrl ());\r
139                         msoLogger.recordAuditEvent (startTime, MsoLogger.StatusCode.ERROR, MsoLogger.ResponseCode.InternalError, "Mapping of JSON object to Camunda request failed");\r
140                         \r
141                         response = requestClient.post(camundaJsonReq);\r
142 \r
143                         msoLogger.recordMetricEvent (subStartTime, MsoLogger.StatusCode.COMPLETE, MsoLogger.ResponseCode.Suc, "Successfully received response from BPMN engine", "BPMN", requestUrl, null);\r
144                 } catch (Exception e) {\r
145                     msoLogger.debug ("Exception:", e);\r
146                         msoLogger.recordMetricEvent (subStartTime, MsoLogger.StatusCode.ERROR, MsoLogger.ResponseCode.CommunicationError, "Exception while communicate with BPMN engine", "BPMN", requestUrl, null);\r
147                         msoRequest.setStatus (org.openecomp.mso.apihandlerinfra.vnfbeans.RequestStatusType.FAILED);\r
148                         Response resp = msoRequest.buildServiceErrorResponse (HttpStatus.SC_BAD_GATEWAY,\r
149                                         MsoException.ServiceException,\r
150                                         "Failed calling bpmn " + e.getMessage (),\r
151                                         ErrorNumbers.SVC_NO_SERVER_RESOURCES,\r
152                                         null);\r
153                         alarmLogger.sendAlarm ("MsoConfigurationError",\r
154                                         MsoAlarmLogger.CRITICAL,\r
155                                         Messages.errors.get (ErrorNumbers.NO_COMMUNICATION_TO_BPEL));\r
156                         msoRequest.updateFinalStatus (Status.FAILED);\r
157                         msoLogger.error (MessageEnum.APIH_BPEL_COMMUNICATE_ERROR, Constants.MSO_PROP_APIHANDLER_INFRA, "", "", MsoLogger.ErrorCode.AvailabilityError, "Exception while communicate with BPMN engine");\r
158                         msoLogger.recordAuditEvent (startTime, MsoLogger.StatusCode.ERROR, MsoLogger.ResponseCode.CommunicationError, "Exception while communicate with BPMN engine");\r
159                         msoLogger.debug ("End of the transaction, the final response is: " + (String) resp.getEntity ());\r
160                         return resp;\r
161                 }\r
162 \r
163                 if (response == null) {\r
164                         msoRequest.setStatus (org.openecomp.mso.apihandlerinfra.vnfbeans.RequestStatusType.FAILED);\r
165                         Response resp = msoRequest.buildServiceErrorResponse (HttpStatus.SC_BAD_GATEWAY,\r
166                                         MsoException.ServiceException,\r
167                                         "bpelResponse is null",\r
168                                         ErrorNumbers.SVC_NO_SERVER_RESOURCES,\r
169                                         null);\r
170                         msoRequest.updateFinalStatus (Status.FAILED);\r
171                         msoLogger.error (MessageEnum.APIH_BPEL_COMMUNICATE_ERROR, Constants.MSO_PROP_APIHANDLER_INFRA, "", "", MsoLogger.ErrorCode.BusinessProcesssError, "Null response from BPEL");\r
172                         msoLogger.recordAuditEvent (startTime, MsoLogger.StatusCode.ERROR, MsoLogger.ResponseCode.InternalError, "Null response from BPMN");\r
173                         msoLogger.debug ("End of the transaction, the final response is: " + (String) resp.getEntity ());\r
174                         return resp;\r
175                 }\r
176 \r
177                 ResponseHandler respHandler = new ResponseHandler (response, requestClient.getType ());\r
178                 int bpelStatus = respHandler.getStatus ();\r
179 \r
180                 // BPEL accepted the request, the request is in progress\r
181                 if (bpelStatus == HttpStatus.SC_NO_CONTENT || bpelStatus == HttpStatus.SC_ACCEPTED) {                   \r
182                         msoLogger.debug ("Received good response from Camunda");\r
183                         msoRequest.setStatus (org.openecomp.mso.apihandlerinfra.vnfbeans.RequestStatusType.IN_PROGRESS);                        \r
184                         msoLogger.recordAuditEvent (startTime, MsoLogger.StatusCode.COMPLETE, MsoLogger.ResponseCode.Suc, "BPMN completed the request");\r
185                         TaskRequestReference trr = new TaskRequestReference();\r
186                         trr.setTaskId(taskId);\r
187                         String completeResp = null;\r
188                         try {\r
189                                 ObjectMapper mapper = new ObjectMapper();\r
190                                 mapper.configure(SerializationFeature.WRAP_ROOT_VALUE, true);\r
191                                 completeResp = mapper.writeValueAsString(trr);\r
192                         }\r
193                         catch (Exception e) {\r
194                                 msoLogger.debug("Unable to format response",e);\r
195                                 Response resp = msoRequest.buildServiceErrorResponse(bpelStatus,\r
196                                                 MsoException.ServiceException,\r
197                                                 "Request Failed due to bad response format" ,\r
198                                                 ErrorNumbers.SVC_DETAILED_SERVICE_ERROR,\r
199                                                 null);                          \r
200                                 msoLogger.error (MessageEnum.APIH_BPEL_RESPONSE_ERROR, requestClient.getUrl (), "", "", MsoLogger.ErrorCode.BusinessProcesssError, "Bad response format");\r
201                                 msoLogger.recordAuditEvent (startTime, MsoLogger.StatusCode.ERROR, MsoLogger.ResponseCode.InternalError, "Bad response format");\r
202                                 msoLogger.debug ("End of the transaction, the final response is: " + (String) resp.getEntity ());\r
203                                 return resp;\r
204                         }\r
205                         msoLogger.debug("Response to the caller: " + completeResp);                     \r
206                         msoLogger.debug ("End of the transaction, the final response is: " + (String) completeResp);\r
207                         return Response.status (HttpStatus.SC_ACCEPTED).entity (completeResp).build ();\r
208                 } else {                        \r
209                                 msoRequest.setStatus (org.openecomp.mso.apihandlerinfra.vnfbeans.RequestStatusType.FAILED);\r
210                                 Response resp = msoRequest.buildServiceErrorResponse(bpelStatus,\r
211                                                 MsoException.ServiceException,\r
212                                                 "Request Failed due to BPEL error with HTTP Status= %1" ,\r
213                                                 ErrorNumbers.SVC_DETAILED_SERVICE_ERROR,\r
214                                                 null);                          \r
215                                 msoLogger.error (MessageEnum.APIH_BPEL_RESPONSE_ERROR, requestClient.getUrl (), "", "", MsoLogger.ErrorCode.BusinessProcesssError, "Response from BPEL engine is empty");\r
216                                 msoLogger.recordAuditEvent (startTime, MsoLogger.StatusCode.ERROR, MsoLogger.ResponseCode.InternalError, "Response from BPEL engine is empty");\r
217                                 msoLogger.debug ("End of the transaction, the final response is: " + (String) resp.getEntity ());\r
218                                 return resp;\r
219                 }       \r
220         \r
221         }\r
222         \r
223         private static boolean empty(String s) {\r
224           return (s == null || s.trim().isEmpty());\r
225   }\r
226                 \r
227 }\r