supports multiple Kafka clusters and DBs
[dcaegen2/services.git] / components / datalake-handler / feeder / src / main / java / org / onap / datalake / feeder / controller / DbController.java
1 /*
2 * ============LICENSE_START=======================================================
3 * ONAP : DataLake
4 * ================================================================================
5 * Copyright 2019 China Mobile
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.onap.datalake.feeder.controller;
21
22 import java.io.IOException;
23 import java.util.*;
24
25 import javax.servlet.http.HttpServletResponse;
26
27 import org.onap.datalake.feeder.domain.Db;
28 import org.onap.datalake.feeder.domain.Topic;
29 import org.onap.datalake.feeder.repository.DbRepository;
30 import org.onap.datalake.feeder.dto.DbConfig;
31 import org.onap.datalake.feeder.controller.domain.PostReturnBody;
32 import org.slf4j.Logger;
33 import org.slf4j.LoggerFactory;
34 import org.springframework.beans.factory.annotation.Autowired;
35 import org.springframework.http.MediaType;
36 import org.springframework.validation.BindingResult;
37 import org.springframework.web.bind.annotation.*;
38
39 import io.swagger.annotations.ApiOperation;
40
41 /**
42  * This controller manages the big data storage settings. All the settings are
43  * saved in database.
44  * 
45  * @author Guobiao Mo
46  *
47  */
48
49 @RestController
50 @RequestMapping(value = "/dbs", produces = { MediaType.APPLICATION_JSON_VALUE })
51
52 //@Api(value = "db", consumes = "application/json", produces = "application/json")
53 public class DbController {
54
55         private final Logger log = LoggerFactory.getLogger(this.getClass());
56
57         @Autowired
58         private DbRepository dbRepository;
59
60         //list all dbs 
61         @GetMapping("")
62         @ResponseBody
63         @ApiOperation(value="Gat all databases name")
64         //public Iterable<Db> list() throws IOException {
65         public List<String> list() throws IOException {
66                 Iterable<Db> ret = dbRepository.findAll();
67                 List<String> retString = new ArrayList<>();
68                 for(Db db : ret)
69                 {
70                         log.info(db.getName());
71                         retString.add(db.getName());
72
73                 }
74                 return retString;
75         }
76
77         //Create a  DB
78         @PostMapping("")
79         @ResponseBody
80         @ApiOperation(value="Create a new database.")
81         public PostReturnBody<DbConfig> createDb(@RequestBody DbConfig dbConfig, BindingResult result, HttpServletResponse response) throws IOException {
82                 if (result.hasErrors()) {
83                         sendError(response, 400, "Malformed format of Post body: " + result.toString());
84                         return null;
85                 }
86
87 /*              Db oldDb = dbService.getDb(dbConfig.getName());
88                 if (oldDb != null) {
89                         sendError(response, 400, "Db already exists: " + dbConfig.getName());
90                         return null;
91                 } else {*/
92                         Db newdb = new Db();
93                         newdb.setName(dbConfig.getName());
94                         newdb.setHost(dbConfig.getHost());
95                         newdb.setPort(dbConfig.getPort());
96                         newdb.setEnabled(dbConfig.isEnabled());
97                         newdb.setLogin(dbConfig.getLogin());
98                         newdb.setPass(dbConfig.getPassword());
99                         newdb.setEncrypt(dbConfig.isEncrypt());
100
101                         if(!dbConfig.getName().equals("Elecsticsearch") || !dbConfig.getName().equals("Druid"))
102                         {
103                                 newdb.setDatabase(new String(dbConfig.getDatabase()));
104                         }
105                         dbRepository.save(newdb);
106                         DbConfig retMsg;
107                         PostReturnBody<DbConfig> retBody = new PostReturnBody<>();
108                         retMsg = new DbConfig();
109                         composeRetMessagefromDbConfig(newdb, retMsg);
110                         retBody.setReturnBody(retMsg);
111                         retBody.setStatusCode(200);
112                         return retBody;
113                 //}
114         }
115
116         //Show a db
117         //the topics are missing in the return, since in we use @JsonBackReference on Db's topics 
118         //need to the the following method to retrieve the topic list 
119         @GetMapping("/{dbName}")
120         @ResponseBody
121         @ApiOperation(value="Get a database's details.")
122         public Db getDb(@PathVariable("dbName") String dbName, HttpServletResponse response) throws IOException {
123                 /*Db db = dbService.getDb(dbName);
124                 if (db == null) {
125                         sendError(response, 404, "Db not found: " + dbName);
126                 }*/
127                 Db db = dbRepository.findByName(dbName);
128                 if (db == null) {
129                         sendError(response, 404, "Db not found: " + dbName);
130                 }
131                 return db;
132         }
133
134
135         //Delete a db
136         //the topics are missing in the return, since in we use @JsonBackReference on Db's topics
137         //need to the the following method to retrieve the topic list
138         @DeleteMapping("/{dbName}")
139         @ResponseBody
140         @ApiOperation(value="Delete a database.")
141         public void deleteDb(@PathVariable("dbName") String dbName, HttpServletResponse response) throws IOException {
142
143                 Db delDb = dbRepository.findByName(dbName);
144                 if (delDb == null) {
145                         sendError(response, 404, "Db not found: " + dbName);
146                         return;
147                 }
148                 Set<Topic> topicRelation = delDb.getTopics();
149                 topicRelation.clear();
150                 dbRepository.save(delDb);
151                 dbRepository.delete(delDb);
152                 response.setStatus(204);
153         }
154
155         //Read topics in a DB
156         @GetMapping("/{dbName}/topics")
157         @ResponseBody
158         @ApiOperation(value="Get a database's all topics.")
159         public Set<Topic> getDbTopics(@PathVariable("dbName") String dbName, HttpServletResponse response) throws IOException {
160                 //Db db = dbService.getDb(dbName);
161                 Set<Topic> topics;
162                 try {
163                         Db db = dbRepository.findByName(dbName);
164                         topics = db.getTopics();
165                 }catch(Exception ex)
166                 {
167                         sendError(response, 404, "DB: " + dbName + " or Topics not found");
168                         return null;
169
170                 }
171                 return topics;
172         }
173
174
175         //Update Db
176         @PutMapping("")
177         @ResponseBody
178         @ApiOperation(value="Update a database.")
179         public PostReturnBody<DbConfig> updateDb(@RequestBody DbConfig dbConfig, BindingResult result, HttpServletResponse response) throws IOException {
180
181                 if (result.hasErrors()) {
182                         sendError(response, 400, "Error parsing DB: " + result.toString());
183                         return null;
184                 }
185
186                 Db oldDb = dbRepository.findById(dbConfig.getId()).get();
187                 if (oldDb == null) {
188                         sendError(response, 404, "Db not found: " + dbConfig.getName());
189                         return null;
190                 } else {
191                         oldDb.setHost(dbConfig.getHost());
192                         oldDb.setPort(dbConfig.getPort());
193                         oldDb.setEnabled(dbConfig.isEnabled());
194                         oldDb.setLogin(dbConfig.getLogin());
195                         oldDb.setPass(dbConfig.getPassword());
196                         oldDb.setEncrypt(dbConfig.isEncrypt());
197                         if (!oldDb.getName().equals("Elecsticsearch") || !oldDb.getName().equals("Druid")) {
198                                 oldDb.setDatabase(dbConfig.getDatabase());
199                         }
200
201                         dbRepository.save(oldDb);
202                         DbConfig retMsg;
203                         PostReturnBody<DbConfig> retBody = new PostReturnBody<>();
204                         retMsg = new DbConfig();
205                         composeRetMessagefromDbConfig(oldDb, retMsg);
206                         retBody.setReturnBody(retMsg);
207                         retBody.setStatusCode(200);
208                         return retBody;
209                 }
210
211         }
212
213
214         @PostMapping("/verify")
215         @ResponseBody
216         @ApiOperation(value="Database connection verification")
217         public PostReturnBody<DbConfig> verifyDbConnection(@RequestBody DbConfig dbConfig, HttpServletResponse response) throws IOException {
218
219                 /*
220                         Not implemented yet.
221                  */
222
223                 response.setStatus(501);
224                 return null;
225         }
226
227         private void composeRetMessagefromDbConfig(Db db, DbConfig dbConfigMsg)
228         {
229                 dbConfigMsg.setName(db.getName());
230                 dbConfigMsg.setHost(db.getHost());
231                 dbConfigMsg.setEnabled(db.isEnabled());
232                 dbConfigMsg.setPort(db.getPort());
233                 dbConfigMsg.setLogin(db.getLogin());
234                 dbConfigMsg.setDatabase(db.getDatabase());
235
236
237         }
238
239         private void sendError(HttpServletResponse response, int sc, String msg) throws IOException {
240                 log.info(msg);
241                 response.sendError(sc, msg);
242         }
243 }