d686e8035261e3a20a6f14a34499c347de82f06d
[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
28 import javax.transaction.Transactional;
29 import javax.ws.rs.Consumes;
30 import javax.ws.rs.POST;
31 import javax.ws.rs.Path;
32 import javax.ws.rs.PathParam;
33 import javax.ws.rs.Produces;
34 import javax.ws.rs.container.ContainerRequestContext;
35 import javax.ws.rs.core.Context;
36 import javax.ws.rs.core.MediaType;
37 import javax.ws.rs.core.Response;
38
39 import org.apache.http.HttpResponse;
40 import org.apache.http.HttpStatus;
41 import org.onap.so.apihandler.common.ErrorNumbers;
42 import org.onap.so.apihandler.common.RequestClient;
43 import org.onap.so.apihandler.common.RequestClientFactory;
44 import org.onap.so.apihandler.common.ResponseBuilder;
45 import org.onap.so.apihandler.common.ResponseHandler;
46 import org.onap.so.apihandlerinfra.exceptions.ApiException;
47 import org.onap.so.apihandlerinfra.exceptions.BPMNFailureException;
48 import org.onap.so.apihandlerinfra.exceptions.ValidateException;
49
50 import org.onap.so.apihandlerinfra.logging.ErrorLoggerInfo;
51 import org.onap.so.apihandlerinfra.tasksbeans.TaskRequestReference;
52 import org.onap.so.apihandlerinfra.tasksbeans.TasksRequest;
53 import org.onap.so.apihandlerinfra.tasksbeans.Value;
54 import org.onap.so.apihandlerinfra.tasksbeans.Variables;
55 import org.onap.so.db.request.beans.InfraActiveRequests;
56 import org.onap.so.exceptions.ValidationException;
57 import org.onap.so.logger.MessageEnum;
58
59 import org.onap.so.logger.MsoLogger;
60 import org.slf4j.Logger;
61 import org.slf4j.LoggerFactory;
62 import org.springframework.beans.factory.annotation.Autowired;
63 import org.springframework.stereotype.Component;
64
65 import com.fasterxml.jackson.core.JsonProcessingException;
66 import com.fasterxml.jackson.databind.ObjectMapper;
67 import com.fasterxml.jackson.databind.SerializationFeature;
68
69 import io.swagger.annotations.ApiOperation;
70
71
72 @Path("/tasks")
73 @Component
74 public class ManualTasks {
75         private static Logger logger = LoggerFactory.getLogger(ManualTasks.class);
76
77         
78         @org.springframework.beans.factory.annotation.Value("${mso.camunda.rest.task.uri}")
79         private String taskUri;
80     
81         @Autowired
82         private RequestClientFactory reqClientFactory;
83         
84         @Autowired
85         private MsoRequest msoRequest;
86         
87         @Autowired
88         private ResponseBuilder builder;
89         
90         @POST
91         @Path("/{version:[vV]1}/{taskId}/complete")
92         @Consumes(MediaType.APPLICATION_JSON)
93         @Produces(MediaType.APPLICATION_JSON)
94         @ApiOperation(value="Complete specified task",response=Response.class)
95         @Transactional
96         public Response completeTask(String request, @PathParam("version") String version, @PathParam("taskId") String taskId,
97                                                                 @Context ContainerRequestContext requestContext) throws ApiException {
98                 
99                 String requestId = requestContext.getProperty("requestId").toString();
100         MsoLogger.setLogContext(requestId, null);
101         logger.info("{} {}", MessageEnum.APIH_GENERATED_REQUEST_ID.toString(), requestId);
102                 long startTime = System.currentTimeMillis ();
103                 logger.debug ("requestId is: {}", requestId);
104                 TasksRequest taskRequest = null;
105                 String apiVersion = version.substring(1);
106                 
107                 try{
108                         ObjectMapper mapper = new ObjectMapper();
109                         taskRequest= mapper.readValue(request, TasksRequest.class);
110                         
111                         if (taskRequest.getRequestDetails() == null) {
112                                 throw new ValidationException("requestDetails");                                
113                         }
114                         if (taskRequest.getRequestDetails().getRequestInfo() == null) {
115                                 throw new ValidationException("requestInfo");
116                         }
117                         if (empty(taskRequest.getRequestDetails().getRequestInfo().getSource())) {
118                                 throw new ValidationException("source");
119                         }
120                         if (empty(taskRequest.getRequestDetails().getRequestInfo().getRequestorId())) {
121                                 throw new ValidationException("requestorId");
122                         }
123
124                 }catch(IOException e){
125                         ErrorLoggerInfo errorLoggerInfo = new ErrorLoggerInfo.Builder(MessageEnum.APIH_REQUEST_VALIDATION_ERROR, MsoLogger.ErrorCode.SchemaError).build();
126
127
128                         ValidateException validateException = new ValidateException.Builder("Mapping of request to JSON object failed: " + e.getMessage(),
129                                         HttpStatus.SC_BAD_REQUEST, ErrorNumbers.SVC_BAD_PARAMETER).cause(e).errorInfo(errorLoggerInfo).build();
130
131                         throw validateException;
132                 }
133                 catch(ValidationException e){
134                         ErrorLoggerInfo errorLoggerInfo = new ErrorLoggerInfo.Builder(MessageEnum.APIH_REQUEST_VALIDATION_ERROR, MsoLogger.ErrorCode.SchemaError).errorSource(Constants.MSO_PROP_APIHANDLER_INFRA).build();
135
136
137                         ValidateException validateException = new ValidateException.Builder("Mapping of request to JSON Object failed. " + e.getMessage(),
138                                         HttpStatus.SC_BAD_REQUEST,ErrorNumbers.SVC_BAD_PARAMETER).errorInfo(errorLoggerInfo).build();
139                         throw validateException;
140
141                 }
142                 //Create Request Record
143                 InfraActiveRequests currentActiveReq = msoRequest.createRequestObject(taskRequest,Action.completeTask,requestId,Status.PENDING,request);
144                 
145                 // Transform the request to Camunda-style Complete request
146                 Variables variablesForComplete = new Variables();
147                 Value sourceValue = new Value(); 
148                 sourceValue.setValue(taskRequest.getRequestDetails().getRequestInfo().getSource());
149                 Value responseValue = new Value(); 
150                 responseValue.setValue(taskRequest.getRequestDetails().getRequestInfo().getResponseValue().name());
151                 Value requestorIdValue = new Value(); 
152                 requestorIdValue.setValue(taskRequest.getRequestDetails().getRequestInfo().getRequestorId());
153                 variablesForComplete.setSource(sourceValue);
154                 variablesForComplete.setResponseValue(responseValue);
155                 variablesForComplete.setRequestorId(requestorIdValue);
156                 
157                 String camundaJsonReq = null;
158                 try {
159                         ObjectMapper mapper = new ObjectMapper();
160                         mapper.configure(SerializationFeature.WRAP_ROOT_VALUE, true);
161                         camundaJsonReq = mapper.writeValueAsString(variablesForComplete);
162                 } catch(JsonProcessingException e){
163
164                         ErrorLoggerInfo errorLoggerInfo = new ErrorLoggerInfo.Builder(MessageEnum.APIH_GENERAL_EXCEPTION, MsoLogger.ErrorCode.UnknownError).errorSource(Constants.MSO_PROP_APIHANDLER_INFRA).build();
165
166
167                         ValidateException validateException = new ValidateException.Builder("Mapping of JSON object to Camunda request failed",
168                                         HttpStatus.SC_INTERNAL_SERVER_ERROR,ErrorNumbers.SVC_GENERAL_SERVICE_ERROR).errorInfo(errorLoggerInfo).build();
169                         throw validateException;
170                 }
171                 
172                 RequestClient requestClient = null;
173                 HttpResponse response = null;
174                 long subStartTime = System.currentTimeMillis();
175                 String requestUrl = taskUri + "/" + taskId + "/complete";
176                 try {
177                         requestClient = reqClientFactory.getRequestClient (requestUrl);
178                         // Capture audit event
179                         
180                         response = requestClient.post(camundaJsonReq);
181
182                 } catch (Exception e) {
183
184             ErrorLoggerInfo errorLoggerInfo = new ErrorLoggerInfo.Builder(MessageEnum.APIH_BPEL_COMMUNICATE_ERROR, MsoLogger.ErrorCode.AvailabilityError).errorSource(Constants.MSO_PROP_APIHANDLER_INFRA).build();
185
186
187
188             BPMNFailureException bpmnFailureException = new BPMNFailureException.Builder(String.valueOf(HttpStatus.SC_BAD_GATEWAY),
189                     HttpStatus.SC_BAD_GATEWAY,ErrorNumbers.SVC_NO_SERVER_RESOURCES).errorInfo(errorLoggerInfo).build();
190
191                     throw bpmnFailureException;
192                 }
193
194                 if (response == null) {
195             ErrorLoggerInfo errorLoggerInfo = new ErrorLoggerInfo.Builder(MessageEnum.APIH_BPEL_COMMUNICATE_ERROR, MsoLogger.ErrorCode.BusinessProcesssError).errorSource(Constants.MSO_PROP_APIHANDLER_INFRA).build();
196
197
198             BPMNFailureException bpmnFailureException = new BPMNFailureException.Builder(String.valueOf(HttpStatus.SC_BAD_GATEWAY),
199                     HttpStatus.SC_BAD_GATEWAY,ErrorNumbers.SVC_NO_SERVER_RESOURCES).errorInfo(errorLoggerInfo).build();
200
201             throw bpmnFailureException;
202
203                 }
204
205                 ResponseHandler respHandler = new ResponseHandler (response, requestClient.getType ());
206                 int bpelStatus = respHandler.getStatus ();
207
208                 // BPEL accepted the request, the request is in progress
209                 if (bpelStatus == HttpStatus.SC_NO_CONTENT || bpelStatus == HttpStatus.SC_ACCEPTED) {                   
210                         logger.debug ("Received good response from Camunda");
211                         TaskRequestReference trr = new TaskRequestReference();
212                         trr.setTaskId(taskId);
213                         String completeResp = null;
214                         try {
215                                 ObjectMapper mapper = new ObjectMapper();
216                                 mapper.configure(SerializationFeature.WRAP_ROOT_VALUE, true);
217                                 completeResp = mapper.writeValueAsString(trr);
218                         }
219                         catch (JsonProcessingException e) {
220
221                 ErrorLoggerInfo errorLoggerInfo = new ErrorLoggerInfo.Builder(MessageEnum.APIH_BPEL_RESPONSE_ERROR, MsoLogger.ErrorCode.BusinessProcesssError).build();
222
223
224                 ValidateException validateException = new ValidateException.Builder("Request Failed due to bad response format" ,
225                         bpelStatus,ErrorNumbers.SVC_DETAILED_SERVICE_ERROR).errorInfo(errorLoggerInfo).build();
226
227                 throw validateException;
228                         }
229                         logger.debug("Response to the caller: {}", completeResp);
230                         logger.debug ("End of the transaction, the final response is: {}", completeResp);
231                         return builder.buildResponse(HttpStatus.SC_ACCEPTED, requestId, completeResp, apiVersion);
232                 } else {
233             ErrorLoggerInfo errorLoggerInfo = new ErrorLoggerInfo.Builder(MessageEnum.APIH_BPEL_RESPONSE_ERROR, MsoLogger.ErrorCode.BusinessProcesssError).build();
234
235
236             BPMNFailureException bpmnFailureException = new BPMNFailureException.Builder(String.valueOf(bpelStatus),
237                     bpelStatus,ErrorNumbers.SVC_DETAILED_SERVICE_ERROR).errorInfo(errorLoggerInfo).build();
238
239             throw bpmnFailureException;
240             
241                 }       
242         
243         }
244         
245         private static boolean empty(String s) {
246           return (s == null || s.trim().isEmpty());
247   }
248                 
249 }