added svcapi ui and camunda code
[it/otf.git] / otf-service-api / src / main / java / org / oran / otf / api / service / impl / TestExecutionServiceImpl.java
1 /*  Copyright (c) 2019 AT&T Intellectual Property.                             #\r
2 #                                                                              #\r
3 #   Licensed under the Apache License, Version 2.0 (the "License");            #\r
4 #   you may not use this file except in compliance with the License.           #\r
5 #   You may obtain a copy of the License at                                    #\r
6 #                                                                              #\r
7 #       http://www.apache.org/licenses/LICENSE-2.0                             #\r
8 #                                                                              #\r
9 #   Unless required by applicable law or agreed to in writing, software        #\r
10 #   distributed under the License is distributed on an "AS IS" BASIS,          #\r
11 #   WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.   #\r
12 #   See the License for the specific language governing permissions and        #\r
13 #   limitations under the License.                                             #\r
14 ##############################################################################*/\r
15 \r
16 \r
17 package org.oran.otf.api.service.impl;\r
18 \r
19 import org.oran.otf.api.Utilities;\r
20 import org.oran.otf.api.service.TestExecutionService;\r
21 import org.oran.otf.common.model.Group;\r
22 import org.oran.otf.common.model.TestExecution;\r
23 import org.oran.otf.common.model.User;\r
24 import org.oran.otf.common.repository.GroupRepository;\r
25 import org.oran.otf.common.repository.TestExecutionRepository;\r
26 import org.oran.otf.common.repository.UserRepository;\r
27 import org.oran.otf.common.utility.permissions.PermissionChecker;\r
28 import org.oran.otf.common.utility.permissions.UserPermission;\r
29 import com.google.gson.JsonElement;\r
30 import com.google.gson.JsonObject;\r
31 import com.google.gson.JsonParser;\r
32 import java.util.Optional;\r
33 import java.util.UUID;\r
34 import javax.ws.rs.core.Response;\r
35 \r
36 import org.slf4j.Logger;\r
37 import org.slf4j.LoggerFactory;\r
38 import org.springframework.beans.factory.annotation.Autowired;\r
39 import org.springframework.stereotype.Service;\r
40 \r
41 @Service\r
42 public class TestExecutionServiceImpl implements TestExecutionService {\r
43   private static final Logger logger = LoggerFactory.getLogger(TestExecutionServiceImpl.class);\r
44   @Autowired\r
45   private UserRepository userRepository;\r
46   @Autowired private TestExecutionRepository testExecutionRepository;\r
47   @Autowired private GroupRepository groupRepository;\r
48 \r
49   @Override\r
50   public Response getExecutionStatus(String authorization, String executionId) {\r
51     if (authorization == null) {\r
52       return Utilities.Http.BuildResponse.unauthorizedWithMessage("Missing authorization header.");\r
53     }\r
54     // check if the executionId is a valid UUID\r
55     try {\r
56       UUID.fromString(executionId);\r
57     } catch (IllegalArgumentException e) {\r
58       return Utilities.Http.BuildResponse.badRequestWithMessage(\r
59           "Invalid execution identifier. Expected type is UUID (v4).");\r
60     }\r
61 \r
62     // try to find the test execution\r
63     Optional<TestExecution> optionalTestExecution =\r
64         testExecutionRepository.findFirstByProcessInstanceId(executionId);\r
65     TestExecution testExecution = Utilities.resolveOptional(optionalTestExecution);\r
66     if (testExecution == null) {\r
67       return Utilities.Http.BuildResponse.badRequestWithMessage(\r
68           String.format("An execution with identifier %s was not found.", executionId));\r
69     }\r
70 \r
71     // try to find the group of the test execution\r
72     String testExecutionGroupId = testExecution.getGroupId().toString();\r
73     Optional<Group> optionalGroup = groupRepository.findById(testExecutionGroupId);\r
74     Group group = Utilities.resolveOptional(optionalGroup);\r
75     if (group == null) {\r
76       return Utilities.Http.BuildResponse.badRequestWithMessage(\r
77           String.format(\r
78               "The group (id: %s) associated with the test execution does not exist.",\r
79               testExecutionGroupId));\r
80     }\r
81 \r
82     // try to find the user for the mechanizedId used to make this request\r
83     User user = Utilities.findUserByAuthHeader(authorization, userRepository);\r
84     if (user == null) {\r
85       return Utilities.Http.BuildResponse.badRequestWithMessage(\r
86           "No user associated with mechanized identifier used for this request.");\r
87     }\r
88     // if it doesnt have read permission then return bad request\r
89     if (!PermissionChecker.hasPermissionTo(user,group, UserPermission.Permission.READ,groupRepository)){\r
90       return Utilities.Http.BuildResponse.unauthorizedWithMessage(\r
91           "Unauthorized to view this test execution.");\r
92     }\r
93     // Used the build the final response to be returned\r
94     JsonObject res = new JsonObject();\r
95     try {\r
96       // Parsing is required to prevent Gson from escaping all the characters of the json\r
97       JsonElement testExecutionParsed = new JsonParser().parse(testExecution.toString());\r
98       res.add("testExecution", testExecutionParsed);\r
99       // Get the state of the process instance using the Camunda REST API\r
100       JsonObject procInstStatus = Utilities.Camunda.processInstanceStatus(executionId);\r
101       // Extract the state of the process instance from the JSON response\r
102       String processInstanceState =\r
103           procInstStatus.getAsJsonObject("historicProcessInstance").get("state").getAsString();\r
104       // Add the result to the final response\r
105       res.addProperty("state", processInstanceState);\r
106     } catch (NullPointerException npe) {\r
107       // In the case of a null pointer exception, make it clear that the state was not able\r
108       // to be determined using the Camunda API.\r
109       logger.error("Unable to determine the live status of the test execution.");\r
110       res.addProperty("state", "Unable to determine");\r
111     }\r
112     // Send the response\r
113     return Response.ok(res.toString()).build();\r
114   }\r
115 \r
116   @Override\r
117   public Response getExecution(String authorization, String processInstanceId) {\r
118     try {\r
119       UUID.fromString(processInstanceId);\r
120     } catch (IllegalArgumentException e) {\r
121       return Utilities.Http.BuildResponse.badRequestWithMessage(\r
122           "Invalid execution identifier. Expected type is UUID (v4).");\r
123     }\r
124 \r
125     // try to find the test execution\r
126     Optional<TestExecution> optionalTestExecution =\r
127         testExecutionRepository.findFirstByProcessInstanceId(processInstanceId);\r
128     TestExecution testExecution = Utilities.resolveOptional(optionalTestExecution);\r
129     if (testExecution == null) {\r
130       return Utilities.Http.BuildResponse.badRequestWithMessage(\r
131           String.format("An execution with identifier %s was not found.", processInstanceId));\r
132     }\r
133 \r
134     // try to find the group of the test execution\r
135     String testExecutionGroupId = testExecution.getGroupId().toString();\r
136     Optional<Group> optionalGroup = groupRepository.findById(testExecutionGroupId);\r
137     Group group = Utilities.resolveOptional(optionalGroup);\r
138     if (group == null) {\r
139       return Utilities.Http.BuildResponse.badRequestWithMessage(\r
140           String.format(\r
141               "The group (id: %s) associated with the test execution does not exist.",\r
142               testExecutionGroupId));\r
143     }\r
144 \r
145     // try to find the user for the mechanizedId used to make this request\r
146     User user = Utilities.findUserByAuthHeader(authorization, userRepository);\r
147     if (user == null) {\r
148       return Utilities.Http.BuildResponse.badRequestWithMessage(\r
149           "No user associated with mechanized identifier used" + " for this request.");\r
150     }\r
151 \r
152     // if it doesnt have read permission then return bad request\r
153     if (!PermissionChecker.hasPermissionTo(user,group,UserPermission.Permission.READ,groupRepository)){\r
154       return Utilities.Http.BuildResponse.unauthorizedWithMessage(\r
155           "Unauthorized to view this test execution.");\r
156     }\r
157 \r
158     return Response.ok(testExecution.toString()).build();\r
159   }\r
160 }\r