f177a9acb466658567f1055e6a08ec62a7592f5a
[dcaegen2/services.git] /
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         @GetMapping("/idAndName")
78         @ResponseBody
79         @ApiOperation(value="Gat all databases id and name")
80         public Map<Integer, String> listIdAndName() {
81                 Iterable<Db> ret = dbRepository.findAll();
82                 Map<Integer, String> map = new HashMap<>();
83                 for(Db db : ret)
84                 {
85                         log.info(db.getId() + "\t"+ db.getName());
86                         map.put(db.getId(), db.getName());
87                 }
88                 return map;
89         }
90
91         //Create a  DB
92         @PostMapping("")
93         @ResponseBody
94         @ApiOperation(value="Create a new database.")
95         public PostReturnBody<DbConfig> createDb(@RequestBody DbConfig dbConfig, BindingResult result, HttpServletResponse response) throws IOException {
96                 if (result.hasErrors()) {
97                         sendError(response, 400, "Malformed format of Post body: " + result.toString());
98                         return null;
99                 }
100
101 /*              Db oldDb = dbService.getDb(dbConfig.getName());
102                 if (oldDb != null) {
103                         sendError(response, 400, "Db already exists: " + dbConfig.getName());
104                         return null;
105                 } else {*/
106                         Db newdb = new Db();
107                         newdb.setName(dbConfig.getName());
108                         newdb.setHost(dbConfig.getHost());
109                         newdb.setPort(dbConfig.getPort());
110                         newdb.setEnabled(dbConfig.isEnabled());
111                         newdb.setLogin(dbConfig.getLogin());
112                         newdb.setPass(dbConfig.getPassword());
113                         newdb.setEncrypt(dbConfig.isEncrypt());
114
115                         if(!dbConfig.getName().equals("Elecsticsearch") || !dbConfig.getName().equals("Druid"))
116                         {
117                                 newdb.setDatabase(new String(dbConfig.getDatabase()));
118                         }
119                         dbRepository.save(newdb);
120                         DbConfig retMsg;
121                         PostReturnBody<DbConfig> retBody = new PostReturnBody<>();
122                         retMsg = new DbConfig();
123                         composeRetMessagefromDbConfig(newdb, retMsg);
124                         retBody.setReturnBody(retMsg);
125                         retBody.setStatusCode(200);
126                         return retBody;
127                 //}
128         }
129
130         //Show a db
131         //the topics are missing in the return, since in we use @JsonBackReference on Db's topics 
132         //need to the the following method to retrieve the topic list 
133         @GetMapping("/{dbName}")
134         @ResponseBody
135         @ApiOperation(value="Get a database's details.")
136         public Db getDb(@PathVariable("dbName") String dbName, HttpServletResponse response) throws IOException {
137                 /*Db db = dbService.getDb(dbName);
138                 if (db == null) {
139                         sendError(response, 404, "Db not found: " + dbName);
140                 }*/
141                 Db db = dbRepository.findByName(dbName);
142                 if (db == null) {
143                         sendError(response, 404, "Db not found: " + dbName);
144                 }
145                 return db;
146         }
147
148
149         //Delete a db
150         //the topics are missing in the return, since in we use @JsonBackReference on Db's topics
151         //need to the the following method to retrieve the topic list
152         @DeleteMapping("/{dbName}")
153         @ResponseBody
154         @ApiOperation(value="Delete a database.")
155         public void deleteDb(@PathVariable("dbName") String dbName, HttpServletResponse response) throws IOException {
156
157                 Db delDb = dbRepository.findByName(dbName);
158                 if (delDb == null) {
159                         sendError(response, 404, "Db not found: " + dbName);
160                         return;
161                 }
162                 Set<Topic> topicRelation = delDb.getTopics();
163                 topicRelation.clear();
164                 dbRepository.save(delDb);
165                 dbRepository.delete(delDb);
166                 response.setStatus(204);
167         }
168
169         //Read topics in a DB
170         @GetMapping("/{dbName}/topics")
171         @ResponseBody
172         @ApiOperation(value="Get a database's all topics.")
173         public Set<Topic> getDbTopics(@PathVariable("dbName") String dbName, HttpServletResponse response) throws IOException {
174                 //Db db = dbService.getDb(dbName);
175                 Set<Topic> topics;
176                 try {
177                         Db db = dbRepository.findByName(dbName);
178                         topics = db.getTopics();
179                 }catch(Exception ex)
180                 {
181                         sendError(response, 404, "DB: " + dbName + " or Topics not found");
182                         return null;
183
184                 }
185                 return topics;
186         }
187
188
189         //Update Db
190         @PutMapping("")
191         @ResponseBody
192         @ApiOperation(value="Update a database.")
193         public PostReturnBody<DbConfig> updateDb(@RequestBody DbConfig dbConfig, BindingResult result, HttpServletResponse response) throws IOException {
194
195                 if (result.hasErrors()) {
196                         sendError(response, 400, "Error parsing DB: " + result.toString());
197                         return null;
198                 }
199
200                 Db oldDb = dbRepository.findById(dbConfig.getId()).get();
201                 if (oldDb == null) {
202                         sendError(response, 404, "Db not found: " + dbConfig.getName());
203                         return null;
204                 } else {
205                         oldDb.setHost(dbConfig.getHost());
206                         oldDb.setPort(dbConfig.getPort());
207                         oldDb.setEnabled(dbConfig.isEnabled());
208                         oldDb.setLogin(dbConfig.getLogin());
209                         oldDb.setPass(dbConfig.getPassword());
210                         oldDb.setEncrypt(dbConfig.isEncrypt());
211                         if (!oldDb.getName().equals("Elecsticsearch") || !oldDb.getName().equals("Druid")) {
212                                 oldDb.setDatabase(dbConfig.getDatabase());
213                         }
214
215                         dbRepository.save(oldDb);
216                         DbConfig retMsg;
217                         PostReturnBody<DbConfig> retBody = new PostReturnBody<>();
218                         retMsg = new DbConfig();
219                         composeRetMessagefromDbConfig(oldDb, retMsg);
220                         retBody.setReturnBody(retMsg);
221                         retBody.setStatusCode(200);
222                         return retBody;
223                 }
224
225         }
226
227
228         @PostMapping("/verify")
229         @ResponseBody
230         @ApiOperation(value="Database connection verification")
231         public PostReturnBody<DbConfig> verifyDbConnection(@RequestBody DbConfig dbConfig, HttpServletResponse response) throws IOException {
232
233                 /*
234                         Not implemented yet.
235                  */
236
237                 response.setStatus(501);
238                 return null;
239         }
240
241         private void composeRetMessagefromDbConfig(Db db, DbConfig dbConfigMsg)
242         {
243                 dbConfigMsg.setName(db.getName());
244                 dbConfigMsg.setHost(db.getHost());
245                 dbConfigMsg.setEnabled(db.isEnabled());
246                 dbConfigMsg.setPort(db.getPort());
247                 dbConfigMsg.setLogin(db.getLogin());
248                 dbConfigMsg.setDatabase(db.getDatabase());
249
250
251         }
252
253         private void sendError(HttpServletResponse response, int sc, String msg) throws IOException {
254                 log.info(msg);
255                 response.sendError(sc, msg);
256         }
257 }