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