summaryrefslogtreecommitdiffstats
path: root/components/datalake-handler/feeder/src/main/java/org/onap/datalake/feeder/controller/DbController.java
blob: 49439e6036d94dd2ec326df6a6576756c928d5c4 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
/*
* ============LICENSE_START=======================================================
* ONAP : DataLake
* ================================================================================
* Copyright 2019 China Mobile
*=================================================================================
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
*     http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* ============LICENSE_END=========================================================
*/
package org.onap.datalake.feeder.controller;

import java.io.IOException;
import java.util.*;

import javax.servlet.http.HttpServletResponse;

import org.onap.datalake.feeder.domain.Db;
import org.onap.datalake.feeder.domain.DbType;
import org.onap.datalake.feeder.domain.DesignType;
import org.onap.datalake.feeder.domain.Topic;
import org.onap.datalake.feeder.repository.DbRepository;
import org.onap.datalake.feeder.dto.DbConfig;
import org.onap.datalake.feeder.controller.domain.PostReturnBody;
import org.onap.datalake.feeder.repository.DbTypeRepository;
import org.onap.datalake.feeder.repository.DesignTypeRepository;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.MediaType;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.*;

import io.swagger.annotations.ApiOperation;

/**
 * This controller manages the big data storage settings. All the settings are
 * saved in database.
 *
 * @author Guobiao Mo
 *
 */

@RestController
@RequestMapping(value = "/dbs", produces = { MediaType.APPLICATION_JSON_VALUE })

//@Api(value = "db", consumes = "application/json", produces = "application/json")
public class DbController {

	private final Logger log = LoggerFactory.getLogger(this.getClass());
	private static final String DB_NOT_FOUND = "Db not found: ";

	@Autowired
	private DbRepository dbRepository;

    @Autowired
    private DbTypeRepository dbTypeRepository;

	@Autowired
	private DesignTypeRepository designTypeRepository;

	//list all dbs
	@GetMapping("")
	@ResponseBody
	@ApiOperation(value="Get all database id")
	public List<Integer> list() {
		Iterable<Db> ret = dbRepository.findAll();
		List<Integer> retString = new ArrayList<>();
		for(Db db : ret)
		{
			retString.add(db.getId());

		}
		return retString;
	}

	@GetMapping("/list")
	@ResponseBody
	@ApiOperation(value="Get all tools or dbs")
	public List<DbConfig> dblistByTool(@RequestParam boolean isDb) {
		log.info("Search dbs by tool start......");
		Iterable<DbType> dbType  = dbTypeRepository.findByTool(!isDb);
		List<DbConfig> retDbConfig = new ArrayList<>();
		for (DbType item : dbType) {
			for (Db d : item.getDbs()) {
				retDbConfig.add(d.getDbConfig());
			}
		}
		return retDbConfig;
	}

	@GetMapping("/idAndName/{id}")
	@ResponseBody
	@ApiOperation(value="Get all databases id and name by designTypeId")
	public Map<Integer, String> listIdAndName(@PathVariable String id) {
		Optional<DesignType> designType  = designTypeRepository.findById(id);
		Map<Integer, String> map = new HashMap<>();
		if (designType.isPresent()) {
			Set<Db> dbs = designType.get().getDbType().getDbs();
			for (Db item : dbs) {
				map.put(item.getId(), item.getName());
			}
		}
		return map;
	}

	//Create a  DB
	@PostMapping("")
	@ResponseBody
	@ApiOperation(value="Create a new database.")
	public PostReturnBody<DbConfig> createDb(@RequestBody DbConfig dbConfig, BindingResult result, HttpServletResponse response) throws IOException {
		if (result.hasErrors()) {
			sendError(response, 400, "Malformed format of Post body: " + result.toString());
			return null;
		}

/*		Db oldDb = dbService.getDb(dbConfig.getName());
		if (oldDb != null) {
			sendError(response, 400, "Db already exists: " + dbConfig.getName());
			return null;
		} else {*/
			Db newdb = new Db();
			newdb.setName(dbConfig.getName());
			newdb.setHost(dbConfig.getHost());
			newdb.setPort(dbConfig.getPort());
			newdb.setEnabled(dbConfig.isEnabled());
			newdb.setLogin(dbConfig.getLogin());
			newdb.setPass(dbConfig.getPass());
			newdb.setEncrypt(dbConfig.isEncrypt());
			if (dbConfig.getDbTypeId().isEmpty()) {
                sendError(response, 400, "Malformed format of Post body: " + result.toString());
            } else {
                Optional<DbType> dbType = dbTypeRepository.findById(dbConfig.getDbTypeId());
                if (dbType.isPresent()) {
                    newdb.setDbType(dbType.get());
                }
            }

			if(!dbConfig.getName().equals("Elecsticsearch") || dbConfig.getName().equals("Druid"))
			{
				newdb.setDatabase(dbConfig.getDatabase());
			}
			dbRepository.save(newdb);
            log.info("Db save ....... name: " + dbConfig.getName());
			DbConfig retMsg;
			PostReturnBody<DbConfig> retBody = new PostReturnBody<>();
			retMsg = new DbConfig();
			composeRetMessagefromDbConfig(newdb, retMsg);
			retBody.setReturnBody(retMsg);
			retBody.setStatusCode(200);
			return retBody;
		//}
	}

