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