forked from Cepr0/sb-multitenant-db-demo
-
Notifications
You must be signed in to change notification settings - Fork 0
/
TenantController.java
60 lines (49 loc) · 1.73 KB
/
TenantController.java
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
package io.github.cepr0.demo.controller;
import io.github.cepr0.demo.exception.InvalidDbPropertiesException;
import io.github.cepr0.demo.exception.LoadDataSourceException;
import io.github.cepr0.demo.multitenant.MultiTenantManager;
import lombok.extern.slf4j.Slf4j;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
import java.sql.SQLException;
import java.util.Map;
@Slf4j
@RestController
@RequestMapping("/tenants")
public class TenantController {
private final MultiTenantManager tenantManager;
public TenantController(MultiTenantManager tenantManager) {
this.tenantManager = tenantManager;
}
/**
* Get list of all tenants in the local storage
*/
@GetMapping
public ResponseEntity<?> getAll() {
return ResponseEntity.ok(tenantManager.getTenantList());
}
/**
* Add the new tenant on the fly
*
* @param dbProperty Map with tenantId and related datasource properties
*/
@PostMapping
public ResponseEntity<?> add(@RequestBody Map<String, String> dbProperty) {
log.info("[i] Received add new tenant params request {}", dbProperty);
String tenantId = dbProperty.get("tenantId");
String url = dbProperty.get("url");
String username = dbProperty.get("username");
String password = dbProperty.get("password");
if (tenantId == null || url == null || username == null || password == null) {
log.error("[!] Received database params are incorrect or not full!");
throw new InvalidDbPropertiesException();
}
try {
tenantManager.addTenant(tenantId, url, username, password);
log.info("[i] Loaded DataSource for tenant '{}'.", tenantId);
return ResponseEntity.ok(dbProperty);
} catch (SQLException e) {
throw new LoadDataSourceException(e);
}
}
}