2  * ============LICENSE_START=======================================================
\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 
  12  *      http://www.apache.org/licenses/LICENSE-2.0
\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 
  21 package org.openecomp.mso.apihandlerinfra;
\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 
  28 import com.wordnik.swagger.annotations.ApiOperation;
\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 
  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 
  47 import org.codehaus.jackson.map.ObjectMapper;
\r 
  48 import org.codehaus.jackson.map.SerializationConfig;
\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 
  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 
  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 
  69                 MsoRequest msoRequest = new MsoRequest (requestId);
\r 
  72                         ObjectMapper mapper = new ObjectMapper();
\r 
  73                         tr= mapper.readValue(request, TasksRequest.class);
\r 
  75                         if (tr.getRequestDetails() == null) {
\r 
  76                                 throw new ValidationException("requestDetails");                                
\r 
  78                         if (tr.getRequestDetails().getRequestInfo() == null) {
\r 
  79                                 throw new ValidationException("requestInfo");
\r 
  81                         if (empty(tr.getRequestDetails().getRequestInfo().getSource())) {
\r 
  82                                 throw new ValidationException("source");
\r 
  84                         if (empty(tr.getRequestDetails().getRequestInfo().getRequestorId())) {
\r 
  85                                 throw new ValidationException("requestorId");
\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 
  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 
 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 
 112                 String camundaJsonReq = null;
\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 
 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 
 130                 RequestClient requestClient = null;
\r 
 131                 HttpResponse response = null;
\r 
 132                 long subStartTime = System.currentTimeMillis();
\r 
 133                 String requestUrl = "/mso/task/" + taskId + "/complete";
\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 
 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 
 142                         response = requestClient.post(camundaJsonReq);
\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.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 
 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, 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 
 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 
 170                         msoRequest.updateFinalStatus (Status.FAILED);
\r 
 171                         msoLogger.error (MessageEnum.APIH_BPEL_COMMUNICATE_ERROR, 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 
 177                 ResponseHandler respHandler = new ResponseHandler (response, requestClient.getType ());
\r 
 178                 int bpelStatus = respHandler.getStatus ();
\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 
 189                                 ObjectMapper mapper = new ObjectMapper();
\r 
 190                                 mapper.configure(SerializationConfig.Feature.WRAP_ROOT_VALUE, true);
\r 
 191                                 completeResp = mapper.writeValueAsString(trr);
\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 
 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 
 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 
 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 
 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 
 223         private static boolean empty(String s) {
\r 
 224           return (s == null || s.trim().isEmpty());
\r