Add Http Response Code in A1 Controller Api
[nonrtric.git] / dashboard / webapp-backend / src / main / java / org / oransc / ric / portal / dashboard / controller / A1Controller.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 import java.util.List;
24 import javax.servlet.http.HttpServletResponse;
25 import org.oransc.ric.a1controller.client.api.A1ControllerApi;
26 import org.oransc.ric.a1controller.client.model.InputNRRidPTidPIidPISchema;
27 import org.oransc.ric.a1controller.client.model.InputNRRidPTidPIidPISchemaInput;
28 import org.oransc.ric.a1controller.client.model.InputNRRidPTidPIidSchema;
29 import org.oransc.ric.a1controller.client.model.InputNRRidPTidPIidSchemaInput;
30 import org.oransc.ric.a1controller.client.model.InputNRRidPTidSchema;
31 import org.oransc.ric.a1controller.client.model.InputNRRidPTidSchemaInput;
32 import org.oransc.ric.a1controller.client.model.InputNRRidSchema;
33 import org.oransc.ric.a1controller.client.model.InputNRRidSchemaInput;
34 import org.oransc.ric.a1controller.client.model.OutputCodeSchema;
35 import org.oransc.ric.a1controller.client.model.OutputDescNamePTCodeSchema;
36 import org.oransc.ric.a1controller.client.model.OutputDescNamePTCodeSchemaOutput;
37 import org.oransc.ric.a1controller.client.model.OutputPICodeSchema;
38 import org.oransc.ric.a1controller.client.model.OutputPIidsListCodeSchema;
39 import org.oransc.ric.a1controller.client.model.OutputPTidsListCodeSchema;
40 import org.oransc.ric.portal.dashboard.DashboardApplication;
41 import org.oransc.ric.portal.dashboard.DashboardConstants;
42 import org.oransc.ric.portal.dashboard.exceptions.HttpBadRequestException;
43 import org.oransc.ric.portal.dashboard.exceptions.HttpInternalServerErrorException;
44 import org.oransc.ric.portal.dashboard.exceptions.HttpNotFoundException;
45 import org.oransc.ric.portal.dashboard.exceptions.HttpNotImplementedException;
46 import org.oransc.ric.portal.dashboard.model.PolicyInstance;
47 import org.oransc.ric.portal.dashboard.model.PolicyInstances;
48 import org.oransc.ric.portal.dashboard.model.PolicyType;
49 import org.oransc.ric.portal.dashboard.model.PolicyTypes;
50 import org.oransc.ric.portal.dashboard.model.SuccessTransport;
51 import org.slf4j.Logger;
52 import org.slf4j.LoggerFactory;
53 import org.springframework.beans.factory.annotation.Autowired;
54 import org.springframework.http.HttpStatus;
55 import org.springframework.http.MediaType;
56 import org.springframework.security.access.annotation.Secured;
57 import org.springframework.util.Assert;
58 import org.springframework.web.bind.annotation.DeleteMapping;
59 import org.springframework.web.bind.annotation.GetMapping;
60 import org.springframework.web.bind.annotation.PathVariable;
61 import org.springframework.web.bind.annotation.PutMapping;
62 import org.springframework.web.bind.annotation.RequestBody;
63 import org.springframework.web.bind.annotation.RequestMapping;
64 import org.springframework.web.bind.annotation.RestController;
65 import io.swagger.annotations.ApiOperation;
66
67 /**
68  * Proxies calls from the front end to the A1 Controller via the A1 Mediator
69  * API.
70  *
71  * If a method throws RestClientResponseException, it is handled by
72  * {@link CustomResponseEntityExceptionHandler#handleProxyMethodException(Exception,
73  * org.springframework.web.context.request.WebRequest)}
74  * which returns status 502. All other exceptions are handled by Spring which
75  * returns status 500.
76  */
77 @RestController
78 @RequestMapping(value = A1Controller.CONTROLLER_PATH, produces = MediaType.APPLICATION_JSON_VALUE)
79 public class A1Controller {
80
81     private static final String NEAR_RT_RIC_ID = "NearRtRic1";
82
83         private static final Logger logger = LoggerFactory.getLogger(MethodHandles.lookup().lookupClass());
84
85         // Publish paths in constants so tests are easy to write
86         public static final String CONTROLLER_PATH = DashboardConstants.ENDPOINT_PREFIX + "/policy";
87         // Endpoints
88         public static final String VERSION_METHOD = DashboardConstants.VERSION_METHOD;
89         public static final String POLICY_TYPES_METHOD = "policytypes";
90         public static final String POLICY_TYPE_ID_NAME = "policy_type_id";
91         public static final String POLICIES_NAME = "policies";
92         public static final String POLICY_INSTANCE_ID_NAME = "policy_instance_id";
93
94         // Populated by the autowired constructor
95         private final A1ControllerApi a1ControllerApi;
96
97         @Autowired
98         public A1Controller(final A1ControllerApi A1ControllerApi) {
99                 Assert.notNull(A1ControllerApi, "API must not be null");
100                 this.a1ControllerApi = A1ControllerApi;
101                 if (logger.isDebugEnabled())
102                         logger.debug("ctor: configured with client type {}", A1ControllerApi.getClass().getName());
103         }
104
105         @ApiOperation(value = "Gets the A1 client library MANIFEST.MF property Implementation-Version.",
106                 response = SuccessTransport.class)
107         @GetMapping(VERSION_METHOD)
108         // No role required
109         public SuccessTransport getA1ControllerClientVersion() {
110                 return new SuccessTransport(200, DashboardApplication.getImplementationVersion(A1ControllerApi.class));
111         }
112
113         /*
114          * The fields are defined in the A1Control Typescript interface.
115          */
116         @ApiOperation(value = "Gets the policy types from Near Realtime-RIC via the A1 Controller API")
117         @GetMapping(POLICY_TYPES_METHOD)
118         @Secured({ DashboardConstants.ROLE_ADMIN, DashboardConstants.ROLE_STANDARD })
119         public Object getAllPolicyTypes(HttpServletResponse response) {
120                 logger.debug("getAllPolicyTypes");
121                 InputNRRidSchemaInput nrrid = new InputNRRidSchemaInput();
122                 nrrid.setNearRtRicId(NEAR_RT_RIC_ID);
123                 InputNRRidSchema inputSchema = new InputNRRidSchema();
124                 inputSchema.setInput(nrrid);
125                 OutputPTidsListCodeSchema outputPTidsListCodeSchema =
126                         a1ControllerApi.a1ControllerGetAllPolicyTypes(inputSchema);
127                 checkHttpError(outputPTidsListCodeSchema.getOutput().getCode());
128                 List<Integer> policyTypeIds = outputPTidsListCodeSchema.getOutput().getPolicyTypeIdList();
129                 PolicyTypes policyTypes = new PolicyTypes();
130                 InputNRRidPTidSchema typeSchema = new InputNRRidPTidSchema();
131                 InputNRRidPTidSchemaInput typeId = new InputNRRidPTidSchemaInput();
132                 typeId.setNearRtRicId(NEAR_RT_RIC_ID);
133                 for (Integer policyTypeId : policyTypeIds) {
134                         typeId.setPolicyTypeId(policyTypeId);
135                         typeSchema.setInput(typeId);
136                         OutputDescNamePTCodeSchema controllerGetPolicyType =
137                                 a1ControllerApi.a1ControllerGetPolicyType(typeSchema);
138                         checkHttpError(controllerGetPolicyType.getOutput().getCode());
139                         OutputDescNamePTCodeSchemaOutput policyTypeSchema = controllerGetPolicyType.getOutput();
140                         PolicyType type = new PolicyType(policyTypeId, policyTypeSchema.getName(),
141                                         policyTypeSchema.getDescription(), policyTypeSchema.getPolicyType().toString());
142                         policyTypes.add(type);
143                 }
144                 return policyTypes;
145         }
146
147         @ApiOperation(value = "Returns the policy instances for the given policy type.")
148         @GetMapping(POLICY_TYPES_METHOD + "/{" + POLICY_TYPE_ID_NAME + "}/" + POLICIES_NAME)
149         @Secured({ DashboardConstants.ROLE_ADMIN, DashboardConstants.ROLE_STANDARD })
150         public Object getPolicyInstances(@PathVariable(POLICY_TYPE_ID_NAME) String policyTypeIdString) {
151                 logger.debug("getPolicyInstances {}", policyTypeIdString);
152                 InputNRRidPTidSchemaInput typeIdInput = new InputNRRidPTidSchemaInput();
153                 typeIdInput.setNearRtRicId(NEAR_RT_RIC_ID);
154                 Integer policyTypeId = Integer.decode(policyTypeIdString);
155                 typeIdInput.setPolicyTypeId(policyTypeId);
156                 InputNRRidPTidSchema inputSchema = new InputNRRidPTidSchema();
157                 inputSchema.setInput(typeIdInput);
158                 OutputPIidsListCodeSchema controllerGetAllInstancesForType =
159                         a1ControllerApi.a1ControllerGetAllInstancesForType(inputSchema);
160                 checkHttpError(controllerGetAllInstancesForType.getOutput().getCode());
161                 List<String> instancesForType = controllerGetAllInstancesForType.getOutput().getPolicyInstanceIdList();
162                 PolicyInstances instances = new PolicyInstances();
163                 InputNRRidPTidPIidSchemaInput instanceIdInput = new InputNRRidPTidPIidSchemaInput();
164                 instanceIdInput.setNearRtRicId(NEAR_RT_RIC_ID);
165                 instanceIdInput.setPolicyTypeId(policyTypeId);
166                 InputNRRidPTidPIidSchema instanceInputSchema = new InputNRRidPTidPIidSchema();
167                 for (String instanceId : instancesForType) {
168                         instanceIdInput.setPolicyInstanceId(instanceId);
169                         instanceInputSchema.setInput(instanceIdInput);
170                         OutputPICodeSchema policyInstance =
171                                 a1ControllerApi.a1ControllerGetPolicyInstance(instanceInputSchema);
172                         checkHttpError(policyInstance.getOutput().getCode());
173                         PolicyInstance instance =
174                                 new PolicyInstance(instanceId, policyInstance.getOutput().getPolicyInstance());
175                         instances.add(instance);
176                 }
177                 return instances;
178         }
179
180         @ApiOperation(value = "Returns a policy instance of a type")
181         @GetMapping(POLICY_TYPES_METHOD + "/{" + POLICY_TYPE_ID_NAME + "}/" + POLICIES_NAME + "/{"
182                 + POLICY_INSTANCE_ID_NAME + "}")
183         @Secured({ DashboardConstants.ROLE_ADMIN, DashboardConstants.ROLE_STANDARD })
184         public Object getPolicyInstance(@PathVariable(POLICY_TYPE_ID_NAME) String policyTypeIdString,
185                         @PathVariable(POLICY_INSTANCE_ID_NAME) String policyInstanceId) {
186                 logger.debug("getPolicyInstance {}:{}", policyTypeIdString, policyInstanceId);
187                 InputNRRidPTidPIidSchemaInput instanceIdInput = new InputNRRidPTidPIidSchemaInput();
188                 instanceIdInput.setNearRtRicId(NEAR_RT_RIC_ID);
189                 instanceIdInput.setPolicyTypeId(Integer.decode(policyTypeIdString));
190                 instanceIdInput.setPolicyInstanceId(policyInstanceId);
191                 InputNRRidPTidPIidSchema inputSchema = new InputNRRidPTidPIidSchema();
192                 inputSchema.setInput(instanceIdInput);
193                 OutputPICodeSchema policyInstance = a1ControllerApi.a1ControllerGetPolicyInstance(inputSchema);
194                 checkHttpError(policyInstance.getOutput().getCode());
195                 return policyInstance.getOutput().getPolicyInstance();
196         }
197
198         @ApiOperation(value = "Creates the policy instances for the given policy type.")
199         @PutMapping(POLICY_TYPES_METHOD + "/{" + POLICY_TYPE_ID_NAME + "}/" + POLICIES_NAME + "/{"
200                 + POLICY_INSTANCE_ID_NAME + "}")
201         @Secured({ DashboardConstants.ROLE_ADMIN })
202         public void putPolicyInstance(@PathVariable(POLICY_TYPE_ID_NAME) String policyTypeIdString,
203                         @PathVariable(POLICY_INSTANCE_ID_NAME) String policyInstanceId, @RequestBody String instance) {
204                 logger.debug("putPolicyInstance typeId: {}, instanceId: {}, instance: {}", policyTypeIdString,
205                         policyInstanceId, instance);
206                 InputNRRidPTidPIidPISchemaInput createInstanceInput = new InputNRRidPTidPIidPISchemaInput();
207                 createInstanceInput.setNearRtRicId(NEAR_RT_RIC_ID);
208                 createInstanceInput.setPolicyTypeId(Integer.decode(policyTypeIdString));
209                 createInstanceInput.setPolicyInstanceId(policyInstanceId);
210                 createInstanceInput.setPolicyInstance(instance);
211                 InputNRRidPTidPIidPISchema inputSchema = new InputNRRidPTidPIidPISchema();
212                 inputSchema.setInput(createInstanceInput);
213                 OutputCodeSchema outputCodeSchema = a1ControllerApi.a1ControllerCreatePolicyInstance(inputSchema);
214                 checkHttpError(outputCodeSchema.getOutput().getCode());
215         }
216
217         @ApiOperation(value = "Deletes the policy instances for the given policy type.")
218         @DeleteMapping(POLICY_TYPES_METHOD + "/{" + POLICY_TYPE_ID_NAME + "}/" + POLICIES_NAME + "/{"
219                         + POLICY_INSTANCE_ID_NAME + "}")
220         @Secured({ DashboardConstants.ROLE_ADMIN })
221         public void deletePolicyInstance(@PathVariable(POLICY_TYPE_ID_NAME) String policyTypeIdString,
222                         @PathVariable(POLICY_INSTANCE_ID_NAME) String policyInstanceId) {
223                 logger.debug("deletePolicyInstance typeId: {}, instanceId: {}", policyTypeIdString, policyInstanceId);
224                 InputNRRidPTidPIidSchemaInput instanceIdInput = new InputNRRidPTidPIidSchemaInput();
225                 instanceIdInput.setNearRtRicId(NEAR_RT_RIC_ID);
226                 instanceIdInput.setPolicyTypeId(Integer.decode(policyTypeIdString));
227                 instanceIdInput.setPolicyInstanceId(policyInstanceId);
228                 InputNRRidPTidPIidSchema inputSchema = new InputNRRidPTidPIidSchema();
229                 inputSchema.setInput(instanceIdInput);
230                 OutputCodeSchema outputCodeSchema = a1ControllerApi.a1ControllerDeletePolicyInstance(inputSchema);
231                 checkHttpError(outputCodeSchema.getOutput().getCode());
232         }
233
234         private void checkHttpError(String httpCode) {
235             logger.debug("Http Response Code: {}", httpCode);
236             if (httpCode.equals(String.valueOf(HttpStatus.NOT_FOUND.value()))) {
237                 logger.error("Caught HttpNotFoundException");
238                 throw new HttpNotFoundException("Not Found Exception");
239             } else if (httpCode.equals(String.valueOf(HttpStatus.BAD_REQUEST.value()))) {
240                 logger.error("Caught HttpBadRequestException");
241                 throw new HttpBadRequestException("Bad Request Exception");
242             } else if (httpCode.equals(String.valueOf(HttpStatus.INTERNAL_SERVER_ERROR.value()))) {
243                 logger.error("Caught HttpInternalServerErrorException");
244                 throw new HttpInternalServerErrorException("Internal Server Error Exception");
245             } else if (httpCode.equals(String.valueOf(HttpStatus.NOT_IMPLEMENTED.value()))) {
246                 logger.error("Caught HttpNotImplementedException");
247                 throw new HttpNotImplementedException("Not Implemented Exception");
248             }
249         }
250 }