6d43300d11f041e6de30e3dd33781778f54b7905
[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.DbType;
29 import org.onap.datalake.feeder.domain.DesignType;
30 import org.onap.datalake.feeder.domain.Topic;
31 import org.onap.datalake.feeder.repository.DbRepository;
32 import org.onap.datalake.feeder.dto.DbConfig;
33 import org.onap.datalake.feeder.controller.domain.PostReturnBody;
34 import org.onap.datalake.feeder.repository.DbTypeRepository;
35 import org.onap.datalake.feeder.repository.DesignTypeRepository;
36 import org.slf4j.Logger;
37 import org.slf4j.LoggerFactory;
38 import org.springframework.beans.factory.annotation.Autowired;
39 import org.springframework.http.MediaType;
40 import org.springframework.validation.BindingResult;
41 import org.springframework.web.bind.annotation.*;
42
43 import io.swagger.annotations.ApiOperation;
44
45 /**
46  * This controller manages the big data storage settings. All the settings are
47  * saved in database.
48  *
49  * @author Guobiao Mo
50  *
51  */
52
53 @RestController
54 @RequestMapping(value = "/dbs", produces = { MediaType.APPLICATION_JSON_VALUE })
55
56 //@Api(value = "db", consumes = "application/json", produces = "application/json")
57 public class DbController {
58
59         private final Logger log = LoggerFactory.getLogger(this.getClass());
60         private static final String DB_NOT_FOUND = "Db not found: ";
61
62         @Autowired
63         private DbRepository dbRepository;
64
65     @Autowired
66     private DbTypeRepository dbTypeRepository;
67
68         @Autowired
69         private DesignTypeRepository designTypeRepository;
70
71         //list all dbs
72         @GetMapping("")
73         @ResponseBody
74         @ApiOperation(value="Get all databases name")
75         public List<String> list() {
76                 Iterable<Db> ret = dbRepository.findAll();
77                 List<String> retString = new ArrayList<>();
78                 for(Db db : ret)
79                 {
80                         log.info(db.getName());
81                         retString.add(db.getName());
82
83                 }
84                 return retString;
85         }
86
87         @GetMapping("/list")
88         @ResponseBody
89         @ApiOperation(value="Get all dbs by tool")
90         public List<DbConfig> dblistByTool(@RequestParam boolean tool) {
91                 log.info("Search dbs by tool start......");
92                 Iterable<DbType> dbType  = dbTypeRepository.findByTool(tool);
93                 List<DbConfig> retDbConfig = new ArrayList<>();
94                 for (DbType item : dbType) {
95                         for (Db d : item.getDbs()) {
96                                 retDbConfig.add(d.getDbConfig());
97                         }
98                 }
99                 return retDbConfig;
100         }
101
102         @GetMapping("/idAndName/{id}")
103         @ResponseBody
104         @ApiOperation(value="Get all databases id and name by designTypeId")
105         public Map<Integer, String> listIdAndName(@PathVariable String id) {
106                 Optional<DesignType> designType  = designTypeRepository.findById(id);
107                 Map<Integer, String> map = new HashMap<>();
108                 if (designType.isPresent()) {
109                         Set<Db> dbs = designType.get().getDbType().getDbs();
110                         for (Db item : dbs) {
111                                 map.put(item.getId(), item.getName());
112                         }
113                 }
114                 return map;
115         }
116
117         //Create a  DB
118         @PostMapping("")
119         @ResponseBody
120         @ApiOperation(value="Create a new database.")
121         public PostReturnBody<DbConfig> createDb(@RequestBody DbConfig dbConfig, BindingResult result, HttpServletResponse response) throws IOException {
122                 if (result.hasErrors()) {
123                         sendError(response, 400, "Malformed format of Post body: " + result.toString());
124                         return null;
125                 }
126
127 /*              Db oldDb = dbService.getDb(dbConfig.getName());
128                 if (oldDb != null) {
129                         sendError(response, 400, "Db already exists: " + dbConfig.getName());
130                         return null;
131                 } else {*/
132                         Db newdb = new Db();
133                         newdb.setName(dbConfig.getName());
134                         newdb.setHost(dbConfig.getHost());
135                         newdb.setPort(dbConfig.getPort());
136                         newdb.setEnabled(dbConfig.isEnabled());
137                         newdb.setLogin(dbConfig.getLogin());
138                         newdb.setPass(dbConfig.getPass());
139                         newdb.setEncrypt(dbConfig.isEncrypt());
140                         if (dbConfig.getDbTypeId().isEmpty()) {
141                 sendError(response, 400, "Malformed format of Post body: " + result.toString());
142             } else {
143                 Optional<DbType> dbType = dbTypeRepository.findById(dbConfig.getDbTypeId());
144                 if (dbType.isPresent()) {
145                     newdb.setDbType(dbType.get());
146                 }
147             }
148
149                         if(!dbConfig.getName().equals("Elecsticsearch") || dbConfig.getName().equals("Druid"))
150                         {
151                                 newdb.setDatabase(new String(dbConfig.getDatabase()));
152                         }
153                         dbRepository.save(newdb);
154             log.info("Db save ....... name: " + dbConfig.getName());
155                         DbConfig retMsg;
156                         PostReturnBody<DbConfig> retBody = new PostReturnBody<>();
157                         retMsg = new DbConfig();
158                         composeRetMessagefromDbConfig(newdb, retMsg);
159                         retBody.setReturnBody(retMsg);
160                         retBody.setStatusCode(200);
161                         return retBody;
162                 //}
163         }
164
165         //Show a db
166         //the topics are missing in the return, since in we use @JsonBackReference on Db's topics 
167         //need to the the following method to retrieve the topic list 
168         @GetMapping("/{dbName}")
169         @ResponseBody
170         @ApiOperation(value="Get a database's details.")
171         public Db getDb(@PathVariable("dbName") String dbName, HttpServletResponse response) throws IOException {
172                 Db db = dbRepository.findByName(dbName);
173                 if (db == null) {
174                         sendError(response, 404, DB_NOT_FOUND + dbName);
175                 }
176                 return db;
177         }
178
179
180         //Delete a db
181         //the topics are missing in the return, since in we use @JsonBackReference on Db's topics
182         //need to the the following method to retrieve the topic list
183         @DeleteMapping("/{id}")
184         @ResponseBody
185         @ApiOperation(value="Delete a database.")
186         public void deleteDb(@PathVariable("id") int id, HttpServletResponse response) throws IOException {
187
188                 Optional<Db> delDb = dbRepository.findById(id);
189                 if (!delDb.isPresent()) {
190                         sendError(response, 404, "Db not found: " + id);
191                         return;
192                 } else {
193             Set<Topic> topicRelation = delDb.get().getTopics();
194             topicRelation.clear();
195             dbRepository.delete(delDb.get());
196             response.setStatus(204);
197         }
198         }
199
200         //Read topics in a DB
201         @GetMapping("/{dbName}/topics")
202         @ResponseBody
203         @ApiOperation(value="Get a database's all topics.")
204         public Set<Topic> getDbTopics(@PathVariable("dbName") String dbName, HttpServletResponse response) throws IOException {
205                 Set<Topic> topics;
206                 try {
207                         Db db = dbRepository.findByName(dbName);
208                         topics = db.getTopics();
209                 } catch(Exception ex) {
210                         sendError(response, 404, "DB: " + dbName + " or Topics not found");
211                         return Collections.emptySet();
212
213                 }
214                 return topics;
215         }
216
217         //Update Db
218         @PutMapping("")
219         @ResponseBody
220         @ApiOperation(value="Update a database.")
221         public PostReturnBody<DbConfig> updateDb(@RequestBody DbConfig dbConfig, BindingResult result, HttpServletResponse response) throws IOException {
222
223                 if (result.hasErrors()) {
224                         sendError(response, 400, "Error parsing DB: " + result.toString());
225                         return null;
226                 }
227
228                 Db oldDb = dbRepository.findById(dbConfig.getId()).get();
229                 if (oldDb == null) {
230                         sendError(response, 404, DB_NOT_FOUND + dbConfig.getName());
231                         return null;
232                 } else {
233
234                         oldDb.setEnabled(dbConfig.isEnabled());
235             oldDb.setName(dbConfig.getName());
236             oldDb.setHost(dbConfig.getHost());
237             oldDb.setPort(dbConfig.getPort());
238             oldDb.setLogin(dbConfig.getLogin());
239             oldDb.setPass(dbConfig.getPass());
240             oldDb.setEncrypt(dbConfig.isEncrypt());
241             if (dbConfig.getDbTypeId().isEmpty()) {
242                 sendError(response, 400, "Malformed format of Post body: " + result.toString());
243             } else {
244                 Optional<DbType> dbType = dbTypeRepository.findById(dbConfig.getDbTypeId());
245                 if (dbType.isPresent()) {
246                     oldDb.setDbType(dbType.get());
247                 }
248             }
249                         if (!oldDb.getName().equals("Elecsticsearch") || !oldDb.getName().equals("Druid")) {
250                                 oldDb.setDatabase(dbConfig.getDatabase());
251                         }
252
253                         dbRepository.save(oldDb);
254                         DbConfig retMsg;
255                         PostReturnBody<DbConfig> retBody = new PostReturnBody<>();
256                         retMsg = new DbConfig();
257                         composeRetMessagefromDbConfig(oldDb, retMsg);
258                         retBody.setReturnBody(retMsg);
259                         retBody.setStatusCode(200);
260                         return retBody;
261                 }
262
263         }
264
265
266         @PostMapping("/verify")
267         @ResponseBody
268         @ApiOperation(value="Database connection verification")
269         public PostReturnBody<DbConfig> verifyDbConnection(@RequestBody DbConfig dbConfig, HttpServletResponse response) throws IOException {
270
271                 /*
272                         Not implemented yet.
273                  */
274
275                 response.setStatus(501);
276                 return null;
277         }
278
279         private void composeRetMessagefromDbConfig(Db db, DbConfig dbConfigMsg)
280         {
281         dbConfigMsg.setId(db.getId());
282                 dbConfigMsg.setName(db.getName());
283                 dbConfigMsg.setHost(db.getHost());
284                 dbConfigMsg.setEnabled(db.isEnabled());
285                 dbConfigMsg.setPort(db.getPort());
286                 dbConfigMsg.setLogin(db.getLogin());
287                 dbConfigMsg.setDatabase(db.getDatabase());
288         dbConfigMsg.setDbTypeId(db.getDbType().getId());
289         dbConfigMsg.setPass(db.getPass());
290
291         }
292
293         private void sendError(HttpServletResponse response, int sc, String msg) throws IOException {
294                 log.info(msg);
295                 response.sendError(sc, msg);
296         }
297 }