Change the header to SO
[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  * ================================================================================\r
7  * Licensed under the Apache License, Version 2.0 (the "License");\r
8  * you may not use this file except in compliance with the License.\r
9  * You may obtain a copy of the License at\r
10  *\r
11  *      http://www.apache.org/licenses/LICENSE-2.0\r
12  *\r
13  * Unless required by applicable law or agreed to in writing, software\r
14  * distributed under the License is distributed on an "AS IS" BASIS,\r
15  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r
16  * See the License for the specific language governing permissions and\r
17  * limitations under the License.\r
18  * ============LICENSE_END=========================================================\r
19  */\r
20 package org.openecomp.mso.apihandlerinfra;\r
21 \r
22 import org.openecomp.mso.logger.MessageEnum;\r
23 import org.openecomp.mso.logger.MsoAlarmLogger;\r
24 import org.openecomp.mso.logger.MsoLogger;\r
25 import org.openecomp.mso.utils.UUIDChecker;\r
26 \r
27 import com.wordnik.swagger.annotations.ApiOperation;\r
28 \r
29 import org.apache.http.HttpResponse;\r
30 import org.apache.http.HttpStatus;\r
31 import org.openecomp.mso.apihandler.common.ValidationException;\r
32 import org.openecomp.mso.apihandler.common.ErrorNumbers;\r
33 import org.openecomp.mso.apihandler.common.RequestClient;\r
34 import org.openecomp.mso.apihandler.common.RequestClientFactory;\r
35 import org.openecomp.mso.apihandler.common.ResponseHandler;\r
36 import org.openecomp.mso.apihandlerinfra.tasksbeans.*;\r
37 \r
38 import javax.ws.rs.Consumes;\r
39 import javax.ws.rs.POST;\r
40 import javax.ws.rs.Path;\r
41 import javax.ws.rs.PathParam;\r
42 import javax.ws.rs.Produces;\r
43 import javax.ws.rs.core.MediaType;\r
44 import javax.ws.rs.core.Response;\r
45 \r
46 import org.codehaus.jackson.map.ObjectMapper;\r
47 import org.codehaus.jackson.map.SerializationConfig;\r
48 \r
49 \r
50 @Path("/tasks")\r
51 public class ManualTasks {\r
52         private static MsoLogger msoLogger = MsoLogger.getMsoLogger (MsoLogger.Catalog.APIH);\r
53         private static MsoAlarmLogger alarmLogger = new MsoAlarmLogger ();\r
54         public final static String MSO_PROP_APIHANDLER_INFRA = "MSO_PROP_APIHANDLER_INFRA";     \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, 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(SerializationConfig.Feature.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, 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.recordMetricEvent (subStartTime, MsoLogger.StatusCode.ERROR, MsoLogger.ResponseCode.CommunicationError, "Exception while communicate with BPMN engine", "BPMN", requestUrl, null);\r
146                         msoRequest.setStatus (org.openecomp.mso.apihandlerinfra.vnfbeans.RequestStatusType.FAILED);\r
147                         Response resp = msoRequest.buildServiceErrorResponse (HttpStatus.SC_BAD_GATEWAY,\r
148                                         MsoException.ServiceException,\r
149                                         "Failed calling bpmn " + e.getMessage (),\r
150                                         ErrorNumbers.SVC_NO_SERVER_RESOURCES,\r
151                                         null);\r
152                         alarmLogger.sendAlarm ("MsoConfigurationError",\r
153                                         MsoAlarmLogger.CRITICAL,\r
154                                         Messages.errors.get (ErrorNumbers.NO_COMMUNICATION_TO_BPEL));\r
155                         msoRequest.updateFinalStatus (Status.FAILED);\r
156                         msoLogger.error (MessageEnum.APIH_BPEL_COMMUNICATE_ERROR, MSO_PROP_APIHANDLER_INFRA, "", "", MsoLogger.ErrorCode.AvailabilityError, "Exception while communicate with BPMN engine");\r
157                         msoLogger.recordAuditEvent (startTime, MsoLogger.StatusCode.ERROR, MsoLogger.ResponseCode.CommunicationError, "Exception while communicate with BPMN engine");\r
158                         msoLogger.debug ("End of the transaction, the final response is: " + (String) resp.getEntity ());\r
159                         return resp;\r
160                 }\r
161 \r
162                 if (response == null) {\r
163                         msoRequest.setStatus (org.openecomp.mso.apihandlerinfra.vnfbeans.RequestStatusType.FAILED);\r
164                         Response resp = msoRequest.buildServiceErrorResponse (HttpStatus.SC_BAD_GATEWAY,\r
165                                         MsoException.ServiceException,\r
166                                         "bpelResponse is null",\r
167                                         ErrorNumbers.SVC_NO_SERVER_RESOURCES,\r
168                                         null);\r
169                         msoRequest.updateFinalStatus (Status.FAILED);\r
170                         msoLogger.error (MessageEnum.APIH_BPEL_COMMUNICATE_ERROR, MSO_PROP_APIHANDLER_INFRA, "", "", MsoLogger.ErrorCode.BusinessProcesssError, "Null response from BPEL");\r
171                         msoLogger.recordAuditEvent (startTime, MsoLogger.StatusCode.ERROR, MsoLogger.ResponseCode.InternalError, "Null response from BPMN");\r
172                         msoLogger.debug ("End of the transaction, the final response is: " + (String) resp.getEntity ());\r
173                         return resp;\r
174                 }\r
175 \r
176                 ResponseHandler respHandler = new ResponseHandler (response, requestClient.getType ());\r
177                 int bpelStatus = respHandler.getStatus ();\r
178 \r
179                 // BPEL accepted the request, the request is in progress\r
180                 if (bpelStatus == HttpStatus.SC_NO_CONTENT || bpelStatus == HttpStatus.SC_ACCEPTED) {                   \r
181                         msoLogger.debug ("Received good response from Camunda");\r
182                         msoRequest.setStatus (org.openecomp.mso.apihandlerinfra.vnfbeans.RequestStatusType.IN_PROGRESS);                        \r
183                         msoLogger.recordAuditEvent (startTime, MsoLogger.StatusCode.COMPLETE, MsoLogger.ResponseCode.Suc, "BPMN completed the request");\r
184                         TaskRequestReference trr = new TaskRequestReference();\r
185                         trr.setTaskId(taskId);\r
186                         String completeResp = null;\r
187                         try {\r
188                                 ObjectMapper mapper = new ObjectMapper();\r
189                                 mapper.configure(SerializationConfig.Feature.WRAP_ROOT_VALUE, true);\r
190                                 completeResp = mapper.writeValueAsString(trr);\r
191                         }\r
192                         catch (Exception e) {\r
193                                 msoLogger.debug("Unable to format response");\r
194                                 Response resp = msoRequest.buildServiceErrorResponse(bpelStatus,\r
195                                                 MsoException.ServiceException,\r
196                                                 "Request Failed due to bad response format" ,\r
197                                                 ErrorNumbers.SVC_DETAILED_SERVICE_ERROR,\r
198                                                 null);                          \r
199                                 msoLogger.error (MessageEnum.APIH_BPEL_RESPONSE_ERROR, requestClient.getUrl (), "", "", MsoLogger.ErrorCode.BusinessProcesssError, "Bad response format");\r
200                                 msoLogger.recordAuditEvent (startTime, MsoLogger.StatusCode.ERROR, MsoLogger.ResponseCode.InternalError, "Bad response format");\r
201                                 msoLogger.debug ("End of the transaction, the final response is: " + (String) resp.getEntity ());\r
202                                 return resp;\r
203                         }\r
204                         msoLogger.debug("Response to the caller: " + completeResp);                     \r
205                         msoLogger.debug ("End of the transaction, the final response is: " + (String) completeResp);\r
206                         return Response.status (HttpStatus.SC_ACCEPTED).entity (completeResp).build ();\r
207                 } else {                        \r
208                                 msoRequest.setStatus (org.openecomp.mso.apihandlerinfra.vnfbeans.RequestStatusType.FAILED);\r
209                                 Response resp = msoRequest.buildServiceErrorResponse(bpelStatus,\r
210                                                 MsoException.ServiceException,\r
211                                                 "Request Failed due to BPEL error with HTTP Status= %1" ,\r
212                                                 ErrorNumbers.SVC_DETAILED_SERVICE_ERROR,\r
213                                                 null);                          \r
214                                 msoLogger.error (MessageEnum.APIH_BPEL_RESPONSE_ERROR, requestClient.getUrl (), "", "", MsoLogger.ErrorCode.BusinessProcesssError, "Response from BPEL engine is empty");\r
215                                 msoLogger.recordAuditEvent (startTime, MsoLogger.StatusCode.ERROR, MsoLogger.ResponseCode.InternalError, "Response from BPEL engine is empty");\r
216                                 msoLogger.debug ("End of the transaction, the final response is: " + (String) resp.getEntity ());\r
217                                 return resp;\r
218                 }       \r
219         \r
220         }\r
221         \r
222         private static boolean empty(String s) {\r
223           return (s == null || s.trim().isEmpty());\r
224   }\r
225                 \r
226 }\r