Remove all usage of AlarmLogger
[so.git] / mso-api-handlers / mso-api-handler-infra / src / main / java / org / onap / so / apihandlerinfra / TasksHandler.java
1 /*-
2  * ============LICENSE_START=======================================================
3  * ONAP - SO
4  * ================================================================================
5  * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved.
6  * ================================================================================
7  * Licensed under the Apache License, Version 2.0 (the "License");
8  * you may not use this file except in compliance with the License.
9  * You may obtain a copy of the License at
10  * 
11  *      http://www.apache.org/licenses/LICENSE-2.0
12  * 
13  * Unless required by applicable law or agreed to in writing, software
14  * distributed under the License is distributed on an "AS IS" BASIS,
15  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
16  * See the License for the specific language governing permissions and
17  * limitations under the License.
18  * ============LICENSE_END=========================================================
19  */
20
21 package org.onap.so.apihandlerinfra;
22
23 import java.io.IOException;
24 import java.util.ArrayList;
25 import java.util.Arrays;
26 import java.util.List;
27
28 import javax.transaction.Transactional;
29 import javax.ws.rs.GET;
30 import javax.ws.rs.Path;
31 import javax.ws.rs.PathParam;
32 import javax.ws.rs.QueryParam;
33 import javax.ws.rs.core.Response;
34 import javax.ws.rs.core.UriBuilder;
35
36 import org.apache.http.HttpResponse;
37 import org.apache.http.HttpStatus;
38 import org.json.JSONArray;
39 import org.json.JSONException;
40 import org.json.JSONObject;
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.TaskList;
52 import org.onap.so.apihandlerinfra.tasksbeans.TaskVariableValue;
53 import org.onap.so.apihandlerinfra.tasksbeans.TaskVariables;
54 import org.onap.so.apihandlerinfra.tasksbeans.TasksGetResponse;
55 import org.onap.so.logger.MessageEnum;
56
57 import org.onap.so.logger.MsoLogger;
58 import org.onap.so.utils.UUIDChecker;
59 import org.springframework.beans.factory.annotation.Autowired;
60 import org.springframework.beans.factory.annotation.Value;
61 import org.springframework.stereotype.Component;
62
63 import com.fasterxml.jackson.core.JsonProcessingException;
64 import com.fasterxml.jackson.databind.ObjectMapper;
65
66 import io.swagger.annotations.Api;
67 import io.swagger.annotations.ApiOperation;
68
69 @Path("onap/so/infra/tasks")
70 @Api(value="onap/so/infra/tasks",description="Queries of Manual Tasks")
71 @Component
72 public class TasksHandler {
73
74
75     private static MsoLogger msoLogger = MsoLogger.getMsoLogger (MsoLogger.Catalog.APIH,TasksHandler.class);
76        
77     @Value("${mso.camunda.rest.task.uri}")
78     private String requestUrl;
79     
80         @Autowired
81         private RequestClientFactory reqClientFactory;
82
83         @Autowired
84         private ResponseBuilder builder;
85         
86     @Path("/{version:[vV]1}")
87     @GET
88     @ApiOperation(value="Finds Manual Tasks",response=Response.class)
89     @Transactional
90     public Response queryFilters (@QueryParam("taskId") String taskId,
91                                   @QueryParam("originalRequestId") String originalRequestId,
92                                   @QueryParam("subscriptionServiceType") String subscriptionServiceType,
93                                   @QueryParam("nfRole") String nfRole,
94                                   @QueryParam("buildingBlockName") String buildingBlockName,
95                                   @QueryParam("originalRequestDate") String originalRequestDate,
96                                   @QueryParam("originalRequestorId") String originalRequestorId,
97                                   @PathParam("version") String version) throws ApiException {
98         Response responseBack = null;
99
100         String requestId = UUIDChecker.generateUUID(msoLogger);
101         MsoLogger.setServiceName ("ManualTasksQuery");
102         // Generate a Request Id
103         UUIDChecker.generateUUID(msoLogger);
104                 String apiVersion = version.substring(1);
105         
106         // Prepare the query string to /task interface
107         TaskVariables tv = new TaskVariables();
108         
109         List<TaskVariableValue> tvvList = new ArrayList<>();
110         
111         if (originalRequestId != null) {
112                 TaskVariableValue tvv = new TaskVariableValue();
113                 tvv.setName("originalRequestId");
114                 tvv.setValue(originalRequestId);
115                 tvv.setOperator("eq");
116                 tvvList.add(tvv);        
117         }
118         if (subscriptionServiceType != null) {
119                 TaskVariableValue tvv = new TaskVariableValue();
120                 tvv.setName("subscriptionServiceType");
121                 tvv.setValue(subscriptionServiceType);
122                 tvv.setOperator("eq");
123                 tvvList.add(tvv);        
124         }
125         if (nfRole != null) {
126                 TaskVariableValue tvv = new TaskVariableValue();
127                 tvv.setName("nfRole");
128                 tvv.setValue(nfRole);
129                 tvv.setOperator("eq");
130                 tvvList.add(tvv);        
131         }
132         if (buildingBlockName != null) {
133                 TaskVariableValue tvv = new TaskVariableValue();
134                 tvv.setName("buildingBlockName");
135                 tvv.setValue(buildingBlockName);
136                 tvv.setOperator("eq");
137                 tvvList.add(tvv);        
138         }
139         if (originalRequestDate != null) {
140                 TaskVariableValue tvv = new TaskVariableValue();
141                 tvv.setName("originalRequestDate");
142                 tvv.setValue(originalRequestDate);
143                 tvv.setOperator("eq");
144                 tvvList.add(tvv);        
145         }
146         if (originalRequestorId != null) {
147                 TaskVariableValue tvv = new TaskVariableValue();
148                 tvv.setName("originalRequestorId");
149                 tvv.setValue(originalRequestorId);
150                 tvv.setOperator("eq");
151                 tvvList.add(tvv);        
152         }       
153       
154         tv.setTaskVariables(tvvList);
155        
156         RequestClient requestClient = null;
157        
158                 HttpResponse response = null;   
159
160                 try {
161                         requestClient = reqClientFactory.getRequestClient(requestUrl);
162                         // Capture audit event
163                         ObjectMapper mapper = new ObjectMapper();
164                         String camundaJsonReq = mapper.writeValueAsString(tv);
165                         response = requestClient.post(camundaJsonReq);
166
167                 } catch(JsonProcessingException e){
168                         ErrorLoggerInfo errorLoggerInfo = new ErrorLoggerInfo.Builder(MessageEnum.APIH_REQUEST_VALIDATION_ERROR, MsoLogger.ErrorCode.SchemaError).build();
169
170
171                         ValidateException validateException = new ValidateException.Builder("Mapping of request to JSON object failed : " + e.getMessage(),
172                                         HttpStatus.SC_BAD_REQUEST, ErrorNumbers.SVC_BAD_PARAMETER).cause(e).errorInfo(errorLoggerInfo).build();
173
174                         throw validateException;
175                 } catch(IOException e) {
176                         ErrorLoggerInfo errorLoggerInfo = new ErrorLoggerInfo.Builder(MessageEnum.APIH_BPEL_COMMUNICATE_ERROR, MsoLogger.ErrorCode.AvailabilityError).build();
177                         BPMNFailureException bpmnFailureException = new BPMNFailureException.Builder(String.valueOf(HttpStatus.SC_BAD_GATEWAY),HttpStatus.SC_BAD_GATEWAY,ErrorNumbers.SVC_NO_SERVER_RESOURCES).build();
178                         throw bpmnFailureException;
179                 }
180                 TasksGetResponse trr = new TasksGetResponse();
181                 List<TaskList> taskList = new ArrayList<>();
182                 
183                 ResponseHandler respHandler = new ResponseHandler (response, requestClient.getType ());
184                 int bpelStatus = respHandler.getStatus ();
185                 if (bpelStatus == HttpStatus.SC_NO_CONTENT || bpelStatus == HttpStatus.SC_ACCEPTED) {                   
186                         String respBody = respHandler.getResponseBody();
187                         if (respBody != null) {                         
188                                 JSONArray data = new JSONArray(respBody);
189                                 
190                                 for (int i=0; i<data.length();i++) {
191                                         JSONObject taskEntry = data.getJSONObject(i);
192                                         String id = taskEntry.getString("id");
193                                         if (taskId != null && !taskId.equals(id)) {
194                                                 continue;                                               
195                                         }
196                                         // Get variables info for each task ID
197                                         TaskList taskListEntry = null;
198                                         taskListEntry = getTaskInfo(id);
199
200                                         taskList.add(taskListEntry);                            
201                                         
202                                 }
203                                 trr.setTaskList(taskList);                              
204                         }
205                 
206                 } else {
207
208                         ErrorLoggerInfo errorLoggerInfo = new ErrorLoggerInfo.Builder(MessageEnum.APIH_BPEL_RESPONSE_ERROR, MsoLogger.ErrorCode.BusinessProcesssError).build();
209
210
211                         BPMNFailureException bpmnFailureException = new BPMNFailureException.Builder(String.valueOf(bpelStatus), bpelStatus, ErrorNumbers.SVC_DETAILED_SERVICE_ERROR)
212                                         .errorInfo(errorLoggerInfo).build();
213
214                         throw bpmnFailureException;
215                 }
216                 
217                 String jsonResponse = null;
218                 try {
219                         ObjectMapper mapper = new ObjectMapper();                       
220                         jsonResponse = mapper.writeValueAsString(trr);
221                 }
222                 catch (JsonProcessingException e) {
223                         ErrorLoggerInfo errorLoggerInfo = new ErrorLoggerInfo.Builder(MessageEnum.APIH_REQUEST_VALIDATION_ERROR, MsoLogger.ErrorCode.SchemaError).build();
224
225
226                         ValidateException validateException = new ValidateException.Builder("Mapping of request to JSON object failed : " + e.getMessage(),
227                                         HttpStatus.SC_BAD_REQUEST, ErrorNumbers.SVC_BAD_PARAMETER).cause(e).errorInfo(errorLoggerInfo).build();
228
229                         throw validateException;
230                 }
231                 
232                 return builder.buildResponse(HttpStatus.SC_ACCEPTED, requestId, jsonResponse, apiVersion);
233     }    
234
235     protected MsoLogger getMsoLogger () {
236         return msoLogger;
237     }
238     
239     // Makes a GET call to Camunda to get variables for this task
240     private TaskList getTaskInfo(String taskId) throws ApiException{
241         TaskList taskList;
242         String getRequestUrl = UriBuilder.fromUri(requestUrl).path(taskId).path("variables").build().toString();
243                 HttpResponse getResponse;
244                 
245                 RequestClient requestClient = reqClientFactory.getRequestClient (getRequestUrl);                                                
246                 // Capture audit event
247                 try {
248                         getResponse = requestClient.get();
249                 }catch(IOException e){
250                         ErrorLoggerInfo errorLoggerInfo = new ErrorLoggerInfo.Builder(MessageEnum.APIH_BPEL_COMMUNICATE_ERROR, MsoLogger.ErrorCode.AvailabilityError).build();
251                         BPMNFailureException validateException = new BPMNFailureException.Builder(String.valueOf(HttpStatus.SC_BAD_GATEWAY), HttpStatus.SC_BAD_GATEWAY, ErrorNumbers.SVC_NO_SERVER_RESOURCES).build();
252                         throw validateException;
253                 }
254                 ResponseHandler respHandler = new ResponseHandler (getResponse, requestClient.getType ());
255                 int bpelStatus = respHandler.getStatus ();
256                 if (bpelStatus == HttpStatus.SC_ACCEPTED) {                     
257                         String respBody = respHandler.getResponseBody();
258                         if (respBody != null) {
259                                 taskList = buildTaskList(taskId, respBody);                             
260                         }
261                         else {
262                                 ErrorLoggerInfo errorLoggerInfo = new ErrorLoggerInfo.Builder(MessageEnum.APIH_BPEL_COMMUNICATE_ERROR, MsoLogger.ErrorCode.AvailabilityError).build();
263
264
265
266
267                                 BPMNFailureException bpmnFailureException = new BPMNFailureException.Builder(String.valueOf(HttpStatus.SC_BAD_GATEWAY), HttpStatus.SC_BAD_GATEWAY, ErrorNumbers.SVC_NO_SERVER_RESOURCES).build();
268
269                                 throw bpmnFailureException;
270                         }
271                         
272                 }
273                 else {
274                         ErrorLoggerInfo errorLoggerInfo = new ErrorLoggerInfo.Builder(MessageEnum.APIH_BPEL_COMMUNICATE_ERROR, MsoLogger.ErrorCode.AvailabilityError).build();
275
276
277
278
279                         BPMNFailureException bpmnFailureException = new BPMNFailureException.Builder(String.valueOf(bpelStatus), bpelStatus, ErrorNumbers.SVC_NO_SERVER_RESOURCES).build();
280
281
282                         throw bpmnFailureException;
283                 }
284                 
285         return taskList;
286         
287     }
288     
289     private TaskList buildTaskList(String taskId, String respBody) throws JSONException {
290         TaskList taskList = new TaskList();
291         JSONObject variables = new JSONObject(respBody);
292         
293         taskList.setTaskId(taskId);
294         taskList.setType(getOptVariableValue(variables, "type"));
295         taskList.setNfRole(getOptVariableValue(variables, "nfRole"));
296         taskList.setSubscriptionServiceType(getOptVariableValue(variables, "subscriptionServiceType"));
297         taskList.setOriginalRequestId(getOptVariableValue(variables, "originalRequestId"));
298         taskList.setOriginalRequestorId(getOptVariableValue(variables, "originalRequestorId"));
299         taskList.setErrorSource(getOptVariableValue(variables, "errorSource"));
300         taskList.setErrorCode(getOptVariableValue(variables, "errorCode"));
301         taskList.setErrorMessage(getOptVariableValue(variables, "errorMessage"));
302         taskList.setBuildingBlockName(getOptVariableValue(variables, "buildingBlockName"));
303         taskList.setBuildingBlockStep(getOptVariableValue(variables, "buildingBlockStep"));  
304         
305         String validResponses = getOptVariableValue(variables, "validResponses").toLowerCase();
306         List<String> items = Arrays.asList(validResponses.split("\\s*,\\s*"));
307         taskList.setValidResponses(items);
308         
309         return taskList;        
310     }
311     
312     private String getOptVariableValue(JSONObject variables, String name) throws JSONException {
313         String variableEntry = variables.optString(name);
314         String value = "";
315         if (!variableEntry.isEmpty()) {
316                 JSONObject variableEntryJson = new JSONObject(variableEntry);
317                 value = variableEntryJson.optString("value");                   
318         }
319         return value;
320     }
321    
322    
323 }