Removed MsoLogger class
[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.ErrorCode;
58 import org.onap.so.logger.MessageEnum;
59
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     logger.info("{} {}", MessageEnum.APIH_GENERATED_REQUEST_ID.toString(), requestId);
101                 long startTime = System.currentTimeMillis ();
102                 logger.debug ("requestId is: {}", requestId);
103                 TasksRequest taskRequest = null;
104                 String apiVersion = version.substring(1);
105                 
106                 try{
107                         ObjectMapper mapper = new ObjectMapper();
108                         taskRequest= mapper.readValue(request, TasksRequest.class);
109                         
110                         if (taskRequest.getRequestDetails() == null) {
111                                 throw new ValidationException("requestDetails");                                
112                         }
113                         if (taskRequest.getRequestDetails().getRequestInfo() == null) {
114                                 throw new ValidationException("requestInfo");
115                         }
116                         if (empty(taskRequest.getRequestDetails().getRequestInfo().getSource())) {
117                                 throw new ValidationException("source");
118                         }
119                         if (empty(taskRequest.getRequestDetails().getRequestInfo().getRequestorId())) {
120                                 throw new ValidationException("requestorId");
121                         }
122
123                 }catch(IOException e){
124                         ErrorLoggerInfo errorLoggerInfo = new ErrorLoggerInfo.Builder(MessageEnum.APIH_REQUEST_VALIDATION_ERROR, ErrorCode.SchemaError).build();
125
126
127                         ValidateException validateException = new ValidateException.Builder("Mapping of request to JSON object failed: " + e.getMessage(),
128                                         HttpStatus.SC_BAD_REQUEST, ErrorNumbers.SVC_BAD_PARAMETER).cause(e).errorInfo(errorLoggerInfo).build();
129
130                         throw validateException;
131                 }
132                 catch(ValidationException e){
133                         ErrorLoggerInfo errorLoggerInfo = new ErrorLoggerInfo.Builder(MessageEnum.APIH_REQUEST_VALIDATION_ERROR, ErrorCode.SchemaError).errorSource(Constants.MSO_PROP_APIHANDLER_INFRA).build();
134
135
136                         ValidateException validateException = new ValidateException.Builder("Mapping of request to JSON Object failed. " + e.getMessage(),
137                                         HttpStatus.SC_BAD_REQUEST,ErrorNumbers.SVC_BAD_PARAMETER).errorInfo(errorLoggerInfo).build();
138                         throw validateException;
139
140                 }
141                 //Create Request Record
142                 InfraActiveRequests currentActiveReq = msoRequest.createRequestObject(taskRequest,Action.completeTask,requestId,Status.PENDING,request);
143                 
144                 // Transform the request to Camunda-style Complete request
145                 Variables variablesForComplete = new Variables();
146                 Value sourceValue = new Value(); 
147                 sourceValue.setValue(taskRequest.getRequestDetails().getRequestInfo().getSource());
148                 Value responseValue = new Value(); 
149                 responseValue.setValue(taskRequest.getRequestDetails().getRequestInfo().getResponseValue().name());
150                 Value requestorIdValue = new Value(); 
151                 requestorIdValue.setValue(taskRequest.getRequestDetails().getRequestInfo().getRequestorId());
152                 variablesForComplete.setSource(sourceValue);
153                 variablesForComplete.setResponseValue(responseValue);
154                 variablesForComplete.setRequestorId(requestorIdValue);
155                 
156                 String camundaJsonReq = null;
157                 try {
158                         ObjectMapper mapper = new ObjectMapper();
159                         mapper.configure(SerializationFeature.WRAP_ROOT_VALUE, true);
160                         camundaJsonReq = mapper.writeValueAsString(variablesForComplete);
161                 } catch(JsonProcessingException e){
162
163                         ErrorLoggerInfo errorLoggerInfo = new ErrorLoggerInfo.Builder(MessageEnum.APIH_GENERAL_EXCEPTION, ErrorCode.UnknownError).errorSource(Constants.MSO_PROP_APIHANDLER_INFRA).build();
164
165
166                         ValidateException validateException = new ValidateException.Builder("Mapping of JSON object to Camunda request failed",
167                                         HttpStatus.SC_INTERNAL_SERVER_ERROR,ErrorNumbers.SVC_GENERAL_SERVICE_ERROR).errorInfo(errorLoggerInfo).build();
168                         throw validateException;
169                 }
170                 
171                 RequestClient requestClient = null;
172                 HttpResponse response = null;
173                 long subStartTime = System.currentTimeMillis();
174                 String requestUrl = taskUri + "/" + taskId + "/complete";
175                 try {
176                         requestClient = reqClientFactory.getRequestClient (requestUrl);
177                         // Capture audit event
178                         
179                         response = requestClient.post(camundaJsonReq);
180
181                 } catch (Exception e) {
182
183             ErrorLoggerInfo errorLoggerInfo = new ErrorLoggerInfo.Builder(MessageEnum.APIH_BPEL_COMMUNICATE_ERROR, ErrorCode.AvailabilityError).errorSource(Constants.MSO_PROP_APIHANDLER_INFRA).build();
184
185
186
187             BPMNFailureException bpmnFailureException = new BPMNFailureException.Builder(String.valueOf(HttpStatus.SC_BAD_GATEWAY),
188                     HttpStatus.SC_BAD_GATEWAY,ErrorNumbers.SVC_NO_SERVER_RESOURCES).errorInfo(errorLoggerInfo).build();
189
190                     throw bpmnFailureException;
191                 }
192
193                 if (response == null) {
194             ErrorLoggerInfo errorLoggerInfo = new ErrorLoggerInfo.Builder(MessageEnum.APIH_BPEL_COMMUNICATE_ERROR, ErrorCode.BusinessProcesssError).errorSource(Constants.MSO_PROP_APIHANDLER_INFRA).build();
195
196
197             BPMNFailureException bpmnFailureException = new BPMNFailureException.Builder(String.valueOf(HttpStatus.SC_BAD_GATEWAY),
198                     HttpStatus.SC_BAD_GATEWAY,ErrorNumbers.SVC_NO_SERVER_RESOURCES).errorInfo(errorLoggerInfo).build();
199
200             throw bpmnFailureException;
201
202                 }
203
204                 ResponseHandler respHandler = new ResponseHandler (response, requestClient.getType ());
205                 int bpelStatus = respHandler.getStatus ();
206
207                 // BPEL accepted the request, the request is in progress
208                 if (bpelStatus == HttpStatus.SC_NO_CONTENT || bpelStatus == HttpStatus.SC_ACCEPTED) {                   
209                         logger.debug ("Received good response from Camunda");
210                         TaskRequestReference trr = new TaskRequestReference();
211                         trr.setTaskId(taskId);
212                         String completeResp = null;
213                         try {
214                                 ObjectMapper mapper = new ObjectMapper();
215                                 mapper.configure(SerializationFeature.WRAP_ROOT_VALUE, true);
216                                 completeResp = mapper.writeValueAsString(trr);
217                         }
218                         catch (JsonProcessingException e) {
219
220                 ErrorLoggerInfo errorLoggerInfo = new ErrorLoggerInfo.Builder(MessageEnum.APIH_BPEL_RESPONSE_ERROR, ErrorCode.BusinessProcesssError).build();
221
222
223                 ValidateException validateException = new ValidateException.Builder("Request Failed due to bad response format" ,
224                         bpelStatus,ErrorNumbers.SVC_DETAILED_SERVICE_ERROR).errorInfo(errorLoggerInfo).build();
225
226                 throw validateException;
227                         }
228                         logger.debug("Response to the caller: {}", completeResp);
229                         logger.debug ("End of the transaction, the final response is: {}", completeResp);
230                         return builder.buildResponse(HttpStatus.SC_ACCEPTED, requestId, completeResp, apiVersion);
231                 } else {
232             ErrorLoggerInfo errorLoggerInfo = new ErrorLoggerInfo.Builder(MessageEnum.APIH_BPEL_RESPONSE_ERROR, ErrorCode.BusinessProcesssError).build();
233
234
235             BPMNFailureException bpmnFailureException = new BPMNFailureException.Builder(String.valueOf(bpelStatus),
236                     bpelStatus,ErrorNumbers.SVC_DETAILED_SERVICE_ERROR).errorInfo(errorLoggerInfo).build();
237
238             throw bpmnFailureException;
239             
240                 }       
241         
242         }
243         
244         private static boolean empty(String s) {
245           return (s == null || s.trim().isEmpty());
246   }
247                 
248 }