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