529cd2afbe36fa3994ed99457e4236ec49ca874e
[nonrtric.git] / dashboard / webapp-backend / src / main / java / org / oransc / ric / portal / dashboard / controller / PolicyController.java
1 /*-
2  * ========================LICENSE_START=================================
3  * O-RAN-SC
4  * %%
5  * Copyright (C) 2019 Nordix Foundation
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 package org.oransc.ric.portal.dashboard.controller;
21
22 import java.lang.invoke.MethodHandles;
23
24 import javax.servlet.http.HttpServletResponse;
25
26 import com.google.gson.Gson;
27 import com.google.gson.GsonBuilder;
28
29 import org.oransc.ric.portal.dashboard.DashboardApplication;
30 import org.oransc.ric.portal.dashboard.DashboardConstants;
31 import org.oransc.ric.portal.dashboard.exceptions.HttpBadRequestException;
32 import org.oransc.ric.portal.dashboard.exceptions.HttpInternalServerErrorException;
33 import org.oransc.ric.portal.dashboard.exceptions.HttpNotFoundException;
34 import org.oransc.ric.portal.dashboard.exceptions.HttpNotImplementedException;
35 import org.oransc.ric.portal.dashboard.model.PolicyInstances;
36 import org.oransc.ric.portal.dashboard.model.PolicyTypes;
37 import org.oransc.ric.portal.dashboard.model.SuccessTransport;
38 import org.oransc.ric.portal.dashboard.policyagentapi.PolicyAgentApi;
39 import org.slf4j.Logger;
40 import org.slf4j.LoggerFactory;
41 import org.springframework.beans.factory.annotation.Autowired;
42 import org.springframework.http.HttpStatus;
43 import org.springframework.http.MediaType;
44 import org.springframework.http.ResponseEntity;
45 import org.springframework.security.access.annotation.Secured;
46 import org.springframework.util.Assert;
47 import org.springframework.web.bind.annotation.DeleteMapping;
48 import org.springframework.web.bind.annotation.GetMapping;
49 import org.springframework.web.bind.annotation.PathVariable;
50 import org.springframework.web.bind.annotation.PutMapping;
51 import org.springframework.web.bind.annotation.RequestBody;
52 import org.springframework.web.bind.annotation.RequestMapping;
53 import org.springframework.web.bind.annotation.RequestParam;
54 import org.springframework.web.bind.annotation.RestController;
55 import java.util.Collection;
56 import io.swagger.annotations.ApiOperation;
57
58 /**
59  * Proxies calls from the front end to the Policy agent API.
60  *
61  * If a method throws RestClientResponseException, it is handled by
62  * {@link CustomResponseEntityExceptionHandler#handleProxyMethodException(Exception, org.springframework.web.context.request.WebRequest)}
63  * which returns status 502. All other exceptions are handled by Spring which
64  * returns status 500.
65  */
66 @RestController
67 @RequestMapping(value = PolicyController.CONTROLLER_PATH, produces = MediaType.APPLICATION_JSON_VALUE)
68 public class PolicyController {
69
70         private static final Logger logger = LoggerFactory.getLogger(MethodHandles.lookup().lookupClass());
71         private static Gson gson = new GsonBuilder() //
72                         .serializeNulls() //
73                         .create(); //
74
75         // Publish paths in constants so tests are easy to write
76         public static final String CONTROLLER_PATH = DashboardConstants.ENDPOINT_PREFIX + "/policy";
77         // Endpoints
78         public static final String VERSION_METHOD = DashboardConstants.VERSION_METHOD;
79         public static final String POLICY_TYPES_METHOD = "policytypes";
80         public static final String POLICY_TYPE_ID_NAME = "policy_type_id";
81         public static final String POLICIES_NAME = "policies";
82         public static final String POLICY_INSTANCE_ID_NAME = "policy_instance_id";
83
84         // Populated by the autowired constructor
85         private final PolicyAgentApi policyAgentApi;
86
87         @Autowired
88         public PolicyController(final PolicyAgentApi policyAgentApi) {
89                 Assert.notNull(policyAgentApi, "API must not be null");
90                 this.policyAgentApi = policyAgentApi;
91                 logger.debug("ctor: configured with client type {}", policyAgentApi.getClass().getName());
92         }
93
94         /*
95          * The fields are defined in the Policy Control Typescript interface.
96          */
97         @ApiOperation(value = "Gets the policy types from Near Realtime-RIC")
98         @GetMapping(POLICY_TYPES_METHOD)
99         @Secured({ DashboardConstants.ROLE_ADMIN, DashboardConstants.ROLE_STANDARD })
100         public ResponseEntity<PolicyTypes> getAllPolicyTypes(HttpServletResponse response) {
101                 logger.debug("getAllPolicyTypes");
102                 return this.policyAgentApi.getAllPolicyTypes();
103         }
104
105         @ApiOperation(value = "Returns the policy instances for the given policy type.")
106         @GetMapping(POLICY_TYPES_METHOD + "/{" + POLICY_TYPE_ID_NAME + "}/" + POLICIES_NAME)
107         @Secured({ DashboardConstants.ROLE_ADMIN, DashboardConstants.ROLE_STANDARD })
108         public ResponseEntity<String> getPolicyInstances(@PathVariable(POLICY_TYPE_ID_NAME) String policyTypeIdString) {
109                 logger.debug("getPolicyInstances {}", policyTypeIdString);
110
111                 ResponseEntity<PolicyInstances> response = this.policyAgentApi.getPolicyInstancesForType(policyTypeIdString);
112                 if (!response.getStatusCode().is2xxSuccessful()) {
113                         return new ResponseEntity<>(response.getStatusCode());
114                 }
115                 String json = gson.toJson(response.getBody());
116                 return new ResponseEntity<>(json, response.getStatusCode());
117         }
118
119         @ApiOperation(value = "Returns a policy instance of a type")
120         @GetMapping(POLICY_TYPES_METHOD + "/{" + POLICY_TYPE_ID_NAME + "}/" + POLICIES_NAME + "/{" + POLICY_INSTANCE_ID_NAME
121                         + "}")
122         @Secured({ DashboardConstants.ROLE_ADMIN, DashboardConstants.ROLE_STANDARD })
123         public ResponseEntity<String> getPolicyInstance(@PathVariable(POLICY_TYPE_ID_NAME) String policyTypeIdString,
124                         @PathVariable(POLICY_INSTANCE_ID_NAME) String policyInstanceId) {
125                 logger.debug("getPolicyInstance {}:{}", policyTypeIdString, policyInstanceId);
126                 return this.policyAgentApi.getPolicyInstance(policyInstanceId);
127         }
128
129         @ApiOperation(value = "Creates the policy instances for the given policy type.")
130         @PutMapping(POLICY_TYPES_METHOD + "/{" + POLICY_TYPE_ID_NAME + "}/" + POLICIES_NAME + "/{" + POLICY_INSTANCE_ID_NAME
131                         + "}")
132         @Secured({ DashboardConstants.ROLE_ADMIN })
133         public ResponseEntity<String> putPolicyInstance(@PathVariable(POLICY_TYPE_ID_NAME) String policyTypeIdString,
134                         @RequestParam(name = "ric", required = true) String ric,
135                         @PathVariable(POLICY_INSTANCE_ID_NAME) String policyInstanceId, @RequestBody String instance) {
136                 logger.debug("putPolicyInstance typeId: {}, instanceId: {}, instance: {}", policyTypeIdString, policyInstanceId,
137                                 instance);
138                 return this.policyAgentApi.putPolicy(policyTypeIdString, policyInstanceId, instance, ric);
139         }
140
141         @ApiOperation(value = "Deletes the policy instances for the given policy type.")
142         @DeleteMapping(POLICY_TYPES_METHOD + "/{" + POLICY_TYPE_ID_NAME + "}/" + POLICIES_NAME + "/{"
143                         + POLICY_INSTANCE_ID_NAME + "}")
144         @Secured({ DashboardConstants.ROLE_ADMIN })
145         public void deletePolicyInstance(@PathVariable(POLICY_TYPE_ID_NAME) String policyTypeIdString,
146                         @PathVariable(POLICY_INSTANCE_ID_NAME) String policyInstanceId) {
147                 logger.debug("deletePolicyInstance typeId: {}, instanceId: {}", policyTypeIdString, policyInstanceId);
148                 this.policyAgentApi.deletePolicy(policyInstanceId);
149         }
150
151         private void checkHttpError(String httpCode) {
152                 logger.debug("Http Response Code: {}", httpCode);
153                 if (httpCode.equals(String.valueOf(HttpStatus.NOT_FOUND.value()))) {
154                         logger.error("Caught HttpNotFoundException");
155                         throw new HttpNotFoundException("Not Found Exception");
156                 } else if (httpCode.equals(String.valueOf(HttpStatus.BAD_REQUEST.value()))) {
157                         logger.error("Caught HttpBadRequestException");
158                         throw new HttpBadRequestException("Bad Request Exception");
159                 } else if (httpCode.equals(String.valueOf(HttpStatus.INTERNAL_SERVER_ERROR.value()))) {
160                         logger.error("Caught HttpInternalServerErrorException");
161                         throw new HttpInternalServerErrorException("Internal Server Error Exception");
162                 } else if (httpCode.equals(String.valueOf(HttpStatus.NOT_IMPLEMENTED.value()))) {
163                         logger.error("Caught HttpNotImplementedException");
164                         throw new HttpNotImplementedException("Not Implemented Exception");
165                 }
166         }
167
168         @ApiOperation(value = "Returns the rics supporting the given policy type.")
169         @GetMapping("/rics")
170         @Secured({ DashboardConstants.ROLE_ADMIN, DashboardConstants.ROLE_STANDARD })
171         public ResponseEntity<String> getRicsSupportingType(
172                         @RequestParam(name = "policyType", required = true) String supportingPolicyType) {
173                 logger.debug("getRicsSupportingType {}", supportingPolicyType);
174
175                 ResponseEntity<Collection<String>> result = this.policyAgentApi.getRicsSupportingType(supportingPolicyType);
176                 if (!result.getStatusCode().is2xxSuccessful()) {
177                         return new ResponseEntity<>(result.getStatusCode());
178                 }
179                 String json = gson.toJson(result.getBody());
180                 return new ResponseEntity<>(json, result.getStatusCode());
181         }
182
183 };