90cf50262b7f58e8bb8da3420a30be3adb613484
[so.git] /
1 /*-
2  * ============LICENSE_START=======================================================
3  * ONAP - SO
4  * ================================================================================
5  * Copyright (C) 2019 Huawei Technologies Co., Ltd. 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 com.fasterxml.jackson.databind.ObjectMapper;
24 import io.swagger.v3.oas.annotations.OpenAPIDefinition;
25 import io.swagger.v3.oas.annotations.Operation;
26 import io.swagger.v3.oas.annotations.info.Info;
27 import io.swagger.v3.oas.annotations.media.ArraySchema;
28 import io.swagger.v3.oas.annotations.media.Content;
29 import io.swagger.v3.oas.annotations.media.Schema;
30 import io.swagger.v3.oas.annotations.responses.ApiResponse;
31 import org.apache.http.HttpStatus;
32 import org.json.JSONObject;
33 import org.onap.so.apihandler.common.ErrorNumbers;
34 import org.onap.so.apihandler.common.ResponseBuilder;
35 import org.onap.so.apihandlerinfra.exceptions.ApiException;
36 import org.onap.so.db.request.beans.OrchestrationTask;
37 import org.onap.so.db.request.client.RequestsDbClient;
38 import org.onap.so.logger.ErrorCode;
39 import org.onap.so.logger.LoggingAnchor;
40 import org.onap.so.logger.MessageEnum;
41 import org.slf4j.Logger;
42 import org.slf4j.LoggerFactory;
43 import org.springframework.beans.factory.annotation.Autowired;
44 import org.springframework.stereotype.Component;
45 import javax.transaction.Transactional;
46 import javax.ws.rs.*;
47 import javax.ws.rs.core.MediaType;
48 import javax.ws.rs.core.Response;
49 import java.util.HashMap;
50 import java.util.Iterator;
51 import java.util.List;
52 import java.util.Map;
53 import static org.onap.so.apihandlerinfra.Constants.MSO_PROP_APIHANDLER_INFRA;
54
55 @Path("/onap/so/infra/orchestrationTasks")
56 @OpenAPIDefinition(
57         info = @Info(title = "onap/so/infra/orchestrationTasks", description = "API Requests for Orchestration Task"))
58 @Component
59 public class OrchestrationTasks {
60
61     private static Logger logger = LoggerFactory.getLogger(OrchestrationTasks.class);
62
63     @Autowired
64     private MsoRequest msoRequest;
65
66     @Autowired
67     private CamundaRequestHandler camundaRequestHandler;
68
69     @Autowired
70     private RequestsDbClient requestsDbClient;
71
72     @Autowired
73     private ResponseBuilder builder;
74
75     private ObjectMapper mapper = new ObjectMapper();
76
77     @GET
78     @Path("/{version:[vV][4-7]}/")
79     @Operation(description = "Find All Orchestrated Task", responses = @ApiResponse(
80             content = @Content(array = @ArraySchema(schema = @Schema(implementation = Response.class)))))
81     @Produces(MediaType.APPLICATION_JSON)
82     @Transactional
83     public Response getAllOrchestrationTasks(@QueryParam("status") String status,
84             @PathParam("version") String version) {
85         List<OrchestrationTask> orchestrationTaskList = requestsDbClient.getAllOrchestrationTasks();
86         if (status != null && !status.isEmpty()) {
87             for (Iterator<OrchestrationTask> it = orchestrationTaskList.iterator(); it.hasNext();) {
88                 OrchestrationTask task = it.next();
89                 if (!status.equals(task.getStatus())) {
90                     it.remove();
91                 }
92             }
93         }
94         return builder.buildResponse(HttpStatus.SC_OK, null, orchestrationTaskList, version);
95     }
96
97     @GET
98     @Path("/{version:[vV][4-7]}/{taskId}")
99     @Operation(description = "Find Orchestrated Task for a given TaskId", responses = @ApiResponse(
100             content = @Content(array = @ArraySchema(schema = @Schema(implementation = Response.class)))))
101     @Produces(MediaType.APPLICATION_JSON)
102     @Transactional
103     public Response getOrchestrationTask(@PathParam("taskId") String taskId, @PathParam("version") String version)
104             throws ApiException {
105         try {
106             OrchestrationTask orchestrationTask = requestsDbClient.getOrchestrationTask(taskId);
107             return builder.buildResponse(HttpStatus.SC_OK, null, orchestrationTask, version);
108         } catch (Exception e) {
109             logger.error(LoggingAnchor.FOUR, MessageEnum.APIH_DB_ACCESS_EXC.toString(), MSO_PROP_APIHANDLER_INFRA,
110                     ErrorCode.AvailabilityError.getValue(),
111                     "Exception while communciate with Request DB - Orchestration Task Lookup", e);
112             Response response =
113                     msoRequest.buildServiceErrorResponse(HttpStatus.SC_NOT_FOUND, MsoException.ServiceException,
114                             e.getMessage(), ErrorNumbers.NO_COMMUNICATION_TO_REQUESTS_DB, null, version);
115             return response;
116         }
117     }
118
119     @POST
120     @Path("/{version:[vV][4-7]}/")
121     @Operation(description = "Create an Orchestrated Task", responses = @ApiResponse(
122             content = @Content(array = @ArraySchema(schema = @Schema(implementation = Response.class)))))
123     @Produces(MediaType.APPLICATION_JSON)
124     @Transactional
125     public Response CreateOrchestrationTask(String requestJson, @PathParam("version") String version) {
126         try {
127             OrchestrationTask orchestrationTask = mapper.readValue(requestJson, OrchestrationTask.class);
128             requestsDbClient.createOrchestrationTask(orchestrationTask);
129             return builder.buildResponse(HttpStatus.SC_OK, null, orchestrationTask, version);
130         } catch (Exception e) {
131             logger.error(LoggingAnchor.FOUR, MessageEnum.APIH_DB_ACCESS_EXC.toString(), MSO_PROP_APIHANDLER_INFRA,
132                     ErrorCode.AvailabilityError.getValue(),
133                     "Exception while communciate with Request DB - Orchestration Task Create", e);
134             Response response = msoRequest.buildServiceErrorResponse(HttpStatus.SC_INTERNAL_SERVER_ERROR,
135                     MsoException.ServiceException, e.getMessage(), ErrorNumbers.COULD_NOT_WRITE_TO_REQUESTS_DB, null,
136                     version);
137             return response;
138         }
139     }
140
141     @PUT
142     @Path("/{version:[vV][4-7]}/{taskId}")
143     @Operation(description = "Update an Orchestrated Task", responses = @ApiResponse(
144             content = @Content(array = @ArraySchema(schema = @Schema(implementation = Response.class)))))
145     @Produces(MediaType.APPLICATION_JSON)
146     @Transactional
147     public Response UpdateOrchestrationTask(@PathParam("taskId") String taskId, String requestJson,
148             @PathParam("version") String version) {
149         try {
150             OrchestrationTask orchestrationTask = requestsDbClient.getOrchestrationTask(taskId);
151         } catch (Exception e) {
152             logger.error(LoggingAnchor.FOUR, MessageEnum.APIH_DB_ACCESS_EXC.toString(), MSO_PROP_APIHANDLER_INFRA,
153                     ErrorCode.AvailabilityError.getValue(),
154                     "Exception while communciate with Request DB - Orchestration Task Update", e);
155             Response response =
156                     msoRequest.buildServiceErrorResponse(HttpStatus.SC_NOT_FOUND, MsoException.ServiceException,
157                             e.getMessage(), ErrorNumbers.NO_COMMUNICATION_TO_REQUESTS_DB, null, version);
158             return response;
159         }
160
161         try {
162             OrchestrationTask orchestrationTask = mapper.readValue(requestJson, OrchestrationTask.class);
163             requestsDbClient.updateOrchestrationTask(taskId, orchestrationTask);
164             return builder.buildResponse(HttpStatus.SC_OK, null, orchestrationTask, version);
165         } catch (Exception e) {
166             logger.error(LoggingAnchor.FOUR, MessageEnum.APIH_DB_ACCESS_EXC.toString(), MSO_PROP_APIHANDLER_INFRA,
167                     ErrorCode.AvailabilityError.getValue(),
168                     "Exception while communciate with Request DB - Orchestration Task Update", e);
169             Response response = msoRequest.buildServiceErrorResponse(HttpStatus.SC_INTERNAL_SERVER_ERROR,
170                     MsoException.ServiceException, e.getMessage(), ErrorNumbers.NO_COMMUNICATION_TO_REQUESTS_DB, null,
171                     version);
172             return response;
173         }
174     }
175
176     @DELETE
177     @Path("/{version:[vV][4-7]}/{taskId}")
178     @Operation(description = "Delete an Orchestrated Task", responses = @ApiResponse(
179             content = @Content(array = @ArraySchema(schema = @Schema(implementation = Response.class)))))
180     @Produces(MediaType.APPLICATION_JSON)
181     @Transactional
182     public Response DeleteOrchestrationTask(@PathParam("taskId") String taskId, @PathParam("version") String version) {
183         try {
184             OrchestrationTask orchestrationTask = requestsDbClient.getOrchestrationTask(taskId);
185         } catch (Exception e) {
186             logger.error(LoggingAnchor.FOUR, MessageEnum.APIH_DB_ACCESS_EXC.toString(), MSO_PROP_APIHANDLER_INFRA,
187                     ErrorCode.AvailabilityError.getValue(),
188                     "Exception while communciate with Request DB - Orchestration Task Delete", e);
189             Response response =
190                     msoRequest.buildServiceErrorResponse(HttpStatus.SC_NOT_FOUND, MsoException.ServiceException,
191                             e.getMessage(), ErrorNumbers.NO_COMMUNICATION_TO_REQUESTS_DB, null, version);
192             return response;
193         }
194
195         try {
196             requestsDbClient.deleteOrchestrationTask(taskId);
197             return builder.buildResponse(HttpStatus.SC_OK, null, null, version);
198         } catch (Exception e) {
199             logger.error(LoggingAnchor.FOUR, MessageEnum.APIH_DB_ACCESS_EXC.toString(), MSO_PROP_APIHANDLER_INFRA,
200                     ErrorCode.AvailabilityError.getValue(),
201                     "Exception while communciate with Request DB - Orchestration Task Delete", e);
202             Response response = msoRequest.buildServiceErrorResponse(HttpStatus.SC_INTERNAL_SERVER_ERROR,
203                     MsoException.ServiceException, e.getMessage(), ErrorNumbers.COULD_NOT_WRITE_TO_REQUESTS_DB, null,
204                     version);
205             return response;
206         }
207     }
208
209     @POST
210     @Path("/{version:[vV][4-7]}/{taskId}/commit")
211     @Operation(description = "Commit an Orchestrated Task", responses = @ApiResponse(
212             content = @Content(array = @ArraySchema(schema = @Schema(implementation = Response.class)))))
213     @Produces(MediaType.APPLICATION_JSON)
214     @Transactional
215     public Response CommitOrchestrationTask(@PathParam("taskId") String taskId, @PathParam("version") String version) {
216         OrchestrationTask orchestrationTask;
217         try {
218             orchestrationTask = requestsDbClient.getOrchestrationTask(taskId);
219         } catch (Exception e) {
220             logger.error(LoggingAnchor.FOUR, MessageEnum.APIH_DB_ACCESS_EXC.toString(), MSO_PROP_APIHANDLER_INFRA,
221                     ErrorCode.AvailabilityError.getValue(),
222                     "Exception while communciate with Request DB - Orchestration Task Commit", e);
223             Response response =
224                     msoRequest.buildServiceErrorResponse(HttpStatus.SC_NOT_FOUND, MsoException.ServiceException,
225                             e.getMessage(), ErrorNumbers.NO_COMMUNICATION_TO_REQUESTS_DB, null, version);
226             return response;
227         }
228         try {
229             String taskName = orchestrationTask.getName();
230             Map<String, String> commitVar = new HashMap<>();
231             commitVar.put("taskAction", "commit");
232             JSONObject msgJson = createMessageBody(taskId, taskName, commitVar);
233             camundaRequestHandler.sendCamundaMessages(msgJson);
234             return builder.buildResponse(HttpStatus.SC_OK, null, orchestrationTask, version);
235         } catch (Exception e) {
236             logger.error(LoggingAnchor.FOUR, MessageEnum.APIH_DB_ACCESS_EXC.toString(), MSO_PROP_APIHANDLER_INFRA,
237                     ErrorCode.AvailabilityError.getValue(),
238                     "Exception while communciate with Request DB - Orchestration Task Delete", e);
239             Response response = msoRequest.buildServiceErrorResponse(HttpStatus.SC_INTERNAL_SERVER_ERROR,
240                     MsoException.ServiceException, e.getMessage(), ErrorNumbers.ERROR_FROM_BPEL, null, version);
241             return response;
242         }
243
244     }
245
246     @POST
247     @Path("/{version:[vV][4-7]}/{taskId}/abort")
248     @Operation(description = "Commit an Orchestrated Task", responses = @ApiResponse(
249             content = @Content(array = @ArraySchema(schema = @Schema(implementation = Response.class)))))
250     @Produces(MediaType.APPLICATION_JSON)
251     @Transactional
252     public Response AbortOrchestrationTask(@PathParam("taskId") String taskId, @PathParam("version") String version) {
253         OrchestrationTask orchestrationTask;
254         try {
255             orchestrationTask = requestsDbClient.getOrchestrationTask(taskId);
256         } catch (Exception e) {
257             logger.error(LoggingAnchor.FOUR, MessageEnum.APIH_DB_ACCESS_EXC.toString(), MSO_PROP_APIHANDLER_INFRA,
258                     ErrorCode.AvailabilityError.getValue(),
259                     "Exception while communciate with Request DB - Orchestration Task Commit", e);
260             Response response =
261                     msoRequest.buildServiceErrorResponse(HttpStatus.SC_NOT_FOUND, MsoException.ServiceException,
262                             e.getMessage(), ErrorNumbers.NO_COMMUNICATION_TO_REQUESTS_DB, null, version);
263             return response;
264         }
265         try {
266             String taskName = orchestrationTask.getName();
267             Map<String, String> commitVar = new HashMap<>();
268             commitVar.put("taskAction", "abort");
269             JSONObject msgJson = createMessageBody(taskId, taskName, commitVar);
270             camundaRequestHandler.sendCamundaMessages(msgJson);
271             return builder.buildResponse(HttpStatus.SC_OK, null, orchestrationTask, version);
272         } catch (Exception e) {
273             logger.error(LoggingAnchor.FOUR, MessageEnum.APIH_DB_ACCESS_EXC.toString(), MSO_PROP_APIHANDLER_INFRA,
274                     ErrorCode.AvailabilityError.getValue(),
275                     "Exception while communciate with Request DB - Orchestration Task Delete", e);
276             Response response = msoRequest.buildServiceErrorResponse(HttpStatus.SC_INTERNAL_SERVER_ERROR,
277                     MsoException.ServiceException, e.getMessage(), ErrorNumbers.ERROR_FROM_BPEL, null, version);
278             return response;
279         }
280
281     }
282
283     private JSONObject createMessageBody(String taskId, String taskName, Map<String, ?> variables) {
284         JSONObject msgJson = new JSONObject();
285         msgJson.put("messageName", taskName);
286         msgJson.put("businessKey", taskId);
287         JSONObject processVariables = new JSONObject();
288         for (Map.Entry<String, ?> entry : variables.entrySet()) {
289             JSONObject valueInfo = new JSONObject();
290             String key = entry.getKey();
291             Object value = entry.getValue();
292             valueInfo.put("value", value.toString());
293             valueInfo.put("type", value.getClass().getSimpleName());
294             processVariables.put(key, valueInfo);
295         }
296         msgJson.put("processVariables", processVariables);
297         return msgJson;
298     }
299
300 }