Containerization feature of SO
[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  * 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
11  * 
12  *      http://www.apache.org/licenses/LICENSE-2.0
13  * 
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=========================================================
20  */
21
22 package org.onap.so.apihandlerinfra;
23
24 import java.io.IOException;
25
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;
36
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;
60
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;
65
66
67 @Path("/tasks")
68 @Component
69 public class ManualTasks {
70         private static MsoLogger msoLogger = MsoLogger.getMsoLogger (MsoLogger.Catalog.APIH, ManualTasks.class);
71         private static MsoAlarmLogger alarmLogger = new MsoAlarmLogger ();
72         
73         @org.springframework.beans.factory.annotation.Value("${mso.camunda.rest.task.uri}")
74         private String taskUri;
75     
76         @Autowired
77         private RequestClientFactory reqClientFactory;
78         
79         @Autowired
80         private MsoRequest msoRequest;
81         
82         @Autowired
83         private ResponseBuilder builder;
84         
85         @POST
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)
90         @Transactional
91         public Response completeTask(String request, @PathParam("version") String version, @PathParam("taskId") String taskId,
92                                                                 @Context ContainerRequestContext requestContext) throws ApiException {
93                 
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);
101                 
102                 try{
103                         ObjectMapper mapper = new ObjectMapper();
104                         taskRequest= mapper.readValue(request, TasksRequest.class);
105                         
106                         if (taskRequest.getRequestDetails() == null) {
107                                 throw new ValidationException("requestDetails");                                
108                         }
109                         if (taskRequest.getRequestDetails().getRequestInfo() == null) {
110                                 throw new ValidationException("requestInfo");
111                         }
112                         if (empty(taskRequest.getRequestDetails().getRequestInfo().getSource())) {
113                                 throw new ValidationException("source");
114                         }
115                         if (empty(taskRequest.getRequestDetails().getRequestInfo().getRequestorId())) {
116                                 throw new ValidationException("requestorId");
117                         }
118
119                 }catch(IOException e){
120                         ErrorLoggerInfo errorLoggerInfo = new ErrorLoggerInfo.Builder(MessageEnum.APIH_REQUEST_VALIDATION_ERROR, MsoLogger.ErrorCode.SchemaError).build();
121
122
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();
125
126                         throw validateException;
127                 }
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();
130
131
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;
135
136                 }
137                 //Create Request Record
138                 InfraActiveRequests currentActiveReq = msoRequest.createRequestObject(taskRequest,Action.completeTask,requestId,Status.PENDING,request);
139                 
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);
151                 
152                 String camundaJsonReq = null;
153                 try {
154                         ObjectMapper mapper = new ObjectMapper();
155                         mapper.configure(SerializationFeature.WRAP_ROOT_VALUE, true);
156                         camundaJsonReq = mapper.writeValueAsString(variablesForComplete);
157                 } catch(JsonProcessingException e){
158
159                         ErrorLoggerInfo errorLoggerInfo = new ErrorLoggerInfo.Builder(MessageEnum.APIH_GENERAL_EXCEPTION, MsoLogger.ErrorCode.UnknownError).errorSource(Constants.MSO_PROP_APIHANDLER_INFRA).build();
160
161
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;
165                 }
166                 
167                 RequestClient requestClient = null;
168                 HttpResponse response = null;
169                 long subStartTime = System.currentTimeMillis();
170                 String requestUrl = taskUri + "/" + taskId + "/complete";
171                 try {
172                         requestClient = reqClientFactory.getRequestClient (requestUrl);
173                         // Capture audit event
174                         
175                         response = requestClient.post(camundaJsonReq);
176
177                 } catch (Exception e) {
178
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();
181
182
183
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();
186
187                     throw bpmnFailureException;
188                 }
189
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();
192
193
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();
196
197             throw bpmnFailureException;
198
199                 }
200
201                 ResponseHandler respHandler = new ResponseHandler (response, requestClient.getType ());
202                 int bpelStatus = respHandler.getStatus ();
203
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");
207                 
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;
212                         try {
213                                 ObjectMapper mapper = new ObjectMapper();
214                                 mapper.configure(SerializationFeature.WRAP_ROOT_VALUE, true);
215                                 completeResp = mapper.writeValueAsString(trr);
216                         }
217                         catch (JsonProcessingException e) {
218
219                 ErrorLoggerInfo errorLoggerInfo = new ErrorLoggerInfo.Builder(MessageEnum.APIH_BPEL_RESPONSE_ERROR, MsoLogger.ErrorCode.BusinessProcesssError).build();
220
221
222                 ValidateException validateException = new ValidateException.Builder("Request Failed due to bad response format" ,
223                         bpelStatus,ErrorNumbers.SVC_DETAILED_SERVICE_ERROR).errorInfo(errorLoggerInfo).build();
224
225                 throw validateException;
226                         }
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);
230                 } else {
231             ErrorLoggerInfo errorLoggerInfo = new ErrorLoggerInfo.Builder(MessageEnum.APIH_BPEL_RESPONSE_ERROR, MsoLogger.ErrorCode.BusinessProcesssError).build();
232
233
234             BPMNFailureException bpmnFailureException = new BPMNFailureException.Builder(String.valueOf(bpelStatus),
235                     bpelStatus,ErrorNumbers.SVC_DETAILED_SERVICE_ERROR).errorInfo(errorLoggerInfo).build();
236
237             throw bpmnFailureException;
238             
239                 }       
240         
241         }
242         
243         private static boolean empty(String s) {
244           return (s == null || s.trim().isEmpty());
245   }
246                 
247 }