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