Replaced all tabs with spaces in java and pom.xml
[so.git] / mso-api-handlers / mso-api-handler-infra / src / main / java / org / onap / so / apihandlerinfra / ManualTasks.java
1 /*-
2  * ============LICENSE_START=======================================================
3  * ONAP - SO
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  * Modifications Copyright (c) 2019 Samsung
9  * ================================================================================
10  * Licensed under the Apache License, Version 2.0 (the "License");
11  * you may not use this file except in compliance with the License.
12  * You may obtain a copy of the License at
13  * 
14  *      http://www.apache.org/licenses/LICENSE-2.0
15  * 
16  * Unless required by applicable law or agreed to in writing, software
17  * distributed under the License is distributed on an "AS IS" BASIS,
18  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
19  * See the License for the specific language governing permissions and
20  * limitations under the License.
21  * ============LICENSE_END=========================================================
22  */
23
24 package org.onap.so.apihandlerinfra;
25
26 import java.io.IOException;
27 import javax.transaction.Transactional;
28 import javax.ws.rs.Consumes;
29 import javax.ws.rs.POST;
30 import javax.ws.rs.Path;
31 import javax.ws.rs.PathParam;
32 import javax.ws.rs.Produces;
33 import javax.ws.rs.container.ContainerRequestContext;
34 import javax.ws.rs.core.Context;
35 import javax.ws.rs.core.MediaType;
36 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.ErrorLoggerInfo;
48 import org.onap.so.apihandlerinfra.tasksbeans.TaskRequestReference;
49 import org.onap.so.apihandlerinfra.tasksbeans.TasksRequest;
50 import org.onap.so.apihandlerinfra.tasksbeans.Value;
51 import org.onap.so.apihandlerinfra.tasksbeans.Variables;
52 import org.onap.so.db.request.beans.InfraActiveRequests;
53 import org.onap.so.exceptions.ValidationException;
54 import org.onap.so.logger.ErrorCode;
55 import org.onap.so.logger.MessageEnum;
56 import org.slf4j.Logger;
57 import org.slf4j.LoggerFactory;
58 import org.springframework.beans.factory.annotation.Autowired;
59 import org.springframework.stereotype.Component;
60 import com.fasterxml.jackson.core.JsonProcessingException;
61 import com.fasterxml.jackson.databind.ObjectMapper;
62 import com.fasterxml.jackson.databind.SerializationFeature;
63 import io.swagger.annotations.ApiOperation;
64
65
66 @Path("/tasks")
67 @Component
68 public class ManualTasks {
69     private static Logger logger = LoggerFactory.getLogger(ManualTasks.class);
70
71
72     @org.springframework.beans.factory.annotation.Value("${mso.camunda.rest.task.uri}")
73     private String taskUri;
74
75     @Autowired
76     private RequestClientFactory reqClientFactory;
77
78     @Autowired
79     private MsoRequest msoRequest;
80
81     @Autowired
82     private ResponseBuilder builder;
83
84     @POST
85     @Path("/{version:[vV]1}/{taskId}/complete")
86     @Consumes(MediaType.APPLICATION_JSON)
87     @Produces(MediaType.APPLICATION_JSON)
88     @ApiOperation(value = "Complete specified task", response = Response.class)
89     @Transactional
90     public Response completeTask(String request, @PathParam("version") String version,
91             @PathParam("taskId") String taskId, @Context ContainerRequestContext requestContext) throws ApiException {
92
93         String requestId = requestContext.getProperty("requestId").toString();
94         logger.info("{} {}", MessageEnum.APIH_GENERATED_REQUEST_ID.toString(), requestId);
95         long startTime = System.currentTimeMillis();
96         logger.debug("requestId is: {}", requestId);
97         TasksRequest taskRequest = null;
98         String apiVersion = version.substring(1);
99
100         try {
101             ObjectMapper mapper = new ObjectMapper();
102             taskRequest = mapper.readValue(request, TasksRequest.class);
103
104             if (taskRequest.getRequestDetails() == null) {
105                 throw new ValidationException("requestDetails");
106             }
107             if (taskRequest.getRequestDetails().getRequestInfo() == null) {
108                 throw new ValidationException("requestInfo");
109             }
110             if (empty(taskRequest.getRequestDetails().getRequestInfo().getSource())) {
111                 throw new ValidationException("source");
112             }
113             if (empty(taskRequest.getRequestDetails().getRequestInfo().getRequestorId())) {
114                 throw new ValidationException("requestorId");
115             }
116
117         } catch (IOException e) {
118             ErrorLoggerInfo errorLoggerInfo =
119                     new ErrorLoggerInfo.Builder(MessageEnum.APIH_REQUEST_VALIDATION_ERROR, ErrorCode.SchemaError)
120                             .build();
121
122
123             ValidateException validateException =
124                     new ValidateException.Builder("Mapping of request to JSON object failed: " + e.getMessage(),
125                             HttpStatus.SC_BAD_REQUEST, ErrorNumbers.SVC_BAD_PARAMETER).cause(e)
126                                     .errorInfo(errorLoggerInfo).build();
127
128             throw validateException;
129         } catch (ValidationException e) {
130             ErrorLoggerInfo errorLoggerInfo =
131                     new ErrorLoggerInfo.Builder(MessageEnum.APIH_REQUEST_VALIDATION_ERROR, ErrorCode.SchemaError)
132                             .errorSource(Constants.MSO_PROP_APIHANDLER_INFRA).build();
133
134
135             ValidateException validateException =
136                     new ValidateException.Builder("Mapping of request to JSON Object failed. " + e.getMessage(),
137                             HttpStatus.SC_BAD_REQUEST, ErrorNumbers.SVC_BAD_PARAMETER).errorInfo(errorLoggerInfo)
138                                     .build();
139             throw validateException;
140
141         }
142         // Create Request Record
143         InfraActiveRequests currentActiveReq =
144                 msoRequest.createRequestObject(taskRequest, Action.completeTask, requestId, Status.PENDING, request);
145
146         // Transform the request to Camunda-style Complete request
147         Variables variablesForComplete = new Variables();
148         Value sourceValue = new Value();
149         sourceValue.setValue(taskRequest.getRequestDetails().getRequestInfo().getSource());
150         Value responseValue = new Value();
151         responseValue.setValue(taskRequest.getRequestDetails().getRequestInfo().getResponseValue().name());
152         Value requestorIdValue = new Value();
153         requestorIdValue.setValue(taskRequest.getRequestDetails().getRequestInfo().getRequestorId());
154         variablesForComplete.setSource(sourceValue);
155         variablesForComplete.setResponseValue(responseValue);
156         variablesForComplete.setRequestorId(requestorIdValue);
157
158         String camundaJsonReq = null;
159         try {
160             ObjectMapper mapper = new ObjectMapper();
161             mapper.configure(SerializationFeature.WRAP_ROOT_VALUE, true);
162             camundaJsonReq = mapper.writeValueAsString(variablesForComplete);
163         } catch (JsonProcessingException e) {
164
165             ErrorLoggerInfo errorLoggerInfo =
166                     new ErrorLoggerInfo.Builder(MessageEnum.APIH_GENERAL_EXCEPTION, ErrorCode.UnknownError)
167                             .errorSource(Constants.MSO_PROP_APIHANDLER_INFRA).build();
168
169
170             ValidateException validateException =
171                     new ValidateException.Builder("Mapping of JSON object to Camunda request failed",
172                             HttpStatus.SC_INTERNAL_SERVER_ERROR, ErrorNumbers.SVC_GENERAL_SERVICE_ERROR)
173                                     .errorInfo(errorLoggerInfo).build();
174             throw validateException;
175         }
176
177         RequestClient requestClient = null;
178         HttpResponse response = null;
179         long subStartTime = System.currentTimeMillis();
180         String requestUrl = taskUri + "/" + taskId + "/complete";
181         try {
182             requestClient = reqClientFactory.getRequestClient(requestUrl);
183             // Capture audit event
184
185             response = requestClient.post(camundaJsonReq);
186
187         } catch (Exception e) {
188
189             ErrorLoggerInfo errorLoggerInfo =
190                     new ErrorLoggerInfo.Builder(MessageEnum.APIH_BPEL_COMMUNICATE_ERROR, ErrorCode.AvailabilityError)
191                             .errorSource(Constants.MSO_PROP_APIHANDLER_INFRA).build();
192
193
194
195             BPMNFailureException bpmnFailureException =
196                     new BPMNFailureException.Builder(String.valueOf(HttpStatus.SC_BAD_GATEWAY),
197                             HttpStatus.SC_BAD_GATEWAY, ErrorNumbers.SVC_NO_SERVER_RESOURCES).errorInfo(errorLoggerInfo)
198                                     .build();
199
200             throw bpmnFailureException;
201         }
202
203         if (response == null) {
204             ErrorLoggerInfo errorLoggerInfo = new ErrorLoggerInfo.Builder(MessageEnum.APIH_BPEL_COMMUNICATE_ERROR,
205                     ErrorCode.BusinessProcesssError).errorSource(Constants.MSO_PROP_APIHANDLER_INFRA).build();
206
207
208             BPMNFailureException bpmnFailureException =
209                     new BPMNFailureException.Builder(String.valueOf(HttpStatus.SC_BAD_GATEWAY),
210                             HttpStatus.SC_BAD_GATEWAY, ErrorNumbers.SVC_NO_SERVER_RESOURCES).errorInfo(errorLoggerInfo)
211                                     .build();
212
213             throw bpmnFailureException;
214
215         }
216
217         ResponseHandler respHandler = new ResponseHandler(response, requestClient.getType());
218         int bpelStatus = respHandler.getStatus();
219
220         // BPEL accepted the request, the request is in progress
221         if (bpelStatus == HttpStatus.SC_NO_CONTENT || bpelStatus == HttpStatus.SC_ACCEPTED) {
222             logger.debug("Received good response from Camunda");
223             TaskRequestReference trr = new TaskRequestReference();
224             trr.setTaskId(taskId);
225             String completeResp = null;
226             try {
227                 ObjectMapper mapper = new ObjectMapper();
228                 mapper.configure(SerializationFeature.WRAP_ROOT_VALUE, true);
229                 completeResp = mapper.writeValueAsString(trr);
230             } catch (JsonProcessingException e) {
231
232                 ErrorLoggerInfo errorLoggerInfo = new ErrorLoggerInfo.Builder(MessageEnum.APIH_BPEL_RESPONSE_ERROR,
233                         ErrorCode.BusinessProcesssError).build();
234
235
236                 ValidateException validateException =
237                         new ValidateException.Builder("Request Failed due to bad response format", bpelStatus,
238                                 ErrorNumbers.SVC_DETAILED_SERVICE_ERROR).errorInfo(errorLoggerInfo).build();
239
240                 throw validateException;
241             }
242             logger.debug("Response to the caller: {}", completeResp);
243             logger.debug("End of the transaction, the final response is: {}", completeResp);
244             return builder.buildResponse(HttpStatus.SC_ACCEPTED, requestId, completeResp, apiVersion);
245         } else {
246             ErrorLoggerInfo errorLoggerInfo =
247                     new ErrorLoggerInfo.Builder(MessageEnum.APIH_BPEL_RESPONSE_ERROR, ErrorCode.BusinessProcesssError)
248                             .build();
249
250
251             BPMNFailureException bpmnFailureException = new BPMNFailureException.Builder(String.valueOf(bpelStatus),
252                     bpelStatus, ErrorNumbers.SVC_DETAILED_SERVICE_ERROR).errorInfo(errorLoggerInfo).build();
253
254             throw bpmnFailureException;
255
256         }
257
258     }
259
260     private static boolean empty(String s) {
261         return (s == null || s.trim().isEmpty());
262     }
263
264 }