f6abcc35b1544ee33090e5a2a5a4acbe51e480ee
[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 org.codehaus.jackson.map.ObjectMapper;\r
48 import org.codehaus.jackson.map.SerializationConfig;\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         public final static String MSO_PROP_APIHANDLER_INFRA = "MSO_PROP_APIHANDLER_INFRA";     \r
56         \r
57         @POST\r
58         @Path("/{version:[vV]1}/{taskId}/complete")\r
59         @Consumes(MediaType.APPLICATION_JSON)\r
60         @Produces(MediaType.APPLICATION_JSON)\r
61         @ApiOperation(value="Complete specified task",response=Response.class)\r
62         public Response completeTask(String request, @PathParam("version") String version, @PathParam("taskId") String taskId) {\r
63                 \r
64                 String requestId = UUIDChecker.generateUUID(msoLogger);\r
65                 long startTime = System.currentTimeMillis ();\r
66                 msoLogger.debug ("requestId is: " + requestId);\r
67                 TasksRequest tr = null;\r
68                 \r
69                 MsoRequest msoRequest = new MsoRequest (requestId);\r
70                 \r
71                 try{\r
72                         ObjectMapper mapper = new ObjectMapper();\r
73                         tr= mapper.readValue(request, TasksRequest.class);\r
74                         \r
75                         if (tr.getRequestDetails() == null) {\r
76                                 throw new ValidationException("requestDetails");                                \r
77                         }\r
78                         if (tr.getRequestDetails().getRequestInfo() == null) {\r
79                                 throw new ValidationException("requestInfo");\r
80                         }\r
81                         if (empty(tr.getRequestDetails().getRequestInfo().getSource())) {\r
82                                 throw new ValidationException("source");\r
83                         }\r
84                         if (empty(tr.getRequestDetails().getRequestInfo().getRequestorId())) {\r
85                                 throw new ValidationException("requestorId");\r
86                         }\r
87 \r
88                 } catch(Exception e){\r
89                         msoLogger.debug ("Mapping of request to JSON object failed : ", e);\r
90                         Response response = msoRequest.buildServiceErrorResponse(HttpStatus.SC_BAD_REQUEST, MsoException.ServiceException,\r
91                                         "Mapping of request to JSON object failed.  " + e.getMessage(),\r
92                                         ErrorNumbers.SVC_BAD_PARAMETER, null);\r
93                         \r
94                         msoLogger.error (MessageEnum.APIH_REQUEST_VALIDATION_ERROR, MSO_PROP_APIHANDLER_INFRA, "", "", MsoLogger.ErrorCode.SchemaError, request, e);\r
95                         msoLogger.recordAuditEvent (startTime, MsoLogger.StatusCode.ERROR, MsoLogger.ResponseCode.SchemaError, "Mapping of request to JSON object failed");\r
96                         msoLogger.debug ("End of the transaction, the final response is: " + (String) response.getEntity ());\r
97                         return response;\r
98                 }               \r
99                 \r
100                 // Transform the request to Camunda-style Complete request\r
101                 Variables variablesForComplete = new Variables();\r
102                 Value sourceValue = new Value(); \r
103                 sourceValue.setValue(tr.getRequestDetails().getRequestInfo().getSource());\r
104                 Value responseValue = new Value(); \r
105                 responseValue.setValue(tr.getRequestDetails().getRequestInfo().getResponseValue().name());\r
106                 Value requestorIdValue = new Value(); \r
107                 requestorIdValue.setValue(tr.getRequestDetails().getRequestInfo().getRequestorId());\r
108                 variablesForComplete.setSource(sourceValue);\r
109                 variablesForComplete.setResponseValue(responseValue);\r
110                 variablesForComplete.setRequestorId(requestorIdValue);\r
111                 \r
112                 String camundaJsonReq = null;\r
113                 try {\r
114                         ObjectMapper mapper = new ObjectMapper();\r
115                         mapper.configure(SerializationConfig.Feature.WRAP_ROOT_VALUE, true);\r
116                         camundaJsonReq = mapper.writeValueAsString(variablesForComplete);\r
117                         msoLogger.debug("Camunda Json Request: " + camundaJsonReq);\r
118                 } catch(Exception e){\r
119                         msoLogger.debug ("Mapping of JSON object to Camunda request failed : ", e);\r
120                         Response response = msoRequest.buildServiceErrorResponse(HttpStatus.SC_INTERNAL_SERVER_ERROR, MsoException.ServiceException,\r
121                                 "Mapping of JSON object to Camunda Request failed.  " + e.getMessage(),\r
122                                 ErrorNumbers.SVC_GENERAL_SERVICE_ERROR, null);\r
123                 \r
124                         msoLogger.error (MessageEnum.APIH_GENERAL_EXCEPTION, MSO_PROP_APIHANDLER_INFRA, "", "", MsoLogger.ErrorCode.UnknownError, request, e);\r
125                         msoLogger.recordAuditEvent (startTime, MsoLogger.StatusCode.ERROR, MsoLogger.ResponseCode.InternalError, "Mapping of JSON object to Camunda request failed");\r
126                         msoLogger.debug ("End of the transaction, the final response is: " + (String) response.getEntity ());\r
127                         return response;\r
128                 }               \r
129                 \r
130                 RequestClient requestClient = null;\r
131                 HttpResponse response = null;\r
132                 long subStartTime = System.currentTimeMillis();\r
133                 String requestUrl = "/mso/task/" + taskId + "/complete";\r
134                 try {\r
135                         requestClient = RequestClientFactory.getRequestClient (requestUrl, MsoPropertiesUtils.loadMsoProperties ());\r
136                         // Capture audit event\r
137                         msoLogger.debug ("MSO API Handler Posting call to Camunda engine for url: " + requestClient.getUrl ());\r
138 \r
139                         System.out.println("URL : " + requestClient.getUrl ());\r
140                         msoLogger.recordAuditEvent (startTime, MsoLogger.StatusCode.ERROR, MsoLogger.ResponseCode.InternalError, "Mapping of JSON object to Camunda request failed");\r
141                         \r
142                         response = requestClient.post(camundaJsonReq);\r
143 \r
144                         msoLogger.recordMetricEvent (subStartTime, MsoLogger.StatusCode.COMPLETE, MsoLogger.ResponseCode.Suc, "Successfully received response from BPMN engine", "BPMN", requestUrl, null);\r
145                 } catch (Exception e) {\r
146                     msoLogger.debug ("Exception:", e);\r
147                         msoLogger.recordMetricEvent (subStartTime, MsoLogger.StatusCode.ERROR, MsoLogger.ResponseCode.CommunicationError, "Exception while communicate with BPMN engine", "BPMN", requestUrl, null);\r
148                         msoRequest.setStatus (org.openecomp.mso.apihandlerinfra.vnfbeans.RequestStatusType.FAILED);\r
149                         Response resp = msoRequest.buildServiceErrorResponse (HttpStatus.SC_BAD_GATEWAY,\r
150                                         MsoException.ServiceException,\r
151                                         "Failed calling bpmn " + e.getMessage (),\r
152                                         ErrorNumbers.SVC_NO_SERVER_RESOURCES,\r
153                                         null);\r
154                         alarmLogger.sendAlarm ("MsoConfigurationError",\r
155                                         MsoAlarmLogger.CRITICAL,\r
156                                         Messages.errors.get (ErrorNumbers.NO_COMMUNICATION_TO_BPEL));\r
157                         msoRequest.updateFinalStatus (Status.FAILED);\r
158                         msoLogger.error (MessageEnum.APIH_BPEL_COMMUNICATE_ERROR, MSO_PROP_APIHANDLER_INFRA, "", "", MsoLogger.ErrorCode.AvailabilityError, "Exception while communicate with BPMN engine");\r
159                         msoLogger.recordAuditEvent (startTime, MsoLogger.StatusCode.ERROR, MsoLogger.ResponseCode.CommunicationError, "Exception while communicate with BPMN engine");\r
160                         msoLogger.debug ("End of the transaction, the final response is: " + (String) resp.getEntity ());\r
161                         return resp;\r
162                 }\r
163 \r
164                 if (response == null) {\r
165                         msoRequest.setStatus (org.openecomp.mso.apihandlerinfra.vnfbeans.RequestStatusType.FAILED);\r
166                         Response resp = msoRequest.buildServiceErrorResponse (HttpStatus.SC_BAD_GATEWAY,\r
167                                         MsoException.ServiceException,\r
168                                         "bpelResponse is null",\r
169                                         ErrorNumbers.SVC_NO_SERVER_RESOURCES,\r
170                                         null);\r
171                         msoRequest.updateFinalStatus (Status.FAILED);\r
172                         msoLogger.error (MessageEnum.APIH_BPEL_COMMUNICATE_ERROR, MSO_PROP_APIHANDLER_INFRA, "", "", MsoLogger.ErrorCode.BusinessProcesssError, "Null response from BPEL");\r
173                         msoLogger.recordAuditEvent (startTime, MsoLogger.StatusCode.ERROR, MsoLogger.ResponseCode.InternalError, "Null response from BPMN");\r
174                         msoLogger.debug ("End of the transaction, the final response is: " + (String) resp.getEntity ());\r
175                         return resp;\r
176                 }\r
177 \r
178                 ResponseHandler respHandler = new ResponseHandler (response, requestClient.getType ());\r
179                 int bpelStatus = respHandler.getStatus ();\r
180 \r
181                 // BPEL accepted the request, the request is in progress\r
182                 if (bpelStatus == HttpStatus.SC_NO_CONTENT || bpelStatus == HttpStatus.SC_ACCEPTED) {                   \r
183                         msoLogger.debug ("Received good response from Camunda");\r
184                         msoRequest.setStatus (org.openecomp.mso.apihandlerinfra.vnfbeans.RequestStatusType.IN_PROGRESS);                        \r
185                         msoLogger.recordAuditEvent (startTime, MsoLogger.StatusCode.COMPLETE, MsoLogger.ResponseCode.Suc, "BPMN completed the request");\r
186                         TaskRequestReference trr = new TaskRequestReference();\r
187                         trr.setTaskId(taskId);\r
188                         String completeResp = null;\r
189                         try {\r
190                                 ObjectMapper mapper = new ObjectMapper();\r
191                                 mapper.configure(SerializationConfig.Feature.WRAP_ROOT_VALUE, true);\r
192                                 completeResp = mapper.writeValueAsString(trr);\r
193                         }\r
194                         catch (Exception e) {\r
195                                 msoLogger.debug("Unable to format response",e);\r
196                                 Response resp = msoRequest.buildServiceErrorResponse(bpelStatus,\r
197                                                 MsoException.ServiceException,\r
198                                                 "Request Failed due to bad response format" ,\r
199                                                 ErrorNumbers.SVC_DETAILED_SERVICE_ERROR,\r
200                                                 null);                          \r
201                                 msoLogger.error (MessageEnum.APIH_BPEL_RESPONSE_ERROR, requestClient.getUrl (), "", "", MsoLogger.ErrorCode.BusinessProcesssError, "Bad response format");\r
202                                 msoLogger.recordAuditEvent (startTime, MsoLogger.StatusCode.ERROR, MsoLogger.ResponseCode.InternalError, "Bad response format");\r
203                                 msoLogger.debug ("End of the transaction, the final response is: " + (String) resp.getEntity ());\r
204                                 return resp;\r
205                         }\r
206                         msoLogger.debug("Response to the caller: " + completeResp);                     \r
207                         msoLogger.debug ("End of the transaction, the final response is: " + (String) completeResp);\r
208                         return Response.status (HttpStatus.SC_ACCEPTED).entity (completeResp).build ();\r
209                 } else {                        \r
210                                 msoRequest.setStatus (org.openecomp.mso.apihandlerinfra.vnfbeans.RequestStatusType.FAILED);\r
211                                 Response resp = msoRequest.buildServiceErrorResponse(bpelStatus,\r
212                                                 MsoException.ServiceException,\r
213                                                 "Request Failed due to BPEL error with HTTP Status= %1" ,\r
214                                                 ErrorNumbers.SVC_DETAILED_SERVICE_ERROR,\r
215                                                 null);                          \r
216                                 msoLogger.error (MessageEnum.APIH_BPEL_RESPONSE_ERROR, requestClient.getUrl (), "", "", MsoLogger.ErrorCode.BusinessProcesssError, "Response from BPEL engine is empty");\r
217                                 msoLogger.recordAuditEvent (startTime, MsoLogger.StatusCode.ERROR, MsoLogger.ResponseCode.InternalError, "Response from BPEL engine is empty");\r
218                                 msoLogger.debug ("End of the transaction, the final response is: " + (String) resp.getEntity ());\r
219                                 return resp;\r
220                 }       \r
221         \r
222         }\r
223         \r
224         private static boolean empty(String s) {\r
225           return (s == null || s.trim().isEmpty());\r
226   }\r
227                 \r
228 }\r