058d4ca973784da698e9e87dd88c20789cddc4b9
[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 database id")
75         public List<Integer> list() {
76                 Iterable<Db> ret = dbRepository.findAll();
77                 List<Integer> retString = new ArrayList<>();
78                 for(Db db : ret)
79                 {
80                         retString.add(db.getId());
81
82                 }
83                 return retString;
84         }
85
86         @GetMapping("/list")
87         @ResponseBody
88         @ApiOperation(value="Get all tools or dbs")
89         public List<DbConfig> dblistByTool(@RequestParam boolean isDb) {
90                 log.info("Search dbs by tool start......");
91                 Iterable<DbType> dbType  = dbTypeRepository.findByTool(!isDb);
92                 List<DbConfig> retDbConfig = new ArrayList<>();
93                 for (DbType item : dbType) {
94                         for (Db d : item.getDbs()) {
95                                 retDbConfig.add(d.getDbConfig());
96                         }
97                 }
98                 return retDbConfig;
99         }
100
101         @GetMapping("/idAndName/{id}")
102         @ResponseBody
103         @ApiOperation(value="Get all databases id and name by designTypeId")
104         public Map<Integer, String> listIdAndName(@PathVariable String id) {
105                 Optional<DesignType> designType  = designTypeRepository.findById(id);
106                 Map<Integer, String> map = new HashMap<>();
107                 if (designType.isPresent()) {
108                         Set<Db> dbs = designType.get().getDbType().getDbs();
109                         for (Db item : dbs) {
110                                 map.put(item.getId(), item.getName());
111                         }
112                 }
113                 return map;
114         }
115
116         //Create a  DB
117         @PostMapping("")
118         @ResponseBody
119         @ApiOperation(value="Create a new database.")
120         public PostReturnBody<DbConfig> createDb(@RequestBody DbConfig dbConfig, BindingResult result, HttpServletResponse response) throws IOException {
121                 if (result.hasErrors()) {
122                         sendError(response, 400, "Malformed format of Post body: " + result.toString());
123                         return null;
124                 }
125
126 /*              Db oldDb = dbService.getDb(dbConfig.getName());
127                 if (oldDb != null) {
128                         sendError(response, 400, "Db already exists: " + dbConfig.getName());
129                         return null;
130                 } else {*/
131                         Db newdb = new Db();
132                         newdb.setName(dbConfig.getName());
133                         newdb.setHost(dbConfig.getHost());
134                         newdb.setPort(dbConfig.getPort());
135                         newdb.setEnabled(dbConfig.isEnabled());
136                         newdb.setLogin(dbConfig.getLogin());
137                         newdb.setPass(dbConfig.getPass());
138                         newdb.setEncrypt(dbConfig.isEncrypt());
139                         if (dbConfig.getDbTypeId().isEmpty()) {
140                 sendError(response, 400, "Malformed format of Post body: " + result.toString());
141             } else {
142                 Optional<DbType> dbType = dbTypeRepository.findById(dbConfig.getDbTypeId());
143                 if (dbType.isPresent()) {
144                     newdb.setDbType(dbType.get());
145                 }
146             }
147
148                         if(!dbConfig.getName().equals("Elecsticsearch") || dbConfig.getName().equals("Druid"))
149                         {
150                                 newdb.setDatabase(dbConfig.getDatabase());
151                         }
152                         dbRepository.save(newdb);
153             log.info("Db save ....... name: " + dbConfig.getName());
154                         DbConfig retMsg;
155                         PostReturnBody<DbConfig> retBody = new PostReturnBody<>();
156                         retMsg = new DbConfig();
157                         composeRetMessagefromDbConfig(newdb, retMsg);
158                         retBody.setReturnBody(retMsg);
159                         retBody.setStatusCode(200);
160                         return retBody;
161                 //}
162         }
163
164         //Show a db
165         //the topics are missing in the return, since in we use @JsonBackReference on Db's topics 
166         //need to the the following method to retrieve the topic list 
167         @GetMapping("/{dbId}")
168         @ResponseBody
169         @ApiOperation(value="Get a database's details.")
170         public DbConfig getDb(@PathVariable("dbId") int dbId, HttpServletResponse response) throws IOException {
171                 Optional<Db> db = dbRepository.findById(dbId);
172                 return db.isPresent() ? db.get().getDbConfig() : null;
173         }
174
175
176         //Delete a db
177         //the topics are missing in the return, since in we use @JsonBackReference on Db's topics
178         //need to the the following method to retrieve the topic list
179         @DeleteMapping("/{id}")
180         @ResponseBody
181         @ApiOperation(value="Delete a database.")
182         public void deleteDb(@PathVariable("id") int id, HttpServletResponse response) throws IOException {
183
184                 Optional<Db> delDb = dbRepository.findById(id);
185                 if (!delDb.isPresent()) {
186                         sendError(response, 404, "Db not found: " + id);
187                         return;
188                 } else {
189             Set<Topic> topicRelation = delDb.get().getTopics();
190             topicRelation.clear();
191             dbRepository.delete(delDb.get());
192             response.setStatus(204);
193         }
194         }
195
196         //Read topics in a DB
197         @GetMapping("/{dbName}/topics")
198         @ResponseBody
199         @ApiOperation(value="Get a database's all topics.")
200         public Set<Topic> getDbTopics(@PathVariable("dbName") String dbName, HttpServletResponse response) throws IOException {
201                 Set<Topic> topics;
202                 try {
203                         Db db = dbRepository.findByName(dbName);
204                         topics = db.getTopics();
205                 } catch(Exception ex) {
206                         sendError(response, 404, "DB: " + dbName + " or Topics not found");
207                         return Collections.emptySet();
208
209                 }
210                 return topics;
211         }
212
213         //Update Db
214         @PutMapping("/{id}")
215         @ResponseBody
216         @ApiOperation(value="Update a database.")
217         public PostReturnBody<DbConfig> updateDb(@PathVariable int id, @RequestBody DbConfig dbConfig, BindingResult result, HttpServletResponse response) throws IOException {
218
219                 if (result.hasErrors()) {
220                         sendError(response, 400, "Error parsing DB: " + result.toString());
221                         return null;
222                 }
223
224                 Db oldDb = dbRepository.findById(id).get();
225                 if (oldDb == null) {
226                         sendError(response, 404, DB_NOT_FOUND + dbConfig.getName());
227                         return null;
228                 } else {
229
230                         oldDb.setEnabled(dbConfig.isEnabled());
231             oldDb.setName(dbConfig.getName());
232             oldDb.setHost(dbConfig.getHost());
233             oldDb.setPort(dbConfig.getPort());
234             oldDb.setLogin(dbConfig.getLogin());
235             oldDb.setPass(dbConfig.getPass());
236             oldDb.setEncrypt(dbConfig.isEncrypt());
237             if (dbConfig.getDbTypeId().isEmpty()) {
238                 sendError(response, 400, "Malformed format of Post body: " + result.toString());
239             } else {
240                 Optional<DbType> dbType = dbTypeRepository.findById(dbConfig.getDbTypeId());
241                 if (dbType.isPresent()) {
242                     oldDb.setDbType(dbType.get());
243                 }
244             }
245                         if (!oldDb.getName().equals("Elecsticsearch") || !oldDb.getName().equals("Druid")) {
246                                 oldDb.setDatabase(dbConfig.getDatabase());
247                         }
248
249                         dbRepository.save(oldDb);
250                         DbConfig retMsg;
251                         PostReturnBody<DbConfig> retBody = new PostReturnBody<>();
252                         retMsg = new DbConfig();
253                         composeRetMessagefromDbConfig(oldDb, retMsg);
254                         retBody.setReturnBody(retMsg);
255                         retBody.setStatusCode(200);
256                         return retBody;
257                 }
258
259         }
260
261
262         @PostMapping("/verify")
263         @ResponseBody
264         @ApiOperation(value="Database connection verification")
265         public PostReturnBody<DbConfig> verifyDbConnection(@RequestBody DbConfig dbConfig, HttpServletResponse response) throws IOException {
266
267                 /*
268                         Not implemented yet.
269                  */
270
271                 response.setStatus(501);
272                 return null;
273         }
274
275         private void composeRetMessagefromDbConfig(Db db, DbConfig dbConfigMsg)
276         {
277         dbConfigMsg.setId(db.getId());
278                 dbConfigMsg.setName(db.getName());
279                 dbConfigMsg.setHost(db.getHost());
280                 dbConfigMsg.setEnabled(db.isEnabled());
281                 dbConfigMsg.setPort(db.getPort());
282                 dbConfigMsg.setLogin(db.getLogin());
283                 dbConfigMsg.setDatabase(db.getDatabase());
284         dbConfigMsg.setDbTypeId(db.getDbType().getId());
285         dbConfigMsg.setPass(db.getPass());
286
287         }
288
289         private void sendError(HttpServletResponse response, int sc, String msg) throws IOException {
290                 log.info(msg);
291                 response.sendError(sc, msg);
292         }
293 }