	//Show a db
	//the topics are missing in the return, since in we use @JsonBackReference on Db's topics 
	//need to the the following method to retrieve the topic list 
	@GetMapping("/{dbId}")
	@ResponseBody
	@ApiOperation(value="Get a database's details.")
	public DbConfig getDb(@PathVariable("dbId") int dbId, HttpServletResponse response) throws IOException {
  		Optional<Db> db = dbRepository.findById(dbId);
  		return db.isPresent() ? db.get().getDbConfig() : null;
 	}


	//Delete a db
	//the topics are missing in the return, since in we use @JsonBackReference on Db's topics
	//need to the the following method to retrieve the topic list
	@DeleteMapping("/{id}")
	@ResponseBody
	@ApiOperation(value="Delete a database.")
	public void deleteDb(@PathVariable("id") int id, HttpServletResponse response) throws IOException {

		Optional<Db> delDb = dbRepository.findById(id);
		if (!delDb.isPresent()) {
			sendError(response, 404, "Db not found: " + id);
			return;
		} else {
            Set<Topic> topicRelation = delDb.get().getTopics();
            topicRelation.clear();
            dbRepository.delete(delDb.get());
            response.setStatus(204);
        }
	}

	//Read topics in a DB
	@GetMapping("/{dbName}/topics")
	@ResponseBody
	@ApiOperation(value="Get a database's all topics.")
	public Set<Topic> getDbTopics(@PathVariable("dbName") String dbName, HttpServletResponse response) throws IOException {
		Set<Topic> topics;
		try {
			Db db = dbRepository.findByName(dbName);
			topics = db.getTopics();
		} catch(Exception ex) {
			sendError(response, 404, "DB: " + dbName + " or Topics not found");
			return Collections.emptySet();

		}
		return topics;
	}

	//Update Db
	@PutMapping("")
	@ResponseBody
	@ApiOperation(value="Update a database.")
	public PostReturnBody<DbConfig> updateDb(@RequestBody DbConfig dbConfig, BindingResult result, HttpServletResponse response) throws IOException {

		if (result.hasErrors()) {
			sendError(response, 400, "Error parsing DB: " + result.toString());
			return null;
		}

		Db oldDb = dbRepository.findById(dbConfig.getId()).get();
		if (oldDb == null) {
			sendError(response, 404, DB_NOT_FOUND + dbConfig.getName());
			return null;
		} else {

			oldDb.setEnabled(dbConfig.isEnabled());
            oldDb.setName(dbConfig.getName());
            oldDb.setHost(dbConfig.getHost());
            oldDb.setPort(dbConfig.getPort());
            oldDb.setLogin(dbConfig.getLogin());
            oldDb.setPass(dbConfig.getPass());
            oldDb.setEncrypt(dbConfig.isEncrypt());
            if (dbConfig.getDbTypeId().isEmpty()) {
                sendError(response, 400, "Malformed format of Post body: " + result.toString());
            } else {
                Optional<DbType> dbType = dbTypeRepository.findById(dbConfig.getDbTypeId());
                if (dbType.isPresent()) {
                    oldDb.setDbType(dbType.get());
                }
            }
			if (!oldDb.getName().equals("Elecsticsearch") || !oldDb.getName().equals("Druid")) {
				oldDb.setDatabase(dbConfig.getDatabase());
			}

			dbRepository.save(oldDb);
			DbConfig retMsg;
			PostReturnBody<DbConfig> retBody = new PostReturnBody<>();
			retMsg = new DbConfig();
			composeRetMessagefromDbConfig(oldDb, retMsg);
			retBody.setReturnBody(retMsg);
			retBody.setStatusCode(200);
			return retBody;
		}

	}


	@PostMapping("/verify")
	@ResponseBody
	@ApiOperation(value="Database connection verification")
	public PostReturnBody<DbConfig> verifyDbConnection(@RequestBody DbConfig dbConfig, HttpServletResponse response) throws IOException {

		/*
			Not implemented yet.
		 */

		response.setStatus(501);
		return null;
	}

	private void composeRetMessagefromDbConfig(Db db, DbConfig dbConfigMsg)
	{
        dbConfigMsg.setId(db.getId());
		dbConfigMsg.setName(db.getName());
		dbConfigMsg.setHost(db.getHost());
		dbConfigMsg.setEnabled(db.isEnabled());
		dbConfigMsg.setPort(db.getPort());
		dbConfigMsg.setLogin(db.getLogin());
		dbConfigMsg.setDatabase(db.getDatabase());
        dbConfigMsg.setDbTypeId(db.getDbType().getId());
        dbConfigMsg.setPass(db.getPass());

	}

	private void sendError(HttpServletResponse response, int sc, String msg) throws IOException {
		log.info(msg);
		response.sendError(sc, msg);
	}
}