b677a4051bb0fc9cd16fc4e4c1db75445f409608
[ccsdk/oran.git] /
1 /*-
2  * ========================LICENSE_START=================================
3  * Copyright (C) 2020 Nordix Foundation. All rights reserved.
4  * ======================================================================
5  * Licensed under the Apache License, Version 2.0 (the "License");
6  * you may not use this file except in compliance with the License.
7  * You may obtain a copy of the License at
8  *
9  *      http://www.apache.org/licenses/LICENSE-2.0
10  *
11  * Unless required by applicable law or agreed to in writing, software
12  * distributed under the License is distributed on an "AS IS" BASIS,
13  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14  * See the License for the specific language governing permissions and
15  * limitations under the License.
16  * ========================LICENSE_END===================================
17  */
18
19 package org.onap.ccsdk.oran.a1policymanagementservice.controllers.v2;
20
21 import com.google.gson.Gson;
22 import com.google.gson.GsonBuilder;
23 import com.google.gson.JsonObject;
24 import com.google.gson.JsonParser;
25
26 import io.swagger.v3.oas.annotations.Operation;
27 import io.swagger.v3.oas.annotations.media.Content;
28 import io.swagger.v3.oas.annotations.media.Schema;
29 import io.swagger.v3.oas.annotations.responses.ApiResponse;
30 import io.swagger.v3.oas.annotations.responses.ApiResponses;
31 import io.swagger.v3.oas.annotations.tags.Tag;
32
33 import java.io.IOException;
34 import java.util.Optional;
35
36 import org.onap.ccsdk.oran.a1policymanagementservice.configuration.ApplicationConfigParser;
37 import org.onap.ccsdk.oran.a1policymanagementservice.configuration.ConfigurationFile;
38 import org.onap.ccsdk.oran.a1policymanagementservice.controllers.VoidResponse;
39 import org.onap.ccsdk.oran.a1policymanagementservice.exceptions.ServiceException;
40 import org.onap.ccsdk.oran.a1policymanagementservice.tasks.RefreshConfigTask;
41 import org.slf4j.Logger;
42 import org.slf4j.LoggerFactory;
43 import org.springframework.beans.factory.annotation.Autowired;
44 import org.springframework.http.HttpStatus;
45 import org.springframework.http.MediaType;
46 import org.springframework.http.ResponseEntity;
47 import org.springframework.web.bind.annotation.GetMapping;
48 import org.springframework.web.bind.annotation.PutMapping;
49 import org.springframework.web.bind.annotation.RequestBody;
50 import org.springframework.web.bind.annotation.RestController;
51
52 @RestController("ConfigurationControllerV2")
53 @Tag(name = ConfigurationController.API_NAME)
54 public class ConfigurationController {
55     private static final Logger logger = LoggerFactory.getLogger(ConfigurationController.class);
56
57     public static final String API_NAME = "Management of configuration";
58     public static final String API_DESCRIPTION = "";
59
60     @Autowired
61     ConfigurationFile configurationFile;
62
63     @Autowired
64     RefreshConfigTask refreshConfigTask;
65
66     private static Gson gson = new GsonBuilder() //
67             .create(); //
68
69     @PutMapping(path = Consts.V2_API_ROOT + "/configuration", consumes = MediaType.APPLICATION_JSON_VALUE)
70     @Operation(summary = "Replace the current configuration file with the given configuration", //
71             description = "Note that the file is ignored if the Consul is used.")
72     @ApiResponses(value = { //
73             @ApiResponse(responseCode = "200", //
74                     description = "Configuration updated", //
75                     content = @Content(schema = @Schema(implementation = VoidResponse.class))), //
76             @ApiResponse(responseCode = "400", //
77                     description = "Invalid configuration provided", //
78                     content = @Content(schema = @Schema(implementation = ErrorResponse.ErrorInfo.class))), //
79             @ApiResponse(responseCode = "500", //
80                     description = "Something went wrong when replacing the configuration. Try again.", //
81                     content = @Content(schema = @Schema(implementation = ErrorResponse.ErrorInfo.class))) //
82     })
83     public ResponseEntity<Object> putConfiguration(@RequestBody Object configuration) {
84         try {
85             validateConfigFileIsUsed();
86             String configAsString = gson.toJson(configuration);
87             JsonObject configJson = JsonParser.parseString(configAsString).getAsJsonObject();
88             ApplicationConfigParser configParser = new ApplicationConfigParser();
89             configParser.parse(configJson);
90             configurationFile.writeFile(configJson);
91             logger.info("Configuration changed through REST call.");
92             return new ResponseEntity<>(HttpStatus.OK);
93         } catch (IOException ioe) {
94             logger.warn("Configuration file not written, {}.", ioe.getMessage());
95             return ErrorResponse.create("Internal error when writing the configuration.",
96                     HttpStatus.INTERNAL_SERVER_ERROR);
97         } catch (Exception e) {
98             return ErrorResponse.create(e, HttpStatus.BAD_REQUEST);
99         }
100     }
101
102     @GetMapping(path = Consts.V2_API_ROOT + "/configuration", produces = MediaType.APPLICATION_JSON_VALUE)
103     @Operation(summary = "Returns the contents of the configuration file", //
104             description = "Note that the file contents is not relevant if the Consul is used.") //
105     @ApiResponses(value = { //
106             @ApiResponse(responseCode = "200", //
107                     description = "Configuration", //
108                     content = @Content(schema = @Schema(implementation = Object.class))), //
109             @ApiResponse(responseCode = "404", //
110                     description = "File is not found or readable", //
111                     content = @Content(schema = @Schema(implementation = ErrorResponse.ErrorInfo.class)))
112
113     })
114     public ResponseEntity<Object> getConfiguration() {
115         try {
116             validateConfigFileIsUsed();
117             Optional<JsonObject> rootObject = configurationFile.readFile();
118             if (rootObject.isPresent()) {
119                 return new ResponseEntity<>(rootObject.get().toString(), HttpStatus.OK);
120             } else {
121                 return ErrorResponse.create("File does not exist", HttpStatus.NOT_FOUND);
122             }
123         } catch (Exception e) {
124             return ErrorResponse.create(e, HttpStatus.INTERNAL_SERVER_ERROR);
125         }
126     }
127
128     private void validateConfigFileIsUsed() throws ServiceException {
129         if (this.refreshConfigTask.isConsulUsed()) {
130             throw new ServiceException("Config file not used (Consul is used)", HttpStatus.FORBIDDEN);
131         }
132
133     }
134
135 }