2 * ============LICENSE_START=======================================================
4 * ================================================================================
5 * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved.
6 * Copyright (C) 2017 Huawei Technologies Co., Ltd. All rights reserved.
7 * ================================================================================
8 * Licensed under the Apache License, Version 2.0 (the "License");
9 * you may not use this file except in compliance with the License.
10 * You may obtain a copy of the License at
12 * http://www.apache.org/licenses/LICENSE-2.0
14 * Unless required by applicable law or agreed to in writing, software
15 * distributed under the License is distributed on an "AS IS" BASIS,
16 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
17 * See the License for the specific language governing permissions and
18 * limitations under the License.
19 * ============LICENSE_END=========================================================
22 package org.onap.so.apihandlerinfra;
24 import java.io.IOException;
26 import javax.transaction.Transactional;
27 import javax.ws.rs.Consumes;
28 import javax.ws.rs.POST;
29 import javax.ws.rs.Path;
30 import javax.ws.rs.PathParam;
31 import javax.ws.rs.Produces;
32 import javax.ws.rs.container.ContainerRequestContext;
33 import javax.ws.rs.core.Context;
34 import javax.ws.rs.core.MediaType;
35 import javax.ws.rs.core.Response;
37 import org.apache.http.HttpResponse;
38 import org.apache.http.HttpStatus;
39 import org.onap.so.apihandler.common.ErrorNumbers;
40 import org.onap.so.apihandler.common.RequestClient;
41 import org.onap.so.apihandler.common.RequestClientFactory;
42 import org.onap.so.apihandler.common.ResponseBuilder;
43 import org.onap.so.apihandler.common.ResponseHandler;
44 import org.onap.so.apihandlerinfra.exceptions.ApiException;
45 import org.onap.so.apihandlerinfra.exceptions.BPMNFailureException;
46 import org.onap.so.apihandlerinfra.exceptions.ValidateException;
47 import org.onap.so.apihandlerinfra.logging.AlarmLoggerInfo;
48 import org.onap.so.apihandlerinfra.logging.ErrorLoggerInfo;
49 import org.onap.so.apihandlerinfra.tasksbeans.TaskRequestReference;
50 import org.onap.so.apihandlerinfra.tasksbeans.TasksRequest;
51 import org.onap.so.apihandlerinfra.tasksbeans.Value;
52 import org.onap.so.apihandlerinfra.tasksbeans.Variables;
53 import org.onap.so.db.request.beans.InfraActiveRequests;
54 import org.onap.so.exceptions.ValidationException;
55 import org.onap.so.logger.MessageEnum;
56 import org.onap.so.logger.MsoAlarmLogger;
57 import org.onap.so.logger.MsoLogger;
58 import org.springframework.beans.factory.annotation.Autowired;
59 import org.springframework.stereotype.Component;
61 import com.fasterxml.jackson.core.JsonProcessingException;
62 import com.fasterxml.jackson.databind.ObjectMapper;
63 import com.fasterxml.jackson.databind.SerializationFeature;
64 import com.wordnik.swagger.annotations.ApiOperation;
69 public class ManualTasks {
70 private static MsoLogger msoLogger = MsoLogger.getMsoLogger (MsoLogger.Catalog.APIH, ManualTasks.class);
71 private static MsoAlarmLogger alarmLogger = new MsoAlarmLogger ();
73 @org.springframework.beans.factory.annotation.Value("${mso.camunda.rest.task.uri}")
74 private String taskUri;
77 private RequestClientFactory reqClientFactory;
80 private MsoRequest msoRequest;
83 private ResponseBuilder builder;
86 @Path("/{version:[vV]1}/{taskId}/complete")
87 @Consumes(MediaType.APPLICATION_JSON)
88 @Produces(MediaType.APPLICATION_JSON)
89 @ApiOperation(value="Complete specified task",response=Response.class)
91 public Response completeTask(String request, @PathParam("version") String version, @PathParam("taskId") String taskId,
92 @Context ContainerRequestContext requestContext) throws ApiException {
94 String requestId = requestContext.getProperty("requestId").toString();
95 MsoLogger.setLogContext(requestId, null);
96 msoLogger.info(MessageEnum.APIH_GENERATED_REQUEST_ID, requestId, "", "");
97 long startTime = System.currentTimeMillis ();
98 msoLogger.debug ("requestId is: " + requestId);
99 TasksRequest taskRequest = null;
100 String apiVersion = version.substring(1);
103 ObjectMapper mapper = new ObjectMapper();
104 taskRequest= mapper.readValue(request, TasksRequest.class);
106 if (taskRequest.getRequestDetails() == null) {
107 throw new ValidationException("requestDetails");
109 if (taskRequest.getRequestDetails().getRequestInfo() == null) {
110 throw new ValidationException("requestInfo");
112 if (empty(taskRequest.getRequestDetails().getRequestInfo().getSource())) {
113 throw new ValidationException("source");
115 if (empty(taskRequest.getRequestDetails().getRequestInfo().getRequestorId())) {
116 throw new ValidationException("requestorId");
119 }catch(IOException e){
120 ErrorLoggerInfo errorLoggerInfo = new ErrorLoggerInfo.Builder(MessageEnum.APIH_REQUEST_VALIDATION_ERROR, MsoLogger.ErrorCode.SchemaError).build();
123 ValidateException validateException = new ValidateException.Builder("Mapping of request to JSON object failed: " + e.getMessage(),
124 HttpStatus.SC_BAD_REQUEST, ErrorNumbers.SVC_BAD_PARAMETER).cause(e).errorInfo(errorLoggerInfo).build();
126 throw validateException;
128 catch(ValidationException e){
129 ErrorLoggerInfo errorLoggerInfo = new ErrorLoggerInfo.Builder(MessageEnum.APIH_REQUEST_VALIDATION_ERROR, MsoLogger.ErrorCode.SchemaError).errorSource(Constants.MSO_PROP_APIHANDLER_INFRA).build();
132 ValidateException validateException = new ValidateException.Builder("Mapping of request to JSON Object failed. " + e.getMessage(),
133 HttpStatus.SC_BAD_REQUEST,ErrorNumbers.SVC_BAD_PARAMETER).errorInfo(errorLoggerInfo).build();
134 throw validateException;
137 //Create Request Record
138 InfraActiveRequests currentActiveReq = msoRequest.createRequestObject(taskRequest,Action.completeTask,requestId,Status.PENDING,request);
140 // Transform the request to Camunda-style Complete request
141 Variables variablesForComplete = new Variables();
142 Value sourceValue = new Value();
143 sourceValue.setValue(taskRequest.getRequestDetails().getRequestInfo().getSource());
144 Value responseValue = new Value();
145 responseValue.setValue(taskRequest.getRequestDetails().getRequestInfo().getResponseValue().name());
146 Value requestorIdValue = new Value();
147 requestorIdValue.setValue(taskRequest.getRequestDetails().getRequestInfo().getRequestorId());
148 variablesForComplete.setSource(sourceValue);
149 variablesForComplete.setResponseValue(responseValue);
150 variablesForComplete.setRequestorId(requestorIdValue);
152 String camundaJsonReq = null;
154 ObjectMapper mapper = new ObjectMapper();
155 mapper.configure(SerializationFeature.WRAP_ROOT_VALUE, true);
156 camundaJsonReq = mapper.writeValueAsString(variablesForComplete);
157 } catch(JsonProcessingException e){
159 ErrorLoggerInfo errorLoggerInfo = new ErrorLoggerInfo.Builder(MessageEnum.APIH_GENERAL_EXCEPTION, MsoLogger.ErrorCode.UnknownError).errorSource(Constants.MSO_PROP_APIHANDLER_INFRA).build();
162 ValidateException validateException = new ValidateException.Builder("Mapping of JSON object to Camunda request failed",
163 HttpStatus.SC_INTERNAL_SERVER_ERROR,ErrorNumbers.SVC_GENERAL_SERVICE_ERROR).errorInfo(errorLoggerInfo).build();
164 throw validateException;
167 RequestClient requestClient = null;
168 HttpResponse response = null;
169 long subStartTime = System.currentTimeMillis();
170 String requestUrl = taskUri + "/" + taskId + "/complete";
172 requestClient = reqClientFactory.getRequestClient (requestUrl);
173 // Capture audit event
175 response = requestClient.post(camundaJsonReq);
177 } catch (Exception e) {
179 ErrorLoggerInfo errorLoggerInfo = new ErrorLoggerInfo.Builder(MessageEnum.APIH_BPEL_COMMUNICATE_ERROR, MsoLogger.ErrorCode.AvailabilityError).errorSource(Constants.MSO_PROP_APIHANDLER_INFRA).build();
180 AlarmLoggerInfo alarmLoggerInfo = new AlarmLoggerInfo.Builder("MsoConfigurationError", MsoAlarmLogger.CRITICAL, Messages.errors.get (ErrorNumbers.NO_COMMUNICATION_TO_BPEL)).build();
184 BPMNFailureException bpmnFailureException = new BPMNFailureException.Builder(String.valueOf(HttpStatus.SC_BAD_GATEWAY),
185 HttpStatus.SC_BAD_GATEWAY,ErrorNumbers.SVC_NO_SERVER_RESOURCES).errorInfo(errorLoggerInfo).alarmInfo(alarmLoggerInfo).build();
187 throw bpmnFailureException;
190 if (response == null) {
191 ErrorLoggerInfo errorLoggerInfo = new ErrorLoggerInfo.Builder(MessageEnum.APIH_BPEL_COMMUNICATE_ERROR, MsoLogger.ErrorCode.BusinessProcesssError).errorSource(Constants.MSO_PROP_APIHANDLER_INFRA).build();
194 BPMNFailureException bpmnFailureException = new BPMNFailureException.Builder(String.valueOf(HttpStatus.SC_BAD_GATEWAY),
195 HttpStatus.SC_BAD_GATEWAY,ErrorNumbers.SVC_NO_SERVER_RESOURCES).errorInfo(errorLoggerInfo).build();
197 throw bpmnFailureException;
201 ResponseHandler respHandler = new ResponseHandler (response, requestClient.getType ());
202 int bpelStatus = respHandler.getStatus ();
204 // BPEL accepted the request, the request is in progress
205 if (bpelStatus == HttpStatus.SC_NO_CONTENT || bpelStatus == HttpStatus.SC_ACCEPTED) {
206 msoLogger.debug ("Received good response from Camunda");
208 msoLogger.recordAuditEvent (startTime, MsoLogger.StatusCode.COMPLETE, MsoLogger.ResponseCode.Suc, "BPMN completed the request");
209 TaskRequestReference trr = new TaskRequestReference();
210 trr.setTaskId(taskId);
211 String completeResp = null;
213 ObjectMapper mapper = new ObjectMapper();
214 mapper.configure(SerializationFeature.WRAP_ROOT_VALUE, true);
215 completeResp = mapper.writeValueAsString(trr);
217 catch (JsonProcessingException e) {
219 ErrorLoggerInfo errorLoggerInfo = new ErrorLoggerInfo.Builder(MessageEnum.APIH_BPEL_RESPONSE_ERROR, MsoLogger.ErrorCode.BusinessProcesssError).build();
222 ValidateException validateException = new ValidateException.Builder("Request Failed due to bad response format" ,
223 bpelStatus,ErrorNumbers.SVC_DETAILED_SERVICE_ERROR).errorInfo(errorLoggerInfo).build();
225 throw validateException;
227 msoLogger.debug("Response to the caller: " + completeResp);
228 msoLogger.debug ("End of the transaction, the final response is: " + (String) completeResp);
229 return builder.buildResponse(HttpStatus.SC_ACCEPTED, requestId, completeResp, apiVersion);
231 ErrorLoggerInfo errorLoggerInfo = new ErrorLoggerInfo.Builder(MessageEnum.APIH_BPEL_RESPONSE_ERROR, MsoLogger.ErrorCode.BusinessProcesssError).build();
234 BPMNFailureException bpmnFailureException = new BPMNFailureException.Builder(String.valueOf(bpelStatus),
235 bpelStatus,ErrorNumbers.SVC_DETAILED_SERVICE_ERROR).errorInfo(errorLoggerInfo).build();
237 throw bpmnFailureException;
243 private static boolean empty(String s) {
244 return (s == null || s.trim().isEmpty());