Commit a2dd90a4c2f10e9c4208683b2832941e5300a622

Authored by Andrew Shvayka
1 parent 104450c1

Refactoring of app layer to support tenant level rate limits

Showing 58 changed files with 318 additions and 297 deletions
@@ -123,7 +123,7 @@ class DeviceActorMessageProcessor extends AbstractContextAwareMsgProcessor { @@ -123,7 +123,7 @@ class DeviceActorMessageProcessor extends AbstractContextAwareMsgProcessor {
123 } 123 }
124 124
125 private void initAttributes() { 125 private void initAttributes() {
126 - Device device = systemContext.getDeviceService().findDeviceById(deviceId); 126 + Device device = systemContext.getDeviceService().findDeviceById(tenantId, deviceId);
127 this.deviceName = device.getName(); 127 this.deviceName = device.getName();
128 this.deviceType = device.getType(); 128 this.deviceType = device.getType();
129 this.defaultMetaData = new TbMsgMetaData(); 129 this.defaultMetaData = new TbMsgMetaData();
@@ -290,9 +290,9 @@ class DeviceActorMessageProcessor extends AbstractContextAwareMsgProcessor { @@ -290,9 +290,9 @@ class DeviceActorMessageProcessor extends AbstractContextAwareMsgProcessor {
290 private ListenableFuture<List<AttributeKvEntry>> getAttributeKvEntries(DeviceId deviceId, String scope, Optional<Set<String>> names) { 290 private ListenableFuture<List<AttributeKvEntry>> getAttributeKvEntries(DeviceId deviceId, String scope, Optional<Set<String>> names) {
291 if (names.isPresent()) { 291 if (names.isPresent()) {
292 if (!names.get().isEmpty()) { 292 if (!names.get().isEmpty()) {
293 - return systemContext.getAttributesService().find(deviceId, scope, names.get()); 293 + return systemContext.getAttributesService().find(tenantId, deviceId, scope, names.get());
294 } else { 294 } else {
295 - return systemContext.getAttributesService().findAll(deviceId, scope); 295 + return systemContext.getAttributesService().findAll(tenantId, deviceId, scope);
296 } 296 }
297 } else { 297 } else {
298 return Futures.immediateFuture(Collections.emptyList()); 298 return Futures.immediateFuture(Collections.emptyList());
@@ -90,9 +90,9 @@ public class RuleChainActorMessageProcessor extends ComponentMsgProcessor<RuleCh @@ -90,9 +90,9 @@ public class RuleChainActorMessageProcessor extends ComponentMsgProcessor<RuleCh
90 @Override 90 @Override
91 public void start(ActorContext context) { 91 public void start(ActorContext context) {
92 if (!started) { 92 if (!started) {
93 - RuleChain ruleChain = service.findRuleChainById(entityId); 93 + RuleChain ruleChain = service.findRuleChainById(tenantId, entityId);
94 ruleChainName = ruleChain.getName(); 94 ruleChainName = ruleChain.getName();
95 - List<RuleNode> ruleNodeList = service.getRuleChainNodes(entityId); 95 + List<RuleNode> ruleNodeList = service.getRuleChainNodes(tenantId, entityId);
96 log.trace("[{}][{}] Starting rule chain with {} nodes", tenantId, entityId, ruleNodeList.size()); 96 log.trace("[{}][{}] Starting rule chain with {} nodes", tenantId, entityId, ruleNodeList.size());
97 // Creating and starting the actors; 97 // Creating and starting the actors;
98 for (RuleNode ruleNode : ruleNodeList) { 98 for (RuleNode ruleNode : ruleNodeList) {
@@ -109,9 +109,9 @@ public class RuleChainActorMessageProcessor extends ComponentMsgProcessor<RuleCh @@ -109,9 +109,9 @@ public class RuleChainActorMessageProcessor extends ComponentMsgProcessor<RuleCh
109 109
110 @Override 110 @Override
111 public void onUpdate(ActorContext context) { 111 public void onUpdate(ActorContext context) {
112 - RuleChain ruleChain = service.findRuleChainById(entityId); 112 + RuleChain ruleChain = service.findRuleChainById(tenantId, entityId);
113 ruleChainName = ruleChain.getName(); 113 ruleChainName = ruleChain.getName();
114 - List<RuleNode> ruleNodeList = service.getRuleChainNodes(entityId); 114 + List<RuleNode> ruleNodeList = service.getRuleChainNodes(tenantId, entityId);
115 log.trace("[{}][{}] Updating rule chain with {} nodes", tenantId, entityId, ruleNodeList.size()); 115 log.trace("[{}][{}] Updating rule chain with {} nodes", tenantId, entityId, ruleNodeList.size());
116 for (RuleNode ruleNode : ruleNodeList) { 116 for (RuleNode ruleNode : ruleNodeList) {
117 RuleNodeCtx existing = nodeActors.get(ruleNode.getId()); 117 RuleNodeCtx existing = nodeActors.get(ruleNode.getId());
@@ -164,7 +164,7 @@ public class RuleChainActorMessageProcessor extends ComponentMsgProcessor<RuleCh @@ -164,7 +164,7 @@ public class RuleChainActorMessageProcessor extends ComponentMsgProcessor<RuleCh
164 nodeRoutes.clear(); 164 nodeRoutes.clear();
165 // Populating the routes map; 165 // Populating the routes map;
166 for (RuleNode ruleNode : ruleNodeList) { 166 for (RuleNode ruleNode : ruleNodeList) {
167 - List<EntityRelation> relations = service.getRuleNodeRelations(ruleNode.getId()); 167 + List<EntityRelation> relations = service.getRuleNodeRelations(TenantId.SYS_TENANT_ID, ruleNode.getId());
168 log.trace("[{}][{}][{}] Processing rule node relations [{}]", tenantId, entityId, ruleNode.getId(), relations.size()); 168 log.trace("[{}][{}][{}] Processing rule node relations [{}]", tenantId, entityId, ruleNode.getId(), relations.size());
169 if (relations.size() == 0) { 169 if (relations.size() == 0) {
170 nodeRoutes.put(ruleNode.getId(), Collections.emptyList()); 170 nodeRoutes.put(ruleNode.getId(), Collections.emptyList());
@@ -49,7 +49,7 @@ public class RuleNodeActorMessageProcessor extends ComponentMsgProcessor<RuleNod @@ -49,7 +49,7 @@ public class RuleNodeActorMessageProcessor extends ComponentMsgProcessor<RuleNod
49 this.parent = parent; 49 this.parent = parent;
50 this.self = self; 50 this.self = self;
51 this.service = systemContext.getRuleChainService(); 51 this.service = systemContext.getRuleChainService();
52 - this.ruleNode = systemContext.getRuleChainService().findRuleNodeById(entityId); 52 + this.ruleNode = systemContext.getRuleChainService().findRuleNodeById(tenantId, entityId);
53 this.defaultCtx = new DefaultTbContext(systemContext, new RuleNodeCtx(tenantId, parent, self, ruleNode)); 53 this.defaultCtx = new DefaultTbContext(systemContext, new RuleNodeCtx(tenantId, parent, self, ruleNode));
54 } 54 }
55 55
@@ -61,7 +61,7 @@ public class RuleNodeActorMessageProcessor extends ComponentMsgProcessor<RuleNod @@ -61,7 +61,7 @@ public class RuleNodeActorMessageProcessor extends ComponentMsgProcessor<RuleNod
61 61
62 @Override 62 @Override
63 public void onUpdate(ActorContext context) throws Exception { 63 public void onUpdate(ActorContext context) throws Exception {
64 - RuleNode newRuleNode = systemContext.getRuleChainService().findRuleNodeById(entityId); 64 + RuleNode newRuleNode = systemContext.getRuleChainService().findRuleNodeById(tenantId, entityId);
65 boolean restartRequired = !(ruleNode.getType().equals(newRuleNode.getType()) 65 boolean restartRequired = !(ruleNode.getType().equals(newRuleNode.getType())
66 && ruleNode.getConfiguration().equals(newRuleNode.getConfiguration())); 66 && ruleNode.getConfiguration().equals(newRuleNode.getConfiguration()));
67 this.ruleNode = newRuleNode; 67 this.ruleNode = newRuleNode;
@@ -143,7 +143,7 @@ public class TenantActor extends RuleChainManagerActor { @@ -143,7 +143,7 @@ public class TenantActor extends RuleChainManagerActor {
143 if (target != null) { 143 if (target != null) {
144 if (msg.getEntityId().getEntityType() == EntityType.RULE_CHAIN) { 144 if (msg.getEntityId().getEntityType() == EntityType.RULE_CHAIN) {
145 RuleChain ruleChain = systemContext.getRuleChainService(). 145 RuleChain ruleChain = systemContext.getRuleChainService().
146 - findRuleChainById(new RuleChainId(msg.getEntityId().getId())); 146 + findRuleChainById(tenantId, new RuleChainId(msg.getEntityId().getId()));
147 ruleChainManager.visit(ruleChain, target); 147 ruleChainManager.visit(ruleChain, target);
148 } 148 }
149 target.tell(msg, ActorRef.noSender()); 149 target.tell(msg, ActorRef.noSender());
@@ -26,6 +26,7 @@ import org.springframework.web.bind.annotation.RestController; @@ -26,6 +26,7 @@ import org.springframework.web.bind.annotation.RestController;
26 import org.thingsboard.rule.engine.api.MailService; 26 import org.thingsboard.rule.engine.api.MailService;
27 import org.thingsboard.server.common.data.AdminSettings; 27 import org.thingsboard.server.common.data.AdminSettings;
28 import org.thingsboard.server.common.data.exception.ThingsboardException; 28 import org.thingsboard.server.common.data.exception.ThingsboardException;
  29 +import org.thingsboard.server.common.data.id.TenantId;
29 import org.thingsboard.server.dao.settings.AdminSettingsService; 30 import org.thingsboard.server.dao.settings.AdminSettingsService;
30 import org.thingsboard.server.service.update.UpdateService; 31 import org.thingsboard.server.service.update.UpdateService;
31 import org.thingsboard.server.service.update.model.UpdateMessage; 32 import org.thingsboard.server.service.update.model.UpdateMessage;
@@ -48,7 +49,7 @@ public class AdminController extends BaseController { @@ -48,7 +49,7 @@ public class AdminController extends BaseController {
48 @ResponseBody 49 @ResponseBody
49 public AdminSettings getAdminSettings(@PathVariable("key") String key) throws ThingsboardException { 50 public AdminSettings getAdminSettings(@PathVariable("key") String key) throws ThingsboardException {
50 try { 51 try {
51 - return checkNotNull(adminSettingsService.findAdminSettingsByKey(key)); 52 + return checkNotNull(adminSettingsService.findAdminSettingsByKey(TenantId.SYS_TENANT_ID, key));
52 } catch (Exception e) { 53 } catch (Exception e) {
53 throw handleException(e); 54 throw handleException(e);
54 } 55 }
@@ -59,7 +60,7 @@ public class AdminController extends BaseController { @@ -59,7 +60,7 @@ public class AdminController extends BaseController {
59 @ResponseBody 60 @ResponseBody
60 public AdminSettings saveAdminSettings(@RequestBody AdminSettings adminSettings) throws ThingsboardException { 61 public AdminSettings saveAdminSettings(@RequestBody AdminSettings adminSettings) throws ThingsboardException {
61 try { 62 try {
62 - adminSettings = checkNotNull(adminSettingsService.saveAdminSettings(adminSettings)); 63 + adminSettings = checkNotNull(adminSettingsService.saveAdminSettings(TenantId.SYS_TENANT_ID, adminSettings));
63 if (adminSettings.getKey().equals("mail")) { 64 if (adminSettings.getKey().equals("mail")) {
64 mailService.updateMailConfiguration(); 65 mailService.updateMailConfiguration();
65 } 66 }
@@ -100,7 +100,7 @@ public class AlarmController extends BaseController { @@ -100,7 +100,7 @@ public class AlarmController extends BaseController {
100 try { 100 try {
101 AlarmId alarmId = new AlarmId(toUUID(strAlarmId)); 101 AlarmId alarmId = new AlarmId(toUUID(strAlarmId));
102 Alarm alarm = checkAlarmId(alarmId); 102 Alarm alarm = checkAlarmId(alarmId);
103 - alarmService.ackAlarm(alarmId, System.currentTimeMillis()).get(); 103 + alarmService.ackAlarm(getCurrentUser().getTenantId(), alarmId, System.currentTimeMillis()).get();
104 logEntityAction(alarmId, alarm, getCurrentUser().getCustomerId(), ActionType.ALARM_ACK, null); 104 logEntityAction(alarmId, alarm, getCurrentUser().getCustomerId(), ActionType.ALARM_ACK, null);
105 } catch (Exception e) { 105 } catch (Exception e) {
106 throw handleException(e); 106 throw handleException(e);
@@ -115,7 +115,7 @@ public class AlarmController extends BaseController { @@ -115,7 +115,7 @@ public class AlarmController extends BaseController {
115 try { 115 try {
116 AlarmId alarmId = new AlarmId(toUUID(strAlarmId)); 116 AlarmId alarmId = new AlarmId(toUUID(strAlarmId));
117 Alarm alarm = checkAlarmId(alarmId); 117 Alarm alarm = checkAlarmId(alarmId);
118 - alarmService.clearAlarm(alarmId, null, System.currentTimeMillis()).get(); 118 + alarmService.clearAlarm(getCurrentUser().getTenantId(), alarmId, null, System.currentTimeMillis()).get();
119 logEntityAction(alarmId, alarm, getCurrentUser().getCustomerId(), ActionType.ALARM_CLEAR, null); 119 logEntityAction(alarmId, alarm, getCurrentUser().getCustomerId(), ActionType.ALARM_CLEAR, null);
120 } catch (Exception e) { 120 } catch (Exception e) {
121 throw handleException(e); 121 throw handleException(e);
@@ -149,7 +149,7 @@ public class AlarmController extends BaseController { @@ -149,7 +149,7 @@ public class AlarmController extends BaseController {
149 checkEntityId(entityId); 149 checkEntityId(entityId);
150 try { 150 try {
151 TimePageLink pageLink = createPageLink(limit, startTime, endTime, ascOrder, offset); 151 TimePageLink pageLink = createPageLink(limit, startTime, endTime, ascOrder, offset);
152 - return checkNotNull(alarmService.findAlarms(new AlarmQuery(entityId, pageLink, alarmSearchStatus, alarmStatus, fetchOriginator)).get()); 152 + return checkNotNull(alarmService.findAlarms(getCurrentUser().getTenantId(), new AlarmQuery(entityId, pageLink, alarmSearchStatus, alarmStatus, fetchOriginator)).get());
153 } catch (Exception e) { 153 } catch (Exception e) {
154 throw handleException(e); 154 throw handleException(e);
155 } 155 }
@@ -175,7 +175,7 @@ public class AlarmController extends BaseController { @@ -175,7 +175,7 @@ public class AlarmController extends BaseController {
175 } 175 }
176 checkEntityId(entityId); 176 checkEntityId(entityId);
177 try { 177 try {
178 - return alarmService.findHighestAlarmSeverity(entityId, alarmSearchStatus, alarmStatus); 178 + return alarmService.findHighestAlarmSeverity(getCurrentUser().getTenantId(), entityId, alarmSearchStatus, alarmStatus);
179 } catch (Exception e) { 179 } catch (Exception e) {
180 throw handleException(e); 180 throw handleException(e);
181 } 181 }
@@ -104,7 +104,7 @@ public class AssetController extends BaseController { @@ -104,7 +104,7 @@ public class AssetController extends BaseController {
104 try { 104 try {
105 AssetId assetId = new AssetId(toUUID(strAssetId)); 105 AssetId assetId = new AssetId(toUUID(strAssetId));
106 Asset asset = checkAssetId(assetId); 106 Asset asset = checkAssetId(assetId);
107 - assetService.deleteAsset(assetId); 107 + assetService.deleteAsset(getTenantId(), assetId);
108 108
109 logEntityAction(assetId, asset, 109 logEntityAction(assetId, asset,
110 asset.getCustomerId(), 110 asset.getCustomerId(),
@@ -133,7 +133,7 @@ public class AssetController extends BaseController { @@ -133,7 +133,7 @@ public class AssetController extends BaseController {
133 AssetId assetId = new AssetId(toUUID(strAssetId)); 133 AssetId assetId = new AssetId(toUUID(strAssetId));
134 checkAssetId(assetId); 134 checkAssetId(assetId);
135 135
136 - Asset savedAsset = checkNotNull(assetService.assignAssetToCustomer(assetId, customerId)); 136 + Asset savedAsset = checkNotNull(assetService.assignAssetToCustomer(getTenantId(), assetId, customerId));
137 137
138 logEntityAction(assetId, savedAsset, 138 logEntityAction(assetId, savedAsset,
139 savedAsset.getCustomerId(), 139 savedAsset.getCustomerId(),
@@ -164,7 +164,7 @@ public class AssetController extends BaseController { @@ -164,7 +164,7 @@ public class AssetController extends BaseController {
164 164
165 Customer customer = checkCustomerId(asset.getCustomerId()); 165 Customer customer = checkCustomerId(asset.getCustomerId());
166 166
167 - Asset savedAsset = checkNotNull(assetService.unassignAssetFromCustomer(assetId)); 167 + Asset savedAsset = checkNotNull(assetService.unassignAssetFromCustomer(getTenantId(), assetId));
168 168
169 logEntityAction(assetId, asset, 169 logEntityAction(assetId, asset,
170 asset.getCustomerId(), 170 asset.getCustomerId(),
@@ -190,7 +190,7 @@ public class AssetController extends BaseController { @@ -190,7 +190,7 @@ public class AssetController extends BaseController {
190 AssetId assetId = new AssetId(toUUID(strAssetId)); 190 AssetId assetId = new AssetId(toUUID(strAssetId));
191 Asset asset = checkAssetId(assetId); 191 Asset asset = checkAssetId(assetId);
192 Customer publicCustomer = customerService.findOrCreatePublicCustomer(asset.getTenantId()); 192 Customer publicCustomer = customerService.findOrCreatePublicCustomer(asset.getTenantId());
193 - Asset savedAsset = checkNotNull(assetService.assignAssetToCustomer(assetId, publicCustomer.getId())); 193 + Asset savedAsset = checkNotNull(assetService.assignAssetToCustomer(getTenantId(), assetId, publicCustomer.getId()));
194 194
195 logEntityAction(assetId, savedAsset, 195 logEntityAction(assetId, savedAsset,
196 savedAsset.getCustomerId(), 196 savedAsset.getCustomerId(),
@@ -303,7 +303,7 @@ public class AssetController extends BaseController { @@ -303,7 +303,7 @@ public class AssetController extends BaseController {
303 checkNotNull(query.getAssetTypes()); 303 checkNotNull(query.getAssetTypes());
304 checkEntityId(query.getParameters().getEntityId()); 304 checkEntityId(query.getParameters().getEntityId());
305 try { 305 try {
306 - List<Asset> assets = checkNotNull(assetService.findAssetsByQuery(query).get()); 306 + List<Asset> assets = checkNotNull(assetService.findAssetsByQuery(getTenantId(), query).get());
307 assets = assets.stream().filter(asset -> { 307 assets = assets.stream().filter(asset -> {
308 try { 308 try {
309 checkAsset(asset); 309 checkAsset(asset);
@@ -36,6 +36,7 @@ import org.thingsboard.rule.engine.api.MailService; @@ -36,6 +36,7 @@ import org.thingsboard.rule.engine.api.MailService;
36 import org.thingsboard.server.common.data.User; 36 import org.thingsboard.server.common.data.User;
37 import org.thingsboard.server.common.data.exception.ThingsboardErrorCode; 37 import org.thingsboard.server.common.data.exception.ThingsboardErrorCode;
38 import org.thingsboard.server.common.data.exception.ThingsboardException; 38 import org.thingsboard.server.common.data.exception.ThingsboardException;
  39 +import org.thingsboard.server.common.data.id.TenantId;
39 import org.thingsboard.server.common.data.security.UserCredentials; 40 import org.thingsboard.server.common.data.security.UserCredentials;
40 import org.thingsboard.server.service.security.auth.jwt.RefreshTokenRepository; 41 import org.thingsboard.server.service.security.auth.jwt.RefreshTokenRepository;
41 import org.thingsboard.server.service.security.model.SecurityUser; 42 import org.thingsboard.server.service.security.model.SecurityUser;
@@ -52,8 +53,6 @@ import java.net.URISyntaxException; @@ -52,8 +53,6 @@ import java.net.URISyntaxException;
52 @Slf4j 53 @Slf4j
53 public class AuthController extends BaseController { 54 public class AuthController extends BaseController {
54 55
55 -  
56 -  
57 @Autowired 56 @Autowired
58 private BCryptPasswordEncoder passwordEncoder; 57 private BCryptPasswordEncoder passwordEncoder;
59 58
@@ -71,7 +70,7 @@ public class AuthController extends BaseController { @@ -71,7 +70,7 @@ public class AuthController extends BaseController {
71 public @ResponseBody User getUser() throws ThingsboardException { 70 public @ResponseBody User getUser() throws ThingsboardException {
72 try { 71 try {
73 SecurityUser securityUser = getCurrentUser(); 72 SecurityUser securityUser = getCurrentUser();
74 - return userService.findUserById(securityUser.getId()); 73 + return userService.findUserById(securityUser.getTenantId(), securityUser.getId());
75 } catch (Exception e) { 74 } catch (Exception e) {
76 throw handleException(e); 75 throw handleException(e);
77 } 76 }
@@ -86,12 +85,12 @@ public class AuthController extends BaseController { @@ -86,12 +85,12 @@ public class AuthController extends BaseController {
86 String currentPassword = changePasswordRequest.get("currentPassword").asText(); 85 String currentPassword = changePasswordRequest.get("currentPassword").asText();
87 String newPassword = changePasswordRequest.get("newPassword").asText(); 86 String newPassword = changePasswordRequest.get("newPassword").asText();
88 SecurityUser securityUser = getCurrentUser(); 87 SecurityUser securityUser = getCurrentUser();
89 - UserCredentials userCredentials = userService.findUserCredentialsByUserId(securityUser.getId()); 88 + UserCredentials userCredentials = userService.findUserCredentialsByUserId(TenantId.SYS_TENANT_ID, securityUser.getId());
90 if (!passwordEncoder.matches(currentPassword, userCredentials.getPassword())) { 89 if (!passwordEncoder.matches(currentPassword, userCredentials.getPassword())) {
91 throw new ThingsboardException("Current password doesn't match!", ThingsboardErrorCode.BAD_REQUEST_PARAMS); 90 throw new ThingsboardException("Current password doesn't match!", ThingsboardErrorCode.BAD_REQUEST_PARAMS);
92 } 91 }
93 userCredentials.setPassword(passwordEncoder.encode(newPassword)); 92 userCredentials.setPassword(passwordEncoder.encode(newPassword));
94 - userService.saveUserCredentials(userCredentials); 93 + userService.saveUserCredentials(securityUser.getTenantId(), userCredentials);
95 } catch (Exception e) { 94 } catch (Exception e) {
96 throw handleException(e); 95 throw handleException(e);
97 } 96 }
@@ -102,7 +101,7 @@ public class AuthController extends BaseController { @@ -102,7 +101,7 @@ public class AuthController extends BaseController {
102 @RequestParam(value = "activateToken") String activateToken) { 101 @RequestParam(value = "activateToken") String activateToken) {
103 HttpHeaders headers = new HttpHeaders(); 102 HttpHeaders headers = new HttpHeaders();
104 HttpStatus responseStatus; 103 HttpStatus responseStatus;
105 - UserCredentials userCredentials = userService.findUserCredentialsByActivateToken(activateToken); 104 + UserCredentials userCredentials = userService.findUserCredentialsByActivateToken(TenantId.SYS_TENANT_ID, activateToken);
106 if (userCredentials != null) { 105 if (userCredentials != null) {
107 String createURI = "/login/createPassword"; 106 String createURI = "/login/createPassword";
108 try { 107 try {
@@ -126,7 +125,7 @@ public class AuthController extends BaseController { @@ -126,7 +125,7 @@ public class AuthController extends BaseController {
126 HttpServletRequest request) throws ThingsboardException { 125 HttpServletRequest request) throws ThingsboardException {
127 try { 126 try {
128 String email = resetPasswordByEmailRequest.get("email").asText(); 127 String email = resetPasswordByEmailRequest.get("email").asText();
129 - UserCredentials userCredentials = userService.requestPasswordReset(email); 128 + UserCredentials userCredentials = userService.requestPasswordReset(TenantId.SYS_TENANT_ID, email);
130 String baseUrl = constructBaseUrl(request); 129 String baseUrl = constructBaseUrl(request);
131 String resetUrl = String.format("%s/api/noauth/resetPassword?resetToken=%s", baseUrl, 130 String resetUrl = String.format("%s/api/noauth/resetPassword?resetToken=%s", baseUrl,
132 userCredentials.getResetToken()); 131 userCredentials.getResetToken());
@@ -143,7 +142,7 @@ public class AuthController extends BaseController { @@ -143,7 +142,7 @@ public class AuthController extends BaseController {
143 HttpHeaders headers = new HttpHeaders(); 142 HttpHeaders headers = new HttpHeaders();
144 HttpStatus responseStatus; 143 HttpStatus responseStatus;
145 String resetURI = "/login/resetPassword"; 144 String resetURI = "/login/resetPassword";
146 - UserCredentials userCredentials = userService.findUserCredentialsByResetToken(resetToken); 145 + UserCredentials userCredentials = userService.findUserCredentialsByResetToken(TenantId.SYS_TENANT_ID, resetToken);
147 if (userCredentials != null) { 146 if (userCredentials != null) {
148 try { 147 try {
149 URI location = new URI(resetURI + "?resetToken=" + resetToken); 148 URI location = new URI(resetURI + "?resetToken=" + resetToken);
@@ -169,8 +168,8 @@ public class AuthController extends BaseController { @@ -169,8 +168,8 @@ public class AuthController extends BaseController {
169 String activateToken = activateRequest.get("activateToken").asText(); 168 String activateToken = activateRequest.get("activateToken").asText();
170 String password = activateRequest.get("password").asText(); 169 String password = activateRequest.get("password").asText();
171 String encodedPassword = passwordEncoder.encode(password); 170 String encodedPassword = passwordEncoder.encode(password);
172 - UserCredentials credentials = userService.activateUserCredentials(activateToken, encodedPassword);  
173 - User user = userService.findUserById(credentials.getUserId()); 171 + UserCredentials credentials = userService.activateUserCredentials(TenantId.SYS_TENANT_ID, activateToken, encodedPassword);
  172 + User user = userService.findUserById(TenantId.SYS_TENANT_ID, credentials.getUserId());
174 UserPrincipal principal = new UserPrincipal(UserPrincipal.Type.USER_NAME, user.getEmail()); 173 UserPrincipal principal = new UserPrincipal(UserPrincipal.Type.USER_NAME, user.getEmail());
175 SecurityUser securityUser = new SecurityUser(user, credentials.isEnabled(), principal); 174 SecurityUser securityUser = new SecurityUser(user, credentials.isEnabled(), principal);
176 String baseUrl = constructBaseUrl(request); 175 String baseUrl = constructBaseUrl(request);
@@ -205,13 +204,13 @@ public class AuthController extends BaseController { @@ -205,13 +204,13 @@ public class AuthController extends BaseController {
205 try { 204 try {
206 String resetToken = resetPasswordRequest.get("resetToken").asText(); 205 String resetToken = resetPasswordRequest.get("resetToken").asText();
207 String password = resetPasswordRequest.get("password").asText(); 206 String password = resetPasswordRequest.get("password").asText();
208 - UserCredentials userCredentials = userService.findUserCredentialsByResetToken(resetToken); 207 + UserCredentials userCredentials = userService.findUserCredentialsByResetToken(TenantId.SYS_TENANT_ID, resetToken);
209 if (userCredentials != null) { 208 if (userCredentials != null) {
210 String encodedPassword = passwordEncoder.encode(password); 209 String encodedPassword = passwordEncoder.encode(password);
211 userCredentials.setPassword(encodedPassword); 210 userCredentials.setPassword(encodedPassword);
212 userCredentials.setResetToken(null); 211 userCredentials.setResetToken(null);
213 - userCredentials = userService.saveUserCredentials(userCredentials);  
214 - User user = userService.findUserById(userCredentials.getUserId()); 212 + userCredentials = userService.saveUserCredentials(TenantId.SYS_TENANT_ID, userCredentials);
  213 + User user = userService.findUserById(TenantId.SYS_TENANT_ID, userCredentials.getUserId());
215 UserPrincipal principal = new UserPrincipal(UserPrincipal.Type.USER_NAME, user.getEmail()); 214 UserPrincipal principal = new UserPrincipal(UserPrincipal.Type.USER_NAME, user.getEmail());
216 SecurityUser securityUser = new SecurityUser(user, userCredentials.isEnabled(), principal); 215 SecurityUser securityUser = new SecurityUser(user, userCredentials.isEnabled(), principal);
217 String baseUrl = constructBaseUrl(request); 216 String baseUrl = constructBaseUrl(request);
@@ -275,7 +275,7 @@ public abstract class BaseController { @@ -275,7 +275,7 @@ public abstract class BaseController {
275 ThingsboardErrorCode.PERMISSION_DENIED); 275 ThingsboardErrorCode.PERMISSION_DENIED);
276 } 276 }
277 if (customerId != null && !customerId.isNullUid()) { 277 if (customerId != null && !customerId.isNullUid()) {
278 - Customer customer = customerService.findCustomerById(customerId); 278 + Customer customer = customerService.findCustomerById(authUser.getTenantId(), customerId);
279 checkCustomer(customer); 279 checkCustomer(customer);
280 return customer; 280 return customer;
281 } else { 281 } else {
@@ -294,7 +294,7 @@ public abstract class BaseController { @@ -294,7 +294,7 @@ public abstract class BaseController {
294 User checkUserId(UserId userId) throws ThingsboardException { 294 User checkUserId(UserId userId) throws ThingsboardException {
295 try { 295 try {
296 validateId(userId, "Incorrect userId " + userId); 296 validateId(userId, "Incorrect userId " + userId);
297 - User user = userService.findUserById(userId); 297 + User user = userService.findUserById(getCurrentUser().getTenantId(), userId);
298 checkUser(user); 298 checkUser(user);
299 return user; 299 return user;
300 } catch (Exception e) { 300 } catch (Exception e) {
@@ -314,9 +314,10 @@ public abstract class BaseController { @@ -314,9 +314,10 @@ public abstract class BaseController {
314 try { 314 try {
315 checkNotNull(entityId); 315 checkNotNull(entityId);
316 validateId(entityId.getId(), "Incorrect entityId " + entityId); 316 validateId(entityId.getId(), "Incorrect entityId " + entityId);
  317 + SecurityUser authUser = getCurrentUser();
317 switch (entityId.getEntityType()) { 318 switch (entityId.getEntityType()) {
318 case DEVICE: 319 case DEVICE:
319 - checkDevice(deviceService.findDeviceById(new DeviceId(entityId.getId()))); 320 + checkDevice(deviceService.findDeviceById(authUser.getTenantId(), new DeviceId(entityId.getId())));
320 return; 321 return;
321 case CUSTOMER: 322 case CUSTOMER:
322 checkCustomerId(new CustomerId(entityId.getId())); 323 checkCustomerId(new CustomerId(entityId.getId()));
@@ -328,7 +329,7 @@ public abstract class BaseController { @@ -328,7 +329,7 @@ public abstract class BaseController {
328 checkRuleChain(new RuleChainId(entityId.getId())); 329 checkRuleChain(new RuleChainId(entityId.getId()));
329 return; 330 return;
330 case ASSET: 331 case ASSET:
331 - checkAsset(assetService.findAssetById(new AssetId(entityId.getId()))); 332 + checkAsset(assetService.findAssetById(authUser.getTenantId(), new AssetId(entityId.getId())));
332 return; 333 return;
333 case DASHBOARD: 334 case DASHBOARD:
334 checkDashboardId(new DashboardId(entityId.getId())); 335 checkDashboardId(new DashboardId(entityId.getId()));
@@ -350,7 +351,7 @@ public abstract class BaseController { @@ -350,7 +351,7 @@ public abstract class BaseController {
350 Device checkDeviceId(DeviceId deviceId) throws ThingsboardException { 351 Device checkDeviceId(DeviceId deviceId) throws ThingsboardException {
351 try { 352 try {
352 validateId(deviceId, "Incorrect deviceId " + deviceId); 353 validateId(deviceId, "Incorrect deviceId " + deviceId);
353 - Device device = deviceService.findDeviceById(deviceId); 354 + Device device = deviceService.findDeviceById(getCurrentUser().getTenantId(), deviceId);
354 checkDevice(device); 355 checkDevice(device);
355 return device; 356 return device;
356 } catch (Exception e) { 357 } catch (Exception e) {
@@ -367,7 +368,7 @@ public abstract class BaseController { @@ -367,7 +368,7 @@ public abstract class BaseController {
367 protected EntityView checkEntityViewId(EntityViewId entityViewId) throws ThingsboardException { 368 protected EntityView checkEntityViewId(EntityViewId entityViewId) throws ThingsboardException {
368 try { 369 try {
369 validateId(entityViewId, "Incorrect entityViewId " + entityViewId); 370 validateId(entityViewId, "Incorrect entityViewId " + entityViewId);
370 - EntityView entityView = entityViewService.findEntityViewById(entityViewId); 371 + EntityView entityView = entityViewService.findEntityViewById(getCurrentUser().getTenantId(), entityViewId);
371 checkEntityView(entityView); 372 checkEntityView(entityView);
372 return entityView; 373 return entityView;
373 } catch (Exception e) { 374 } catch (Exception e) {
@@ -384,7 +385,7 @@ public abstract class BaseController { @@ -384,7 +385,7 @@ public abstract class BaseController {
384 Asset checkAssetId(AssetId assetId) throws ThingsboardException { 385 Asset checkAssetId(AssetId assetId) throws ThingsboardException {
385 try { 386 try {
386 validateId(assetId, "Incorrect assetId " + assetId); 387 validateId(assetId, "Incorrect assetId " + assetId);
387 - Asset asset = assetService.findAssetById(assetId); 388 + Asset asset = assetService.findAssetById(getCurrentUser().getTenantId(), assetId);
388 checkAsset(asset); 389 checkAsset(asset);
389 return asset; 390 return asset;
390 } catch (Exception e) { 391 } catch (Exception e) {
@@ -401,7 +402,7 @@ public abstract class BaseController { @@ -401,7 +402,7 @@ public abstract class BaseController {
401 Alarm checkAlarmId(AlarmId alarmId) throws ThingsboardException { 402 Alarm checkAlarmId(AlarmId alarmId) throws ThingsboardException {
402 try { 403 try {
403 validateId(alarmId, "Incorrect alarmId " + alarmId); 404 validateId(alarmId, "Incorrect alarmId " + alarmId);
404 - Alarm alarm = alarmService.findAlarmByIdAsync(alarmId).get(); 405 + Alarm alarm = alarmService.findAlarmByIdAsync(getCurrentUser().getTenantId(), alarmId).get();
405 checkAlarm(alarm); 406 checkAlarm(alarm);
406 return alarm; 407 return alarm;
407 } catch (Exception e) { 408 } catch (Exception e) {
@@ -412,7 +413,7 @@ public abstract class BaseController { @@ -412,7 +413,7 @@ public abstract class BaseController {
412 AlarmInfo checkAlarmInfoId(AlarmId alarmId) throws ThingsboardException { 413 AlarmInfo checkAlarmInfoId(AlarmId alarmId) throws ThingsboardException {
413 try { 414 try {
414 validateId(alarmId, "Incorrect alarmId " + alarmId); 415 validateId(alarmId, "Incorrect alarmId " + alarmId);
415 - AlarmInfo alarmInfo = alarmService.findAlarmInfoByIdAsync(alarmId).get(); 416 + AlarmInfo alarmInfo = alarmService.findAlarmInfoByIdAsync(getCurrentUser().getTenantId(), alarmId).get();
416 checkAlarm(alarmInfo); 417 checkAlarm(alarmInfo);
417 return alarmInfo; 418 return alarmInfo;
418 } catch (Exception e) { 419 } catch (Exception e) {
@@ -428,7 +429,7 @@ public abstract class BaseController { @@ -428,7 +429,7 @@ public abstract class BaseController {
428 WidgetsBundle checkWidgetsBundleId(WidgetsBundleId widgetsBundleId, boolean modify) throws ThingsboardException { 429 WidgetsBundle checkWidgetsBundleId(WidgetsBundleId widgetsBundleId, boolean modify) throws ThingsboardException {
429 try { 430 try {
430 validateId(widgetsBundleId, "Incorrect widgetsBundleId " + widgetsBundleId); 431 validateId(widgetsBundleId, "Incorrect widgetsBundleId " + widgetsBundleId);
431 - WidgetsBundle widgetsBundle = widgetsBundleService.findWidgetsBundleById(widgetsBundleId); 432 + WidgetsBundle widgetsBundle = widgetsBundleService.findWidgetsBundleById(getCurrentUser().getTenantId(), widgetsBundleId);
432 checkWidgetsBundle(widgetsBundle, modify); 433 checkWidgetsBundle(widgetsBundle, modify);
433 return widgetsBundle; 434 return widgetsBundle;
434 } catch (Exception e) { 435 } catch (Exception e) {
@@ -449,7 +450,7 @@ public abstract class BaseController { @@ -449,7 +450,7 @@ public abstract class BaseController {
449 WidgetType checkWidgetTypeId(WidgetTypeId widgetTypeId, boolean modify) throws ThingsboardException { 450 WidgetType checkWidgetTypeId(WidgetTypeId widgetTypeId, boolean modify) throws ThingsboardException {
450 try { 451 try {
451 validateId(widgetTypeId, "Incorrect widgetTypeId " + widgetTypeId); 452 validateId(widgetTypeId, "Incorrect widgetTypeId " + widgetTypeId);
452 - WidgetType widgetType = widgetTypeService.findWidgetTypeById(widgetTypeId); 453 + WidgetType widgetType = widgetTypeService.findWidgetTypeById(getCurrentUser().getTenantId(), widgetTypeId);
453 checkWidgetType(widgetType, modify); 454 checkWidgetType(widgetType, modify);
454 return widgetType; 455 return widgetType;
455 } catch (Exception e) { 456 } catch (Exception e) {
@@ -470,7 +471,7 @@ public abstract class BaseController { @@ -470,7 +471,7 @@ public abstract class BaseController {
470 Dashboard checkDashboardId(DashboardId dashboardId) throws ThingsboardException { 471 Dashboard checkDashboardId(DashboardId dashboardId) throws ThingsboardException {
471 try { 472 try {
472 validateId(dashboardId, "Incorrect dashboardId " + dashboardId); 473 validateId(dashboardId, "Incorrect dashboardId " + dashboardId);
473 - Dashboard dashboard = dashboardService.findDashboardById(dashboardId); 474 + Dashboard dashboard = dashboardService.findDashboardById(getCurrentUser().getTenantId(), dashboardId);
474 checkDashboard(dashboard); 475 checkDashboard(dashboard);
475 return dashboard; 476 return dashboard;
476 } catch (Exception e) { 477 } catch (Exception e) {
@@ -481,7 +482,7 @@ public abstract class BaseController { @@ -481,7 +482,7 @@ public abstract class BaseController {
481 DashboardInfo checkDashboardInfoId(DashboardId dashboardId) throws ThingsboardException { 482 DashboardInfo checkDashboardInfoId(DashboardId dashboardId) throws ThingsboardException {
482 try { 483 try {
483 validateId(dashboardId, "Incorrect dashboardId " + dashboardId); 484 validateId(dashboardId, "Incorrect dashboardId " + dashboardId);
484 - DashboardInfo dashboardInfo = dashboardService.findDashboardInfoById(dashboardId); 485 + DashboardInfo dashboardInfo = dashboardService.findDashboardInfoById(getCurrentUser().getTenantId(), dashboardId);
485 checkDashboard(dashboardInfo); 486 checkDashboard(dashboardInfo);
486 return dashboardInfo; 487 return dashboardInfo;
487 } catch (Exception e) { 488 } catch (Exception e) {
@@ -530,7 +531,7 @@ public abstract class BaseController { @@ -530,7 +531,7 @@ public abstract class BaseController {
530 531
531 protected RuleChain checkRuleChain(RuleChainId ruleChainId) throws ThingsboardException { 532 protected RuleChain checkRuleChain(RuleChainId ruleChainId) throws ThingsboardException {
532 checkNotNull(ruleChainId); 533 checkNotNull(ruleChainId);
533 - return checkRuleChain(ruleChainService.findRuleChainById(ruleChainId)); 534 + return checkRuleChain(ruleChainService.findRuleChainById(getCurrentUser().getTenantId(), ruleChainId));
534 } 535 }
535 536
536 protected RuleChain checkRuleChain(RuleChain ruleChain) throws ThingsboardException { 537 protected RuleChain checkRuleChain(RuleChain ruleChain) throws ThingsboardException {
@@ -119,7 +119,7 @@ public class CustomerController extends BaseController { @@ -119,7 +119,7 @@ public class CustomerController extends BaseController {
119 try { 119 try {
120 CustomerId customerId = new CustomerId(toUUID(strCustomerId)); 120 CustomerId customerId = new CustomerId(toUUID(strCustomerId));
121 Customer customer = checkCustomerId(customerId); 121 Customer customer = checkCustomerId(customerId);
122 - customerService.deleteCustomer(customerId); 122 + customerService.deleteCustomer(getTenantId(), customerId);
123 123
124 logEntityAction(customerId, customer, 124 logEntityAction(customerId, customer,
125 customer.getId(), 125 customer.getId(),
@@ -124,7 +124,7 @@ public class DashboardController extends BaseController { @@ -124,7 +124,7 @@ public class DashboardController extends BaseController {
124 try { 124 try {
125 DashboardId dashboardId = new DashboardId(toUUID(strDashboardId)); 125 DashboardId dashboardId = new DashboardId(toUUID(strDashboardId));
126 Dashboard dashboard = checkDashboardId(dashboardId); 126 Dashboard dashboard = checkDashboardId(dashboardId);
127 - dashboardService.deleteDashboard(dashboardId); 127 + dashboardService.deleteDashboard(getCurrentUser().getTenantId(), dashboardId);
128 128
129 logEntityAction(dashboardId, dashboard, 129 logEntityAction(dashboardId, dashboard,
130 null, 130 null,
@@ -155,7 +155,7 @@ public class DashboardController extends BaseController { @@ -155,7 +155,7 @@ public class DashboardController extends BaseController {
155 DashboardId dashboardId = new DashboardId(toUUID(strDashboardId)); 155 DashboardId dashboardId = new DashboardId(toUUID(strDashboardId));
156 checkDashboardId(dashboardId); 156 checkDashboardId(dashboardId);
157 157
158 - Dashboard savedDashboard = checkNotNull(dashboardService.assignDashboardToCustomer(dashboardId, customerId)); 158 + Dashboard savedDashboard = checkNotNull(dashboardService.assignDashboardToCustomer(getCurrentUser().getTenantId(), dashboardId, customerId));
159 159
160 logEntityAction(dashboardId, savedDashboard, 160 logEntityAction(dashboardId, savedDashboard,
161 customerId, 161 customerId,
@@ -186,7 +186,7 @@ public class DashboardController extends BaseController { @@ -186,7 +186,7 @@ public class DashboardController extends BaseController {
186 DashboardId dashboardId = new DashboardId(toUUID(strDashboardId)); 186 DashboardId dashboardId = new DashboardId(toUUID(strDashboardId));
187 Dashboard dashboard = checkDashboardId(dashboardId); 187 Dashboard dashboard = checkDashboardId(dashboardId);
188 188
189 - Dashboard savedDashboard = checkNotNull(dashboardService.unassignDashboardFromCustomer(dashboardId, customerId)); 189 + Dashboard savedDashboard = checkNotNull(dashboardService.unassignDashboardFromCustomer(getCurrentUser().getTenantId(), dashboardId, customerId));
190 190
191 logEntityAction(dashboardId, dashboard, 191 logEntityAction(dashboardId, dashboard,
192 customerId, 192 customerId,
@@ -242,7 +242,7 @@ public class DashboardController extends BaseController { @@ -242,7 +242,7 @@ public class DashboardController extends BaseController {
242 } else { 242 } else {
243 Dashboard savedDashboard = null; 243 Dashboard savedDashboard = null;
244 for (CustomerId customerId : addedCustomerIds) { 244 for (CustomerId customerId : addedCustomerIds) {
245 - savedDashboard = checkNotNull(dashboardService.assignDashboardToCustomer(dashboardId, customerId)); 245 + savedDashboard = checkNotNull(dashboardService.assignDashboardToCustomer(getCurrentUser().getTenantId(), dashboardId, customerId));
246 ShortCustomerInfo customerInfo = savedDashboard.getAssignedCustomerInfo(customerId); 246 ShortCustomerInfo customerInfo = savedDashboard.getAssignedCustomerInfo(customerId);
247 logEntityAction(dashboardId, savedDashboard, 247 logEntityAction(dashboardId, savedDashboard,
248 customerId, 248 customerId,
@@ -250,7 +250,7 @@ public class DashboardController extends BaseController { @@ -250,7 +250,7 @@ public class DashboardController extends BaseController {
250 } 250 }
251 for (CustomerId customerId : removedCustomerIds) { 251 for (CustomerId customerId : removedCustomerIds) {
252 ShortCustomerInfo customerInfo = dashboard.getAssignedCustomerInfo(customerId); 252 ShortCustomerInfo customerInfo = dashboard.getAssignedCustomerInfo(customerId);
253 - savedDashboard = checkNotNull(dashboardService.unassignDashboardFromCustomer(dashboardId, customerId)); 253 + savedDashboard = checkNotNull(dashboardService.unassignDashboardFromCustomer(getCurrentUser().getTenantId(), dashboardId, customerId));
254 logEntityAction(dashboardId, dashboard, 254 logEntityAction(dashboardId, dashboard,
255 customerId, 255 customerId,
256 ActionType.UNASSIGNED_FROM_CUSTOMER, null, strDashboardId, customerId.toString(), customerInfo.getTitle()); 256 ActionType.UNASSIGNED_FROM_CUSTOMER, null, strDashboardId, customerId.toString(), customerInfo.getTitle());
@@ -293,7 +293,7 @@ public class DashboardController extends BaseController { @@ -293,7 +293,7 @@ public class DashboardController extends BaseController {
293 } else { 293 } else {
294 Dashboard savedDashboard = null; 294 Dashboard savedDashboard = null;
295 for (CustomerId customerId : customerIds) { 295 for (CustomerId customerId : customerIds) {
296 - savedDashboard = checkNotNull(dashboardService.assignDashboardToCustomer(dashboardId, customerId)); 296 + savedDashboard = checkNotNull(dashboardService.assignDashboardToCustomer(getCurrentUser().getTenantId(), dashboardId, customerId));
297 ShortCustomerInfo customerInfo = savedDashboard.getAssignedCustomerInfo(customerId); 297 ShortCustomerInfo customerInfo = savedDashboard.getAssignedCustomerInfo(customerId);
298 logEntityAction(dashboardId, savedDashboard, 298 logEntityAction(dashboardId, savedDashboard,
299 customerId, 299 customerId,
@@ -337,7 +337,7 @@ public class DashboardController extends BaseController { @@ -337,7 +337,7 @@ public class DashboardController extends BaseController {
337 Dashboard savedDashboard = null; 337 Dashboard savedDashboard = null;
338 for (CustomerId customerId : customerIds) { 338 for (CustomerId customerId : customerIds) {
339 ShortCustomerInfo customerInfo = dashboard.getAssignedCustomerInfo(customerId); 339 ShortCustomerInfo customerInfo = dashboard.getAssignedCustomerInfo(customerId);
340 - savedDashboard = checkNotNull(dashboardService.unassignDashboardFromCustomer(dashboardId, customerId)); 340 + savedDashboard = checkNotNull(dashboardService.unassignDashboardFromCustomer(getCurrentUser().getTenantId(), dashboardId, customerId));
341 logEntityAction(dashboardId, dashboard, 341 logEntityAction(dashboardId, dashboard,
342 customerId, 342 customerId,
343 ActionType.UNASSIGNED_FROM_CUSTOMER, null, strDashboardId, customerId.toString(), customerInfo.getTitle()); 343 ActionType.UNASSIGNED_FROM_CUSTOMER, null, strDashboardId, customerId.toString(), customerInfo.getTitle());
@@ -364,7 +364,7 @@ public class DashboardController extends BaseController { @@ -364,7 +364,7 @@ public class DashboardController extends BaseController {
364 DashboardId dashboardId = new DashboardId(toUUID(strDashboardId)); 364 DashboardId dashboardId = new DashboardId(toUUID(strDashboardId));
365 Dashboard dashboard = checkDashboardId(dashboardId); 365 Dashboard dashboard = checkDashboardId(dashboardId);
366 Customer publicCustomer = customerService.findOrCreatePublicCustomer(dashboard.getTenantId()); 366 Customer publicCustomer = customerService.findOrCreatePublicCustomer(dashboard.getTenantId());
367 - Dashboard savedDashboard = checkNotNull(dashboardService.assignDashboardToCustomer(dashboardId, publicCustomer.getId())); 367 + Dashboard savedDashboard = checkNotNull(dashboardService.assignDashboardToCustomer(getCurrentUser().getTenantId(), dashboardId, publicCustomer.getId()));
368 368
369 logEntityAction(dashboardId, savedDashboard, 369 logEntityAction(dashboardId, savedDashboard,
370 publicCustomer.getId(), 370 publicCustomer.getId(),
@@ -391,7 +391,7 @@ public class DashboardController extends BaseController { @@ -391,7 +391,7 @@ public class DashboardController extends BaseController {
391 Dashboard dashboard = checkDashboardId(dashboardId); 391 Dashboard dashboard = checkDashboardId(dashboardId);
392 Customer publicCustomer = customerService.findOrCreatePublicCustomer(dashboard.getTenantId()); 392 Customer publicCustomer = customerService.findOrCreatePublicCustomer(dashboard.getTenantId());
393 393
394 - Dashboard savedDashboard = checkNotNull(dashboardService.unassignDashboardFromCustomer(dashboardId, publicCustomer.getId())); 394 + Dashboard savedDashboard = checkNotNull(dashboardService.unassignDashboardFromCustomer(getCurrentUser().getTenantId(), dashboardId, publicCustomer.getId()));
395 395
396 logEntityAction(dashboardId, dashboard, 396 logEntityAction(dashboardId, dashboard,
397 publicCustomer.getId(), 397 publicCustomer.getId(),
@@ -117,7 +117,7 @@ public class DeviceController extends BaseController { @@ -117,7 +117,7 @@ public class DeviceController extends BaseController {
117 try { 117 try {
118 DeviceId deviceId = new DeviceId(toUUID(strDeviceId)); 118 DeviceId deviceId = new DeviceId(toUUID(strDeviceId));
119 Device device = checkDeviceId(deviceId); 119 Device device = checkDeviceId(deviceId);
120 - deviceService.deleteDevice(deviceId); 120 + deviceService.deleteDevice(getCurrentUser().getTenantId(), deviceId);
121 121
122 logEntityAction(deviceId, device, 122 logEntityAction(deviceId, device,
123 device.getCustomerId(), 123 device.getCustomerId(),
@@ -147,7 +147,7 @@ public class DeviceController extends BaseController { @@ -147,7 +147,7 @@ public class DeviceController extends BaseController {
147 DeviceId deviceId = new DeviceId(toUUID(strDeviceId)); 147 DeviceId deviceId = new DeviceId(toUUID(strDeviceId));
148 checkDeviceId(deviceId); 148 checkDeviceId(deviceId);
149 149
150 - Device savedDevice = checkNotNull(deviceService.assignDeviceToCustomer(deviceId, customerId)); 150 + Device savedDevice = checkNotNull(deviceService.assignDeviceToCustomer(getCurrentUser().getTenantId(), deviceId, customerId));
151 151
152 logEntityAction(deviceId, savedDevice, 152 logEntityAction(deviceId, savedDevice,
153 savedDevice.getCustomerId(), 153 savedDevice.getCustomerId(),
@@ -175,7 +175,7 @@ public class DeviceController extends BaseController { @@ -175,7 +175,7 @@ public class DeviceController extends BaseController {
175 } 175 }
176 Customer customer = checkCustomerId(device.getCustomerId()); 176 Customer customer = checkCustomerId(device.getCustomerId());
177 177
178 - Device savedDevice = checkNotNull(deviceService.unassignDeviceFromCustomer(deviceId)); 178 + Device savedDevice = checkNotNull(deviceService.unassignDeviceFromCustomer(getCurrentUser().getTenantId(), deviceId));
179 179
180 logEntityAction(deviceId, device, 180 logEntityAction(deviceId, device,
181 device.getCustomerId(), 181 device.getCustomerId(),
@@ -199,7 +199,7 @@ public class DeviceController extends BaseController { @@ -199,7 +199,7 @@ public class DeviceController extends BaseController {
199 DeviceId deviceId = new DeviceId(toUUID(strDeviceId)); 199 DeviceId deviceId = new DeviceId(toUUID(strDeviceId));
200 Device device = checkDeviceId(deviceId); 200 Device device = checkDeviceId(deviceId);
201 Customer publicCustomer = customerService.findOrCreatePublicCustomer(device.getTenantId()); 201 Customer publicCustomer = customerService.findOrCreatePublicCustomer(device.getTenantId());
202 - Device savedDevice = checkNotNull(deviceService.assignDeviceToCustomer(deviceId, publicCustomer.getId())); 202 + Device savedDevice = checkNotNull(deviceService.assignDeviceToCustomer(getCurrentUser().getTenantId(), deviceId, publicCustomer.getId()));
203 203
204 logEntityAction(deviceId, savedDevice, 204 logEntityAction(deviceId, savedDevice,
205 savedDevice.getCustomerId(), 205 savedDevice.getCustomerId(),
@@ -222,7 +222,7 @@ public class DeviceController extends BaseController { @@ -222,7 +222,7 @@ public class DeviceController extends BaseController {
222 try { 222 try {
223 DeviceId deviceId = new DeviceId(toUUID(strDeviceId)); 223 DeviceId deviceId = new DeviceId(toUUID(strDeviceId));
224 Device device = checkDeviceId(deviceId); 224 Device device = checkDeviceId(deviceId);
225 - DeviceCredentials deviceCredentials = checkNotNull(deviceCredentialsService.findDeviceCredentialsByDeviceId(deviceId)); 225 + DeviceCredentials deviceCredentials = checkNotNull(deviceCredentialsService.findDeviceCredentialsByDeviceId(getCurrentUser().getTenantId(), deviceId));
226 logEntityAction(deviceId, device, 226 logEntityAction(deviceId, device,
227 device.getCustomerId(), 227 device.getCustomerId(),
228 ActionType.CREDENTIALS_READ, null, strDeviceId); 228 ActionType.CREDENTIALS_READ, null, strDeviceId);
@@ -242,7 +242,7 @@ public class DeviceController extends BaseController { @@ -242,7 +242,7 @@ public class DeviceController extends BaseController {
242 checkNotNull(deviceCredentials); 242 checkNotNull(deviceCredentials);
243 try { 243 try {
244 Device device = checkDeviceId(deviceCredentials.getDeviceId()); 244 Device device = checkDeviceId(deviceCredentials.getDeviceId());
245 - DeviceCredentials result = checkNotNull(deviceCredentialsService.updateDeviceCredentials(deviceCredentials)); 245 + DeviceCredentials result = checkNotNull(deviceCredentialsService.updateDeviceCredentials(getCurrentUser().getTenantId(), deviceCredentials));
246 actorService.onCredentialsUpdate(getCurrentUser().getTenantId(), deviceCredentials.getDeviceId()); 246 actorService.onCredentialsUpdate(getCurrentUser().getTenantId(), deviceCredentials.getDeviceId());
247 logEntityAction(device.getId(), device, 247 logEntityAction(device.getId(), device,
248 device.getCustomerId(), 248 device.getCustomerId(),
@@ -352,7 +352,7 @@ public class DeviceController extends BaseController { @@ -352,7 +352,7 @@ public class DeviceController extends BaseController {
352 checkNotNull(query.getDeviceTypes()); 352 checkNotNull(query.getDeviceTypes());
353 checkEntityId(query.getParameters().getEntityId()); 353 checkEntityId(query.getParameters().getEntityId());
354 try { 354 try {
355 - List<Device> devices = checkNotNull(deviceService.findDevicesByQuery(query).get()); 355 + List<Device> devices = checkNotNull(deviceService.findDevicesByQuery(getCurrentUser().getTenantId(), query).get());
356 devices = devices.stream().filter(device -> { 356 devices = devices.stream().filter(device -> {
357 try { 357 try {
358 checkDevice(device); 358 checkDevice(device);
@@ -60,7 +60,7 @@ public class EntityRelationController extends BaseController { @@ -60,7 +60,7 @@ public class EntityRelationController extends BaseController {
60 if (relation.getTypeGroup() == null) { 60 if (relation.getTypeGroup() == null) {
61 relation.setTypeGroup(RelationTypeGroup.COMMON); 61 relation.setTypeGroup(RelationTypeGroup.COMMON);
62 } 62 }
63 - relationService.saveRelation(relation); 63 + relationService.saveRelation(getTenantId(), relation);
64 logEntityAction(relation.getFrom(), null, getCurrentUser().getCustomerId(), 64 logEntityAction(relation.getFrom(), null, getCurrentUser().getCustomerId(),
65 ActionType.RELATION_ADD_OR_UPDATE, null, relation); 65 ActionType.RELATION_ADD_OR_UPDATE, null, relation);
66 logEntityAction(relation.getTo(), null, getCurrentUser().getCustomerId(), 66 logEntityAction(relation.getTo(), null, getCurrentUser().getCustomerId(),
@@ -94,7 +94,7 @@ public class EntityRelationController extends BaseController { @@ -94,7 +94,7 @@ public class EntityRelationController extends BaseController {
94 RelationTypeGroup relationTypeGroup = parseRelationTypeGroup(strRelationTypeGroup, RelationTypeGroup.COMMON); 94 RelationTypeGroup relationTypeGroup = parseRelationTypeGroup(strRelationTypeGroup, RelationTypeGroup.COMMON);
95 EntityRelation relation = new EntityRelation(fromId, toId, strRelationType, relationTypeGroup); 95 EntityRelation relation = new EntityRelation(fromId, toId, strRelationType, relationTypeGroup);
96 try { 96 try {
97 - Boolean found = relationService.deleteRelation(fromId, toId, strRelationType, relationTypeGroup); 97 + Boolean found = relationService.deleteRelation(getTenantId(), fromId, toId, strRelationType, relationTypeGroup);
98 if (!found) { 98 if (!found) {
99 throw new ThingsboardException("Requested item wasn't found!", ThingsboardErrorCode.ITEM_NOT_FOUND); 99 throw new ThingsboardException("Requested item wasn't found!", ThingsboardErrorCode.ITEM_NOT_FOUND);
100 } 100 }
@@ -121,7 +121,7 @@ public class EntityRelationController extends BaseController { @@ -121,7 +121,7 @@ public class EntityRelationController extends BaseController {
121 EntityId entityId = EntityIdFactory.getByTypeAndId(strType, strId); 121 EntityId entityId = EntityIdFactory.getByTypeAndId(strType, strId);
122 checkEntityId(entityId); 122 checkEntityId(entityId);
123 try { 123 try {
124 - relationService.deleteEntityRelations(entityId); 124 + relationService.deleteEntityRelations(getTenantId(), entityId);
125 logEntityAction(entityId, null, getCurrentUser().getCustomerId(), ActionType.RELATIONS_DELETED, null); 125 logEntityAction(entityId, null, getCurrentUser().getCustomerId(), ActionType.RELATIONS_DELETED, null);
126 } catch (Exception e) { 126 } catch (Exception e) {
127 logEntityAction(entityId, null, getCurrentUser().getCustomerId(), ActionType.RELATIONS_DELETED, e); 127 logEntityAction(entityId, null, getCurrentUser().getCustomerId(), ActionType.RELATIONS_DELETED, e);
@@ -148,7 +148,7 @@ public class EntityRelationController extends BaseController { @@ -148,7 +148,7 @@ public class EntityRelationController extends BaseController {
148 checkEntityId(fromId); 148 checkEntityId(fromId);
149 checkEntityId(toId); 149 checkEntityId(toId);
150 RelationTypeGroup typeGroup = parseRelationTypeGroup(strRelationTypeGroup, RelationTypeGroup.COMMON); 150 RelationTypeGroup typeGroup = parseRelationTypeGroup(strRelationTypeGroup, RelationTypeGroup.COMMON);
151 - return checkNotNull(relationService.getRelation(fromId, toId, strRelationType, typeGroup)); 151 + return checkNotNull(relationService.getRelation(getTenantId(), fromId, toId, strRelationType, typeGroup));
152 } catch (Exception e) { 152 } catch (Exception e) {
153 throw handleException(e); 153 throw handleException(e);
154 } 154 }
@@ -166,7 +166,7 @@ public class EntityRelationController extends BaseController { @@ -166,7 +166,7 @@ public class EntityRelationController extends BaseController {
166 checkEntityId(entityId); 166 checkEntityId(entityId);
167 RelationTypeGroup typeGroup = parseRelationTypeGroup(strRelationTypeGroup, RelationTypeGroup.COMMON); 167 RelationTypeGroup typeGroup = parseRelationTypeGroup(strRelationTypeGroup, RelationTypeGroup.COMMON);
168 try { 168 try {
169 - return checkNotNull(relationService.findByFrom(entityId, typeGroup)); 169 + return checkNotNull(relationService.findByFrom(getTenantId(), entityId, typeGroup));
170 } catch (Exception e) { 170 } catch (Exception e) {
171 throw handleException(e); 171 throw handleException(e);
172 } 172 }
@@ -184,7 +184,7 @@ public class EntityRelationController extends BaseController { @@ -184,7 +184,7 @@ public class EntityRelationController extends BaseController {
184 checkEntityId(entityId); 184 checkEntityId(entityId);
185 RelationTypeGroup typeGroup = parseRelationTypeGroup(strRelationTypeGroup, RelationTypeGroup.COMMON); 185 RelationTypeGroup typeGroup = parseRelationTypeGroup(strRelationTypeGroup, RelationTypeGroup.COMMON);
186 try { 186 try {
187 - return checkNotNull(relationService.findInfoByFrom(entityId, typeGroup).get()); 187 + return checkNotNull(relationService.findInfoByFrom(getTenantId(), entityId, typeGroup).get());
188 } catch (Exception e) { 188 } catch (Exception e) {
189 throw handleException(e); 189 throw handleException(e);
190 } 190 }
@@ -204,7 +204,7 @@ public class EntityRelationController extends BaseController { @@ -204,7 +204,7 @@ public class EntityRelationController extends BaseController {
204 checkEntityId(entityId); 204 checkEntityId(entityId);
205 RelationTypeGroup typeGroup = parseRelationTypeGroup(strRelationTypeGroup, RelationTypeGroup.COMMON); 205 RelationTypeGroup typeGroup = parseRelationTypeGroup(strRelationTypeGroup, RelationTypeGroup.COMMON);
206 try { 206 try {
207 - return checkNotNull(relationService.findByFromAndType(entityId, strRelationType, typeGroup)); 207 + return checkNotNull(relationService.findByFromAndType(getTenantId(), entityId, strRelationType, typeGroup));
208 } catch (Exception e) { 208 } catch (Exception e) {
209 throw handleException(e); 209 throw handleException(e);
210 } 210 }
@@ -222,7 +222,7 @@ public class EntityRelationController extends BaseController { @@ -222,7 +222,7 @@ public class EntityRelationController extends BaseController {
222 checkEntityId(entityId); 222 checkEntityId(entityId);
223 RelationTypeGroup typeGroup = parseRelationTypeGroup(strRelationTypeGroup, RelationTypeGroup.COMMON); 223 RelationTypeGroup typeGroup = parseRelationTypeGroup(strRelationTypeGroup, RelationTypeGroup.COMMON);
224 try { 224 try {
225 - return checkNotNull(relationService.findByTo(entityId, typeGroup)); 225 + return checkNotNull(relationService.findByTo(getTenantId(), entityId, typeGroup));
226 } catch (Exception e) { 226 } catch (Exception e) {
227 throw handleException(e); 227 throw handleException(e);
228 } 228 }
@@ -240,7 +240,7 @@ public class EntityRelationController extends BaseController { @@ -240,7 +240,7 @@ public class EntityRelationController extends BaseController {
240 checkEntityId(entityId); 240 checkEntityId(entityId);
241 RelationTypeGroup typeGroup = parseRelationTypeGroup(strRelationTypeGroup, RelationTypeGroup.COMMON); 241 RelationTypeGroup typeGroup = parseRelationTypeGroup(strRelationTypeGroup, RelationTypeGroup.COMMON);
242 try { 242 try {
243 - return checkNotNull(relationService.findInfoByTo(entityId, typeGroup).get()); 243 + return checkNotNull(relationService.findInfoByTo(getTenantId(), entityId, typeGroup).get());
244 } catch (Exception e) { 244 } catch (Exception e) {
245 throw handleException(e); 245 throw handleException(e);
246 } 246 }
@@ -260,7 +260,7 @@ public class EntityRelationController extends BaseController { @@ -260,7 +260,7 @@ public class EntityRelationController extends BaseController {
260 checkEntityId(entityId); 260 checkEntityId(entityId);
261 RelationTypeGroup typeGroup = parseRelationTypeGroup(strRelationTypeGroup, RelationTypeGroup.COMMON); 261 RelationTypeGroup typeGroup = parseRelationTypeGroup(strRelationTypeGroup, RelationTypeGroup.COMMON);
262 try { 262 try {
263 - return checkNotNull(relationService.findByToAndType(entityId, strRelationType, typeGroup)); 263 + return checkNotNull(relationService.findByToAndType(getTenantId(), entityId, strRelationType, typeGroup));
264 } catch (Exception e) { 264 } catch (Exception e) {
265 throw handleException(e); 265 throw handleException(e);
266 } 266 }
@@ -275,7 +275,7 @@ public class EntityRelationController extends BaseController { @@ -275,7 +275,7 @@ public class EntityRelationController extends BaseController {
275 checkNotNull(query.getFilters()); 275 checkNotNull(query.getFilters());
276 checkEntityId(query.getParameters().getEntityId()); 276 checkEntityId(query.getParameters().getEntityId());
277 try { 277 try {
278 - return checkNotNull(relationService.findByQuery(query).get()); 278 + return checkNotNull(relationService.findByQuery(getTenantId(), query).get());
279 } catch (Exception e) { 279 } catch (Exception e) {
280 throw handleException(e); 280 throw handleException(e);
281 } 281 }
@@ -290,7 +290,7 @@ public class EntityRelationController extends BaseController { @@ -290,7 +290,7 @@ public class EntityRelationController extends BaseController {
290 checkNotNull(query.getFilters()); 290 checkNotNull(query.getFilters());
291 checkEntityId(query.getParameters().getEntityId()); 291 checkEntityId(query.getParameters().getEntityId());
292 try { 292 try {
293 - return checkNotNull(relationService.findInfoByQuery(query).get()); 293 + return checkNotNull(relationService.findInfoByQuery(getTenantId(), query).get());
294 } catch (Exception e) { 294 } catch (Exception e) {
295 throw handleException(e); 295 throw handleException(e);
296 } 296 }
@@ -114,7 +114,7 @@ public class EntityViewController extends BaseController { @@ -114,7 +114,7 @@ public class EntityViewController extends BaseController {
114 private ListenableFuture<List<Void>> copyAttributesFromEntityToEntityView(EntityView entityView, String scope, Collection<String> keys, SecurityUser user) throws ThingsboardException { 114 private ListenableFuture<List<Void>> copyAttributesFromEntityToEntityView(EntityView entityView, String scope, Collection<String> keys, SecurityUser user) throws ThingsboardException {
115 EntityViewId entityId = entityView.getId(); 115 EntityViewId entityId = entityView.getId();
116 if (keys != null && !keys.isEmpty()) { 116 if (keys != null && !keys.isEmpty()) {
117 - ListenableFuture<List<AttributeKvEntry>> getAttrFuture = attributesService.find(entityView.getEntityId(), scope, keys); 117 + ListenableFuture<List<AttributeKvEntry>> getAttrFuture = attributesService.find(getTenantId(), entityView.getEntityId(), scope, keys);
118 return Futures.transform(getAttrFuture, attributeKvEntries -> { 118 return Futures.transform(getAttrFuture, attributeKvEntries -> {
119 List<AttributeKvEntry> attributes; 119 List<AttributeKvEntry> attributes;
120 if (attributeKvEntries != null && !attributeKvEntries.isEmpty()) { 120 if (attributeKvEntries != null && !attributeKvEntries.isEmpty()) {
@@ -129,7 +129,7 @@ public class EntityViewController extends BaseController { @@ -129,7 +129,7 @@ public class EntityViewController extends BaseController {
129 (startTime == 0 && endTime > lastUpdateTs) 129 (startTime == 0 && endTime > lastUpdateTs)
130 ? true : startTime < lastUpdateTs && endTime > lastUpdateTs; 130 ? true : startTime < lastUpdateTs && endTime > lastUpdateTs;
131 }).collect(Collectors.toList()); 131 }).collect(Collectors.toList());
132 - tsSubService.saveAndNotify(entityId, scope, attributes, new FutureCallback<Void>() { 132 + tsSubService.saveAndNotify(entityView.getTenantId(), entityId, scope, attributes, new FutureCallback<Void>() {
133 @Override 133 @Override
134 public void onSuccess(@Nullable Void tmp) { 134 public void onSuccess(@Nullable Void tmp) {
135 try { 135 try {
@@ -169,7 +169,7 @@ public class EntityViewController extends BaseController { @@ -169,7 +169,7 @@ public class EntityViewController extends BaseController {
169 try { 169 try {
170 EntityViewId entityViewId = new EntityViewId(toUUID(strEntityViewId)); 170 EntityViewId entityViewId = new EntityViewId(toUUID(strEntityViewId));
171 EntityView entityView = checkEntityViewId(entityViewId); 171 EntityView entityView = checkEntityViewId(entityViewId);
172 - entityViewService.deleteEntityView(entityViewId); 172 + entityViewService.deleteEntityView(getTenantId(), entityViewId);
173 logEntityAction(entityViewId, entityView, entityView.getCustomerId(), 173 logEntityAction(entityViewId, entityView, entityView.getCustomerId(),
174 ActionType.DELETED, null, strEntityViewId); 174 ActionType.DELETED, null, strEntityViewId);
175 } catch (Exception e) { 175 } catch (Exception e) {
@@ -208,7 +208,7 @@ public class EntityViewController extends BaseController { @@ -208,7 +208,7 @@ public class EntityViewController extends BaseController {
208 EntityViewId entityViewId = new EntityViewId(toUUID(strEntityViewId)); 208 EntityViewId entityViewId = new EntityViewId(toUUID(strEntityViewId));
209 checkEntityViewId(entityViewId); 209 checkEntityViewId(entityViewId);
210 210
211 - EntityView savedEntityView = checkNotNull(entityViewService.assignEntityViewToCustomer(entityViewId, customerId)); 211 + EntityView savedEntityView = checkNotNull(entityViewService.assignEntityViewToCustomer(getTenantId(), entityViewId, customerId));
212 logEntityAction(entityViewId, savedEntityView, 212 logEntityAction(entityViewId, savedEntityView,
213 savedEntityView.getCustomerId(), 213 savedEntityView.getCustomerId(),
214 ActionType.ASSIGNED_TO_CUSTOMER, null, strEntityViewId, strCustomerId, customer.getName()); 214 ActionType.ASSIGNED_TO_CUSTOMER, null, strEntityViewId, strCustomerId, customer.getName());
@@ -233,7 +233,7 @@ public class EntityViewController extends BaseController { @@ -233,7 +233,7 @@ public class EntityViewController extends BaseController {
233 throw new IncorrectParameterException("Entity View isn't assigned to any customer!"); 233 throw new IncorrectParameterException("Entity View isn't assigned to any customer!");
234 } 234 }
235 Customer customer = checkCustomerId(entityView.getCustomerId()); 235 Customer customer = checkCustomerId(entityView.getCustomerId());
236 - EntityView savedEntityView = checkNotNull(entityViewService.unassignEntityViewFromCustomer(entityViewId)); 236 + EntityView savedEntityView = checkNotNull(entityViewService.unassignEntityViewFromCustomer(getTenantId(), entityViewId));
237 logEntityAction(entityViewId, entityView, 237 logEntityAction(entityViewId, entityView,
238 entityView.getCustomerId(), 238 entityView.getCustomerId(),
239 ActionType.UNASSIGNED_FROM_CUSTOMER, null, strEntityViewId, customer.getId().toString(), customer.getName()); 239 ActionType.UNASSIGNED_FROM_CUSTOMER, null, strEntityViewId, customer.getId().toString(), customer.getName());
@@ -305,7 +305,7 @@ public class EntityViewController extends BaseController { @@ -305,7 +305,7 @@ public class EntityViewController extends BaseController {
305 checkNotNull(query.getEntityViewTypes()); 305 checkNotNull(query.getEntityViewTypes());
306 checkEntityId(query.getParameters().getEntityId()); 306 checkEntityId(query.getParameters().getEntityId());
307 try { 307 try {
308 - List<EntityView> entityViews = checkNotNull(entityViewService.findEntityViewsByQuery(query).get()); 308 + List<EntityView> entityViews = checkNotNull(entityViewService.findEntityViewsByQuery(getTenantId(), query).get());
309 entityViews = entityViews.stream().filter(entityView -> { 309 entityViews = entityViews.stream().filter(entityView -> {
310 try { 310 try {
311 checkEntityView(entityView); 311 checkEntityView(entityView);
@@ -94,7 +94,7 @@ public class RuleChainController extends BaseController { @@ -94,7 +94,7 @@ public class RuleChainController extends BaseController {
94 try { 94 try {
95 RuleChainId ruleChainId = new RuleChainId(toUUID(strRuleChainId)); 95 RuleChainId ruleChainId = new RuleChainId(toUUID(strRuleChainId));
96 checkRuleChain(ruleChainId); 96 checkRuleChain(ruleChainId);
97 - return ruleChainService.loadRuleChainMetaData(ruleChainId); 97 + return ruleChainService.loadRuleChainMetaData(getTenantId(), ruleChainId);
98 } catch (Exception e) { 98 } catch (Exception e) {
99 throw handleException(e); 99 throw handleException(e);
100 } 100 }
@@ -137,9 +137,9 @@ public class RuleChainController extends BaseController { @@ -137,9 +137,9 @@ public class RuleChainController extends BaseController {
137 RuleChain ruleChain = checkRuleChain(ruleChainId); 137 RuleChain ruleChain = checkRuleChain(ruleChainId);
138 TenantId tenantId = getCurrentUser().getTenantId(); 138 TenantId tenantId = getCurrentUser().getTenantId();
139 RuleChain previousRootRuleChain = ruleChainService.getRootTenantRuleChain(tenantId); 139 RuleChain previousRootRuleChain = ruleChainService.getRootTenantRuleChain(tenantId);
140 - if (ruleChainService.setRootRuleChain(ruleChainId)) { 140 + if (ruleChainService.setRootRuleChain(getTenantId(), ruleChainId)) {
141 141
142 - previousRootRuleChain = ruleChainService.findRuleChainById(previousRootRuleChain.getId()); 142 + previousRootRuleChain = ruleChainService.findRuleChainById(getTenantId(), previousRootRuleChain.getId());
143 143
144 actorService.onEntityStateChange(previousRootRuleChain.getTenantId(), previousRootRuleChain.getId(), 144 actorService.onEntityStateChange(previousRootRuleChain.getTenantId(), previousRootRuleChain.getId(),
145 ComponentLifecycleEvent.UPDATED); 145 ComponentLifecycleEvent.UPDATED);
@@ -147,7 +147,7 @@ public class RuleChainController extends BaseController { @@ -147,7 +147,7 @@ public class RuleChainController extends BaseController {
147 logEntityAction(previousRootRuleChain.getId(), previousRootRuleChain, 147 logEntityAction(previousRootRuleChain.getId(), previousRootRuleChain,
148 null, ActionType.UPDATED, null); 148 null, ActionType.UPDATED, null);
149 149
150 - ruleChain = ruleChainService.findRuleChainById(ruleChainId); 150 + ruleChain = ruleChainService.findRuleChainById(getTenantId(), ruleChainId);
151 151
152 actorService.onEntityStateChange(ruleChain.getTenantId(), ruleChain.getId(), 152 actorService.onEntityStateChange(ruleChain.getTenantId(), ruleChain.getId(),
153 ComponentLifecycleEvent.UPDATED); 153 ComponentLifecycleEvent.UPDATED);
@@ -172,7 +172,7 @@ public class RuleChainController extends BaseController { @@ -172,7 +172,7 @@ public class RuleChainController extends BaseController {
172 public RuleChainMetaData saveRuleChainMetaData(@RequestBody RuleChainMetaData ruleChainMetaData) throws ThingsboardException { 172 public RuleChainMetaData saveRuleChainMetaData(@RequestBody RuleChainMetaData ruleChainMetaData) throws ThingsboardException {
173 try { 173 try {
174 RuleChain ruleChain = checkRuleChain(ruleChainMetaData.getRuleChainId()); 174 RuleChain ruleChain = checkRuleChain(ruleChainMetaData.getRuleChainId());
175 - RuleChainMetaData savedRuleChainMetaData = checkNotNull(ruleChainService.saveRuleChainMetaData(ruleChainMetaData)); 175 + RuleChainMetaData savedRuleChainMetaData = checkNotNull(ruleChainService.saveRuleChainMetaData(getTenantId(), ruleChainMetaData));
176 176
177 actorService.onEntityStateChange(ruleChain.getTenantId(), ruleChain.getId(), ComponentLifecycleEvent.UPDATED); 177 actorService.onEntityStateChange(ruleChain.getTenantId(), ruleChain.getId(), ComponentLifecycleEvent.UPDATED);
178 178
@@ -216,7 +216,7 @@ public class RuleChainController extends BaseController { @@ -216,7 +216,7 @@ public class RuleChainController extends BaseController {
216 RuleChainId ruleChainId = new RuleChainId(toUUID(strRuleChainId)); 216 RuleChainId ruleChainId = new RuleChainId(toUUID(strRuleChainId));
217 RuleChain ruleChain = checkRuleChain(ruleChainId); 217 RuleChain ruleChain = checkRuleChain(ruleChainId);
218 218
219 - ruleChainService.deleteRuleChainById(ruleChainId); 219 + ruleChainService.deleteRuleChainById(getTenantId(), ruleChainId);
220 220
221 actorService.onEntityStateChange(ruleChain.getTenantId(), ruleChain.getId(), ComponentLifecycleEvent.DELETED); 221 actorService.onEntityStateChange(ruleChain.getTenantId(), ruleChain.getId(), ComponentLifecycleEvent.DELETED);
222 222
@@ -44,6 +44,7 @@ import org.thingsboard.server.common.data.exception.ThingsboardException; @@ -44,6 +44,7 @@ import org.thingsboard.server.common.data.exception.ThingsboardException;
44 import org.thingsboard.server.common.data.id.DeviceId; 44 import org.thingsboard.server.common.data.id.DeviceId;
45 import org.thingsboard.server.common.data.id.EntityId; 45 import org.thingsboard.server.common.data.id.EntityId;
46 import org.thingsboard.server.common.data.id.EntityIdFactory; 46 import org.thingsboard.server.common.data.id.EntityIdFactory;
  47 +import org.thingsboard.server.common.data.id.TenantId;
47 import org.thingsboard.server.common.data.id.UUIDBased; 48 import org.thingsboard.server.common.data.id.UUIDBased;
48 import org.thingsboard.server.common.data.kv.Aggregation; 49 import org.thingsboard.server.common.data.kv.Aggregation;
49 import org.thingsboard.server.common.data.kv.AttributeKey; 50 import org.thingsboard.server.common.data.kv.AttributeKey;
@@ -127,7 +128,7 @@ public class TelemetryController extends BaseController { @@ -127,7 +128,7 @@ public class TelemetryController extends BaseController {
127 @PathVariable("entityType") String entityType, @PathVariable("entityId") String entityIdStr 128 @PathVariable("entityType") String entityType, @PathVariable("entityId") String entityIdStr
128 , @PathVariable("scope") String scope) throws ThingsboardException { 129 , @PathVariable("scope") String scope) throws ThingsboardException {
129 return accessValidator.validateEntityAndCallback(getCurrentUser(), entityType, entityIdStr, 130 return accessValidator.validateEntityAndCallback(getCurrentUser(), entityType, entityIdStr,
130 - (result, entityId) -> getAttributeKeysCallback(result, entityId, scope)); 131 + (result, tenantId, entityId) -> getAttributeKeysCallback(result, tenantId, entityId, scope));
131 } 132 }
132 133
133 @PreAuthorize("hasAnyAuthority('SYS_ADMIN', 'TENANT_ADMIN', 'CUSTOMER_USER')") 134 @PreAuthorize("hasAnyAuthority('SYS_ADMIN', 'TENANT_ADMIN', 'CUSTOMER_USER')")
@@ -138,7 +139,7 @@ public class TelemetryController extends BaseController { @@ -138,7 +139,7 @@ public class TelemetryController extends BaseController {
138 @RequestParam(name = "keys", required = false) String keysStr) throws ThingsboardException { 139 @RequestParam(name = "keys", required = false) String keysStr) throws ThingsboardException {
139 SecurityUser user = getCurrentUser(); 140 SecurityUser user = getCurrentUser();
140 return accessValidator.validateEntityAndCallback(getCurrentUser(), entityType, entityIdStr, 141 return accessValidator.validateEntityAndCallback(getCurrentUser(), entityType, entityIdStr,
141 - (result, entityId) -> getAttributeValuesCallback(result, user, entityId, null, keysStr)); 142 + (result, tenantId, entityId) -> getAttributeValuesCallback(result, user, entityId, null, keysStr));
142 } 143 }
143 144
144 @PreAuthorize("hasAnyAuthority('SYS_ADMIN', 'TENANT_ADMIN', 'CUSTOMER_USER')") 145 @PreAuthorize("hasAnyAuthority('SYS_ADMIN', 'TENANT_ADMIN', 'CUSTOMER_USER')")
@@ -150,7 +151,7 @@ public class TelemetryController extends BaseController { @@ -150,7 +151,7 @@ public class TelemetryController extends BaseController {
150 @RequestParam(name = "keys", required = false) String keysStr) throws ThingsboardException { 151 @RequestParam(name = "keys", required = false) String keysStr) throws ThingsboardException {
151 SecurityUser user = getCurrentUser(); 152 SecurityUser user = getCurrentUser();
152 return accessValidator.validateEntityAndCallback(getCurrentUser(), entityType, entityIdStr, 153 return accessValidator.validateEntityAndCallback(getCurrentUser(), entityType, entityIdStr,
153 - (result, entityId) -> getAttributeValuesCallback(result, user, entityId, scope, keysStr)); 154 + (result, tenantId, entityId) -> getAttributeValuesCallback(result, user, entityId, scope, keysStr));
154 } 155 }
155 156
156 @PreAuthorize("hasAnyAuthority('SYS_ADMIN', 'TENANT_ADMIN', 'CUSTOMER_USER')") 157 @PreAuthorize("hasAnyAuthority('SYS_ADMIN', 'TENANT_ADMIN', 'CUSTOMER_USER')")
@@ -159,9 +160,7 @@ public class TelemetryController extends BaseController { @@ -159,9 +160,7 @@ public class TelemetryController extends BaseController {
159 public DeferredResult<ResponseEntity> getTimeseriesKeys( 160 public DeferredResult<ResponseEntity> getTimeseriesKeys(
160 @PathVariable("entityType") String entityType, @PathVariable("entityId") String entityIdStr) throws ThingsboardException { 161 @PathVariable("entityType") String entityType, @PathVariable("entityId") String entityIdStr) throws ThingsboardException {
161 return accessValidator.validateEntityAndCallback(getCurrentUser(), entityType, entityIdStr, 162 return accessValidator.validateEntityAndCallback(getCurrentUser(), entityType, entityIdStr,
162 - (result, entityId) -> {  
163 - Futures.addCallback(tsService.findAllLatest(entityId), getTsKeysToResponseCallback(result));  
164 - }); 163 + (result, tenantId, entityId) -> Futures.addCallback(tsService.findAllLatest(tenantId, entityId), getTsKeysToResponseCallback(result)));
165 } 164 }
166 165
167 @PreAuthorize("hasAnyAuthority('SYS_ADMIN', 'TENANT_ADMIN', 'CUSTOMER_USER')") 166 @PreAuthorize("hasAnyAuthority('SYS_ADMIN', 'TENANT_ADMIN', 'CUSTOMER_USER')")
@@ -173,7 +172,7 @@ public class TelemetryController extends BaseController { @@ -173,7 +172,7 @@ public class TelemetryController extends BaseController {
173 SecurityUser user = getCurrentUser(); 172 SecurityUser user = getCurrentUser();
174 173
175 return accessValidator.validateEntityAndCallback(getCurrentUser(), entityType, entityIdStr, 174 return accessValidator.validateEntityAndCallback(getCurrentUser(), entityType, entityIdStr,
176 - (result, entityId) -> getLatestTimeseriesValuesCallback(result, user, entityId, keysStr)); 175 + (result, tenantId, entityId) -> getLatestTimeseriesValuesCallback(result, user, entityId, keysStr));
177 } 176 }
178 177
179 178
@@ -190,13 +189,13 @@ public class TelemetryController extends BaseController { @@ -190,13 +189,13 @@ public class TelemetryController extends BaseController {
190 @RequestParam(name = "agg", defaultValue = "NONE") String aggStr 189 @RequestParam(name = "agg", defaultValue = "NONE") String aggStr
191 ) throws ThingsboardException { 190 ) throws ThingsboardException {
192 return accessValidator.validateEntityAndCallback(getCurrentUser(), entityType, entityIdStr, 191 return accessValidator.validateEntityAndCallback(getCurrentUser(), entityType, entityIdStr,
193 - (result, entityId) -> { 192 + (result, tenantId, entityId) -> {
194 // If interval is 0, convert this to a NONE aggregation, which is probably what the user really wanted 193 // If interval is 0, convert this to a NONE aggregation, which is probably what the user really wanted
195 Aggregation agg = interval == 0L ? Aggregation.valueOf(Aggregation.NONE.name()) : Aggregation.valueOf(aggStr); 194 Aggregation agg = interval == 0L ? Aggregation.valueOf(Aggregation.NONE.name()) : Aggregation.valueOf(aggStr);
196 List<ReadTsKvQuery> queries = toKeysList(keys).stream().map(key -> new BaseReadTsKvQuery(key, startTs, endTs, interval, limit, agg)) 195 List<ReadTsKvQuery> queries = toKeysList(keys).stream().map(key -> new BaseReadTsKvQuery(key, startTs, endTs, interval, limit, agg))
197 .collect(Collectors.toList()); 196 .collect(Collectors.toList());
198 197
199 - Futures.addCallback(tsService.findAll(entityId, queries), getTsKvListCallback(result)); 198 + Futures.addCallback(tsService.findAll(tenantId, entityId, queries), getTsKvListCallback(result));
200 }); 199 });
201 } 200 }
202 201
@@ -206,7 +205,7 @@ public class TelemetryController extends BaseController { @@ -206,7 +205,7 @@ public class TelemetryController extends BaseController {
206 public DeferredResult<ResponseEntity> saveDeviceAttributes(@PathVariable("deviceId") String deviceIdStr, @PathVariable("scope") String scope, 205 public DeferredResult<ResponseEntity> saveDeviceAttributes(@PathVariable("deviceId") String deviceIdStr, @PathVariable("scope") String scope,
207 @RequestBody JsonNode request) throws ThingsboardException { 206 @RequestBody JsonNode request) throws ThingsboardException {
208 EntityId entityId = EntityIdFactory.getByTypeAndUuid(EntityType.DEVICE, deviceIdStr); 207 EntityId entityId = EntityIdFactory.getByTypeAndUuid(EntityType.DEVICE, deviceIdStr);
209 - return saveAttributes(entityId, scope, request); 208 + return saveAttributes(getTenantId(), entityId, scope, request);
210 } 209 }
211 210
212 @PreAuthorize("hasAnyAuthority('SYS_ADMIN', 'TENANT_ADMIN', 'CUSTOMER_USER')") 211 @PreAuthorize("hasAnyAuthority('SYS_ADMIN', 'TENANT_ADMIN', 'CUSTOMER_USER')")
@@ -216,7 +215,7 @@ public class TelemetryController extends BaseController { @@ -216,7 +215,7 @@ public class TelemetryController extends BaseController {
216 @PathVariable("scope") String scope, 215 @PathVariable("scope") String scope,
217 @RequestBody JsonNode request) throws ThingsboardException { 216 @RequestBody JsonNode request) throws ThingsboardException {
218 EntityId entityId = EntityIdFactory.getByTypeAndId(entityType, entityIdStr); 217 EntityId entityId = EntityIdFactory.getByTypeAndId(entityType, entityIdStr);
219 - return saveAttributes(entityId, scope, request); 218 + return saveAttributes(getTenantId(), entityId, scope, request);
220 } 219 }
221 220
222 @PreAuthorize("hasAnyAuthority('SYS_ADMIN', 'TENANT_ADMIN', 'CUSTOMER_USER')") 221 @PreAuthorize("hasAnyAuthority('SYS_ADMIN', 'TENANT_ADMIN', 'CUSTOMER_USER')")
@@ -226,7 +225,7 @@ public class TelemetryController extends BaseController { @@ -226,7 +225,7 @@ public class TelemetryController extends BaseController {
226 @PathVariable("scope") String scope, 225 @PathVariable("scope") String scope,
227 @RequestBody JsonNode request) throws ThingsboardException { 226 @RequestBody JsonNode request) throws ThingsboardException {
228 EntityId entityId = EntityIdFactory.getByTypeAndId(entityType, entityIdStr); 227 EntityId entityId = EntityIdFactory.getByTypeAndId(entityType, entityIdStr);
229 - return saveAttributes(entityId, scope, request); 228 + return saveAttributes(getTenantId(), entityId, scope, request);
230 } 229 }
231 230
232 @PreAuthorize("hasAnyAuthority('SYS_ADMIN', 'TENANT_ADMIN', 'CUSTOMER_USER')") 231 @PreAuthorize("hasAnyAuthority('SYS_ADMIN', 'TENANT_ADMIN', 'CUSTOMER_USER')")
@@ -236,7 +235,7 @@ public class TelemetryController extends BaseController { @@ -236,7 +235,7 @@ public class TelemetryController extends BaseController {
236 @PathVariable("scope") String scope, 235 @PathVariable("scope") String scope,
237 @RequestBody String requestBody) throws ThingsboardException { 236 @RequestBody String requestBody) throws ThingsboardException {
238 EntityId entityId = EntityIdFactory.getByTypeAndId(entityType, entityIdStr); 237 EntityId entityId = EntityIdFactory.getByTypeAndId(entityType, entityIdStr);
239 - return saveTelemetry(entityId, requestBody, 0L); 238 + return saveTelemetry(getTenantId(), entityId, requestBody, 0L);
240 } 239 }
241 240
242 @PreAuthorize("hasAnyAuthority('SYS_ADMIN', 'TENANT_ADMIN', 'CUSTOMER_USER')") 241 @PreAuthorize("hasAnyAuthority('SYS_ADMIN', 'TENANT_ADMIN', 'CUSTOMER_USER')")
@@ -246,7 +245,7 @@ public class TelemetryController extends BaseController { @@ -246,7 +245,7 @@ public class TelemetryController extends BaseController {
246 @PathVariable("scope") String scope, @PathVariable("ttl") Long ttl, 245 @PathVariable("scope") String scope, @PathVariable("ttl") Long ttl,
247 @RequestBody String requestBody) throws ThingsboardException { 246 @RequestBody String requestBody) throws ThingsboardException {
248 EntityId entityId = EntityIdFactory.getByTypeAndId(entityType, entityIdStr); 247 EntityId entityId = EntityIdFactory.getByTypeAndId(entityType, entityIdStr);
249 - return saveTelemetry(entityId, requestBody, ttl); 248 + return saveTelemetry(getTenantId(), entityId, requestBody, ttl);
250 } 249 }
251 250
252 @PreAuthorize("hasAnyAuthority('SYS_ADMIN', 'TENANT_ADMIN', 'CUSTOMER_USER')") 251 @PreAuthorize("hasAnyAuthority('SYS_ADMIN', 'TENANT_ADMIN', 'CUSTOMER_USER')")
@@ -280,13 +279,13 @@ public class TelemetryController extends BaseController { @@ -280,13 +279,13 @@ public class TelemetryController extends BaseController {
280 deleteToTs = endTs; 279 deleteToTs = endTs;
281 } 280 }
282 281
283 - return accessValidator.validateEntityAndCallback(user, entityIdStr, (result, entityId) -> { 282 + return accessValidator.validateEntityAndCallback(user, entityIdStr, (result, tenantId, entityId) -> {
284 List<DeleteTsKvQuery> deleteTsKvQueries = new ArrayList<>(); 283 List<DeleteTsKvQuery> deleteTsKvQueries = new ArrayList<>();
285 for (String key : keys) { 284 for (String key : keys) {
286 deleteTsKvQueries.add(new BaseDeleteTsKvQuery(key, deleteFromTs, deleteToTs, rewriteLatestIfDeleted)); 285 deleteTsKvQueries.add(new BaseDeleteTsKvQuery(key, deleteFromTs, deleteToTs, rewriteLatestIfDeleted));
287 } 286 }
288 287
289 - ListenableFuture<List<Void>> future = tsService.remove(entityId, deleteTsKvQueries); 288 + ListenableFuture<List<Void>> future = tsService.remove(user.getTenantId(), entityId, deleteTsKvQueries);
290 Futures.addCallback(future, new FutureCallback<List<Void>>() { 289 Futures.addCallback(future, new FutureCallback<List<Void>>() {
291 @Override 290 @Override
292 public void onSuccess(@Nullable List<Void> tmp) { 291 public void onSuccess(@Nullable List<Void> tmp) {
@@ -333,8 +332,8 @@ public class TelemetryController extends BaseController { @@ -333,8 +332,8 @@ public class TelemetryController extends BaseController {
333 if (DataConstants.SERVER_SCOPE.equals(scope) || 332 if (DataConstants.SERVER_SCOPE.equals(scope) ||
334 DataConstants.SHARED_SCOPE.equals(scope) || 333 DataConstants.SHARED_SCOPE.equals(scope) ||
335 DataConstants.CLIENT_SCOPE.equals(scope)) { 334 DataConstants.CLIENT_SCOPE.equals(scope)) {
336 - return accessValidator.validateEntityAndCallback(getCurrentUser(), entityIdStr, (result, entityId) -> {  
337 - ListenableFuture<List<Void>> future = attributesService.removeAll(entityId, scope, keys); 335 + return accessValidator.validateEntityAndCallback(getCurrentUser(), entityIdStr, (result, tenantId, entityId) -> {
  336 + ListenableFuture<List<Void>> future = attributesService.removeAll(user.getTenantId(), entityId, scope, keys);
338 Futures.addCallback(future, new FutureCallback<List<Void>>() { 337 Futures.addCallback(future, new FutureCallback<List<Void>>() {
339 @Override 338 @Override
340 public void onSuccess(@Nullable List<Void> tmp) { 339 public void onSuccess(@Nullable List<Void> tmp) {
@@ -362,7 +361,7 @@ public class TelemetryController extends BaseController { @@ -362,7 +361,7 @@ public class TelemetryController extends BaseController {
362 } 361 }
363 } 362 }
364 363
365 - private DeferredResult<ResponseEntity> saveAttributes(EntityId entityIdSrc, String scope, JsonNode json) throws ThingsboardException { 364 + private DeferredResult<ResponseEntity> saveAttributes(TenantId srcTenantId, EntityId entityIdSrc, String scope, JsonNode json) throws ThingsboardException {
366 if (!DataConstants.SERVER_SCOPE.equals(scope) && !DataConstants.SHARED_SCOPE.equals(scope)) { 365 if (!DataConstants.SERVER_SCOPE.equals(scope) && !DataConstants.SHARED_SCOPE.equals(scope)) {
367 return getImmediateDeferredResult("Invalid scope: " + scope, HttpStatus.BAD_REQUEST); 366 return getImmediateDeferredResult("Invalid scope: " + scope, HttpStatus.BAD_REQUEST);
368 } 367 }
@@ -372,8 +371,8 @@ public class TelemetryController extends BaseController { @@ -372,8 +371,8 @@ public class TelemetryController extends BaseController {
372 return getImmediateDeferredResult("No attributes data found in request body!", HttpStatus.BAD_REQUEST); 371 return getImmediateDeferredResult("No attributes data found in request body!", HttpStatus.BAD_REQUEST);
373 } 372 }
374 SecurityUser user = getCurrentUser(); 373 SecurityUser user = getCurrentUser();
375 - return accessValidator.validateEntityAndCallback(getCurrentUser(), entityIdSrc, (result, entityId) -> {  
376 - tsSubService.saveAndNotify(entityId, scope, attributes, new FutureCallback<Void>() { 374 + return accessValidator.validateEntityAndCallback(getCurrentUser(), entityIdSrc, (result, tenantId, entityId) -> {
  375 + tsSubService.saveAndNotify(tenantId, entityId, scope, attributes, new FutureCallback<Void>() {
377 @Override 376 @Override
378 public void onSuccess(@Nullable Void tmp) { 377 public void onSuccess(@Nullable Void tmp) {
379 logAttributesUpdated(user, entityId, scope, attributes, null); 378 logAttributesUpdated(user, entityId, scope, attributes, null);
@@ -398,7 +397,7 @@ public class TelemetryController extends BaseController { @@ -398,7 +397,7 @@ public class TelemetryController extends BaseController {
398 } 397 }
399 } 398 }
400 399
401 - private DeferredResult<ResponseEntity> saveTelemetry(EntityId entityIdSrc, String requestBody, long ttl) throws ThingsboardException { 400 + private DeferredResult<ResponseEntity> saveTelemetry(TenantId curTenantId, EntityId entityIdSrc, String requestBody, long ttl) throws ThingsboardException {
402 Map<Long, List<KvEntry>> telemetryRequest; 401 Map<Long, List<KvEntry>> telemetryRequest;
403 JsonElement telemetryJson; 402 JsonElement telemetryJson;
404 try { 403 try {
@@ -421,8 +420,8 @@ public class TelemetryController extends BaseController { @@ -421,8 +420,8 @@ public class TelemetryController extends BaseController {
421 return getImmediateDeferredResult("No timeseries data found in request body!", HttpStatus.BAD_REQUEST); 420 return getImmediateDeferredResult("No timeseries data found in request body!", HttpStatus.BAD_REQUEST);
422 } 421 }
423 SecurityUser user = getCurrentUser(); 422 SecurityUser user = getCurrentUser();
424 - return accessValidator.validateEntityAndCallback(getCurrentUser(), entityIdSrc, (result, entityId) -> {  
425 - tsSubService.saveAndNotify(entityId, entries, ttl, new FutureCallback<Void>() { 423 + return accessValidator.validateEntityAndCallback(getCurrentUser(), entityIdSrc, (result, tenantId, entityId) -> {
  424 + tsSubService.saveAndNotify(tenantId, entityId, entries, ttl, new FutureCallback<Void>() {
426 @Override 425 @Override
427 public void onSuccess(@Nullable Void tmp) { 426 public void onSuccess(@Nullable Void tmp) {
428 result.setResult(new ResponseEntity(HttpStatus.OK)); 427 result.setResult(new ResponseEntity(HttpStatus.OK));
@@ -439,9 +438,9 @@ public class TelemetryController extends BaseController { @@ -439,9 +438,9 @@ public class TelemetryController extends BaseController {
439 private void getLatestTimeseriesValuesCallback(@Nullable DeferredResult<ResponseEntity> result, SecurityUser user, EntityId entityId, String keys) { 438 private void getLatestTimeseriesValuesCallback(@Nullable DeferredResult<ResponseEntity> result, SecurityUser user, EntityId entityId, String keys) {
440 ListenableFuture<List<TsKvEntry>> future; 439 ListenableFuture<List<TsKvEntry>> future;
441 if (StringUtils.isEmpty(keys)) { 440 if (StringUtils.isEmpty(keys)) {
442 - future = tsService.findAllLatest(entityId); 441 + future = tsService.findAllLatest(user.getTenantId(), entityId);
443 } else { 442 } else {
444 - future = tsService.findLatest(entityId, toKeysList(keys)); 443 + future = tsService.findLatest(user.getTenantId(), entityId, toKeysList(keys));
445 } 444 }
446 Futures.addCallback(future, getTsKvListCallback(result)); 445 Futures.addCallback(future, getTsKvListCallback(result));
447 } 446 }
@@ -451,17 +450,17 @@ public class TelemetryController extends BaseController { @@ -451,17 +450,17 @@ public class TelemetryController extends BaseController {
451 FutureCallback<List<AttributeKvEntry>> callback = getAttributeValuesToResponseCallback(result, user, scope, entityId, keyList); 450 FutureCallback<List<AttributeKvEntry>> callback = getAttributeValuesToResponseCallback(result, user, scope, entityId, keyList);
452 if (!StringUtils.isEmpty(scope)) { 451 if (!StringUtils.isEmpty(scope)) {
453 if (keyList != null && !keyList.isEmpty()) { 452 if (keyList != null && !keyList.isEmpty()) {
454 - Futures.addCallback(attributesService.find(entityId, scope, keyList), callback); 453 + Futures.addCallback(attributesService.find(user.getTenantId(), entityId, scope, keyList), callback);
455 } else { 454 } else {
456 - Futures.addCallback(attributesService.findAll(entityId, scope), callback); 455 + Futures.addCallback(attributesService.findAll(user.getTenantId(), entityId, scope), callback);
457 } 456 }
458 } else { 457 } else {
459 List<ListenableFuture<List<AttributeKvEntry>>> futures = new ArrayList<>(); 458 List<ListenableFuture<List<AttributeKvEntry>>> futures = new ArrayList<>();
460 for (String tmpScope : DataConstants.allScopes()) { 459 for (String tmpScope : DataConstants.allScopes()) {
461 if (keyList != null && !keyList.isEmpty()) { 460 if (keyList != null && !keyList.isEmpty()) {
462 - futures.add(attributesService.find(entityId, tmpScope, keyList)); 461 + futures.add(attributesService.find(user.getTenantId(), entityId, tmpScope, keyList));
463 } else { 462 } else {
464 - futures.add(attributesService.findAll(entityId, tmpScope)); 463 + futures.add(attributesService.findAll(user.getTenantId(), entityId, tmpScope));
465 } 464 }
466 } 465 }
467 466
@@ -471,14 +470,14 @@ public class TelemetryController extends BaseController { @@ -471,14 +470,14 @@ public class TelemetryController extends BaseController {
471 } 470 }
472 } 471 }
473 472
474 - private void getAttributeKeysCallback(@Nullable DeferredResult<ResponseEntity> result, EntityId entityId, String scope) {  
475 - Futures.addCallback(attributesService.findAll(entityId, scope), getAttributeKeysToResponseCallback(result)); 473 + private void getAttributeKeysCallback(@Nullable DeferredResult<ResponseEntity> result, TenantId tenantId, EntityId entityId, String scope) {
  474 + Futures.addCallback(attributesService.findAll(tenantId, entityId, scope), getAttributeKeysToResponseCallback(result));
476 } 475 }
477 476
478 - private void getAttributeKeysCallback(@Nullable DeferredResult<ResponseEntity> result, EntityId entityId) { 477 + private void getAttributeKeysCallback(@Nullable DeferredResult<ResponseEntity> result, TenantId tenantId, EntityId entityId) {
479 List<ListenableFuture<List<AttributeKvEntry>>> futures = new ArrayList<>(); 478 List<ListenableFuture<List<AttributeKvEntry>>> futures = new ArrayList<>();
480 for (String scope : DataConstants.allScopes()) { 479 for (String scope : DataConstants.allScopes()) {
481 - futures.add(attributesService.findAll(entityId, scope)); 480 + futures.add(attributesService.findAll(tenantId, entityId, scope));
482 } 481 }
483 482
484 ListenableFuture<List<AttributeKvEntry>> future = mergeAllAttributesFutures(futures); 483 ListenableFuture<List<AttributeKvEntry>> future = mergeAllAttributesFutures(futures);
@@ -107,14 +107,14 @@ public class UserController extends BaseController { @@ -107,14 +107,14 @@ public class UserController extends BaseController {
107 try { 107 try {
108 UserId userId = new UserId(toUUID(strUserId)); 108 UserId userId = new UserId(toUUID(strUserId));
109 SecurityUser authUser = getCurrentUser(); 109 SecurityUser authUser = getCurrentUser();
110 - User user = userService.findUserById(userId); 110 + User user = userService.findUserById(authUser.getTenantId(), userId);
111 if (!userTokenAccessEnabled || (authUser.getAuthority() == Authority.SYS_ADMIN && user.getAuthority() != Authority.TENANT_ADMIN) 111 if (!userTokenAccessEnabled || (authUser.getAuthority() == Authority.SYS_ADMIN && user.getAuthority() != Authority.TENANT_ADMIN)
112 || (authUser.getAuthority() == Authority.TENANT_ADMIN && !authUser.getTenantId().equals(user.getTenantId()))) { 112 || (authUser.getAuthority() == Authority.TENANT_ADMIN && !authUser.getTenantId().equals(user.getTenantId()))) {
113 throw new ThingsboardException(YOU_DON_T_HAVE_PERMISSION_TO_PERFORM_THIS_OPERATION, 113 throw new ThingsboardException(YOU_DON_T_HAVE_PERMISSION_TO_PERFORM_THIS_OPERATION,
114 ThingsboardErrorCode.PERMISSION_DENIED); 114 ThingsboardErrorCode.PERMISSION_DENIED);
115 } 115 }
116 UserPrincipal principal = new UserPrincipal(UserPrincipal.Type.USER_NAME, user.getEmail()); 116 UserPrincipal principal = new UserPrincipal(UserPrincipal.Type.USER_NAME, user.getEmail());
117 - UserCredentials credentials = userService.findUserCredentialsByUserId(userId); 117 + UserCredentials credentials = userService.findUserCredentialsByUserId(authUser.getTenantId(), userId);
118 SecurityUser securityUser = new SecurityUser(user, credentials.isEnabled(), principal); 118 SecurityUser securityUser = new SecurityUser(user, credentials.isEnabled(), principal);
119 JwtToken accessToken = tokenFactory.createAccessJwtToken(securityUser); 119 JwtToken accessToken = tokenFactory.createAccessJwtToken(securityUser);
120 JwtToken refreshToken = refreshTokenRepository.requestRefreshToken(securityUser); 120 JwtToken refreshToken = refreshTokenRepository.requestRefreshToken(securityUser);
@@ -146,7 +146,7 @@ public class UserController extends BaseController { @@ -146,7 +146,7 @@ public class UserController extends BaseController {
146 } 146 }
147 User savedUser = checkNotNull(userService.saveUser(user)); 147 User savedUser = checkNotNull(userService.saveUser(user));
148 if (sendEmail) { 148 if (sendEmail) {
149 - UserCredentials userCredentials = userService.findUserCredentialsByUserId(savedUser.getId()); 149 + UserCredentials userCredentials = userService.findUserCredentialsByUserId(authUser.getTenantId(), savedUser.getId());
150 String baseUrl = constructBaseUrl(request); 150 String baseUrl = constructBaseUrl(request);
151 String activateUrl = String.format(ACTIVATE_URL_PATTERN, baseUrl, 151 String activateUrl = String.format(ACTIVATE_URL_PATTERN, baseUrl,
152 userCredentials.getActivateToken()); 152 userCredentials.getActivateToken());
@@ -154,7 +154,7 @@ public class UserController extends BaseController { @@ -154,7 +154,7 @@ public class UserController extends BaseController {
154 try { 154 try {
155 mailService.sendActivationEmail(activateUrl, email); 155 mailService.sendActivationEmail(activateUrl, email);
156 } catch (ThingsboardException e) { 156 } catch (ThingsboardException e) {
157 - userService.deleteUser(savedUser.getId()); 157 + userService.deleteUser(authUser.getTenantId(), savedUser.getId());
158 throw e; 158 throw e;
159 } 159 }
160 } 160 }
@@ -180,8 +180,8 @@ public class UserController extends BaseController { @@ -180,8 +180,8 @@ public class UserController extends BaseController {
180 @RequestParam(value = "email") String email, 180 @RequestParam(value = "email") String email,
181 HttpServletRequest request) throws ThingsboardException { 181 HttpServletRequest request) throws ThingsboardException {
182 try { 182 try {
183 - User user = checkNotNull(userService.findUserByEmail(email));  
184 - UserCredentials userCredentials = userService.findUserCredentialsByUserId(user.getId()); 183 + User user = checkNotNull(userService.findUserByEmail(getCurrentUser().getTenantId(), email));
  184 + UserCredentials userCredentials = userService.findUserCredentialsByUserId(getCurrentUser().getTenantId(), user.getId());
185 if (!userCredentials.isEnabled()) { 185 if (!userCredentials.isEnabled()) {
186 String baseUrl = constructBaseUrl(request); 186 String baseUrl = constructBaseUrl(request);
187 String activateUrl = String.format(ACTIVATE_URL_PATTERN, baseUrl, 187 String activateUrl = String.format(ACTIVATE_URL_PATTERN, baseUrl,
@@ -210,7 +210,7 @@ public class UserController extends BaseController { @@ -210,7 +210,7 @@ public class UserController extends BaseController {
210 ThingsboardErrorCode.PERMISSION_DENIED); 210 ThingsboardErrorCode.PERMISSION_DENIED);
211 } 211 }
212 User user = checkUserId(userId); 212 User user = checkUserId(userId);
213 - UserCredentials userCredentials = userService.findUserCredentialsByUserId(user.getId()); 213 + UserCredentials userCredentials = userService.findUserCredentialsByUserId(getCurrentUser().getTenantId(), user.getId());
214 if (!userCredentials.isEnabled()) { 214 if (!userCredentials.isEnabled()) {
215 String baseUrl = constructBaseUrl(request); 215 String baseUrl = constructBaseUrl(request);
216 String activateUrl = String.format(ACTIVATE_URL_PATTERN, baseUrl, 216 String activateUrl = String.format(ACTIVATE_URL_PATTERN, baseUrl,
@@ -232,7 +232,7 @@ public class UserController extends BaseController { @@ -232,7 +232,7 @@ public class UserController extends BaseController {
232 try { 232 try {
233 UserId userId = new UserId(toUUID(strUserId)); 233 UserId userId = new UserId(toUUID(strUserId));
234 User user = checkUserId(userId); 234 User user = checkUserId(userId);
235 - userService.deleteUser(userId); 235 + userService.deleteUser(getCurrentUser().getTenantId(), userId);
236 236
237 logEntityAction(userId, user, 237 logEntityAction(userId, user,
238 user.getCustomerId(), 238 user.getCustomerId(),
@@ -75,7 +75,7 @@ public class WidgetTypeController extends BaseController { @@ -75,7 +75,7 @@ public class WidgetTypeController extends BaseController {
75 try { 75 try {
76 WidgetTypeId widgetTypeId = new WidgetTypeId(toUUID(strWidgetTypeId)); 76 WidgetTypeId widgetTypeId = new WidgetTypeId(toUUID(strWidgetTypeId));
77 checkWidgetTypeId(widgetTypeId, true); 77 checkWidgetTypeId(widgetTypeId, true);
78 - widgetTypeService.deleteWidgetType(widgetTypeId); 78 + widgetTypeService.deleteWidgetType(getCurrentUser().getTenantId(), widgetTypeId);
79 } catch (Exception e) { 79 } catch (Exception e) {
80 throw handleException(e); 80 throw handleException(e);
81 } 81 }
@@ -77,7 +77,7 @@ public class WidgetsBundleController extends BaseController { @@ -77,7 +77,7 @@ public class WidgetsBundleController extends BaseController {
77 try { 77 try {
78 WidgetsBundleId widgetsBundleId = new WidgetsBundleId(toUUID(strWidgetsBundleId)); 78 WidgetsBundleId widgetsBundleId = new WidgetsBundleId(toUUID(strWidgetsBundleId));
79 checkWidgetsBundleId(widgetsBundleId, true); 79 checkWidgetsBundleId(widgetsBundleId, true);
80 - widgetsBundleService.deleteWidgetsBundle(widgetsBundleId); 80 + widgetsBundleService.deleteWidgetsBundle(getTenantId(), widgetsBundleId);
81 } catch (Exception e) { 81 } catch (Exception e) {
82 throw handleException(e); 82 throw handleException(e);
83 } 83 }
@@ -94,7 +94,7 @@ public class WidgetsBundleController extends BaseController { @@ -94,7 +94,7 @@ public class WidgetsBundleController extends BaseController {
94 try { 94 try {
95 TextPageLink pageLink = createPageLink(limit, textSearch, idOffset, textOffset); 95 TextPageLink pageLink = createPageLink(limit, textSearch, idOffset, textOffset);
96 if (getCurrentUser().getAuthority() == Authority.SYS_ADMIN) { 96 if (getCurrentUser().getAuthority() == Authority.SYS_ADMIN) {
97 - return checkNotNull(widgetsBundleService.findSystemWidgetsBundlesByPageLink(pageLink)); 97 + return checkNotNull(widgetsBundleService.findSystemWidgetsBundlesByPageLink(getTenantId(), pageLink));
98 } else { 98 } else {
99 TenantId tenantId = getCurrentUser().getTenantId(); 99 TenantId tenantId = getCurrentUser().getTenantId();
100 return checkNotNull(widgetsBundleService.findAllTenantWidgetsBundlesByTenantIdAndPageLink(tenantId, pageLink)); 100 return checkNotNull(widgetsBundleService.findAllTenantWidgetsBundlesByTenantIdAndPageLink(tenantId, pageLink));
@@ -110,7 +110,7 @@ public class WidgetsBundleController extends BaseController { @@ -110,7 +110,7 @@ public class WidgetsBundleController extends BaseController {
110 public List<WidgetsBundle> getWidgetsBundles() throws ThingsboardException { 110 public List<WidgetsBundle> getWidgetsBundles() throws ThingsboardException {
111 try { 111 try {
112 if (getCurrentUser().getAuthority() == Authority.SYS_ADMIN) { 112 if (getCurrentUser().getAuthority() == Authority.SYS_ADMIN) {
113 - return checkNotNull(widgetsBundleService.findSystemWidgetsBundles()); 113 + return checkNotNull(widgetsBundleService.findSystemWidgetsBundles(getTenantId()));
114 } else { 114 } else {
115 TenantId tenantId = getCurrentUser().getTenantId(); 115 TenantId tenantId = getCurrentUser().getTenantId();
116 return checkNotNull(widgetsBundleService.findAllTenantWidgetsBundlesByTenantId(tenantId)); 116 return checkNotNull(widgetsBundleService.findAllTenantWidgetsBundlesByTenantId(tenantId));
@@ -30,6 +30,7 @@ import org.thingsboard.rule.engine.api.NodeConfiguration; @@ -30,6 +30,7 @@ import org.thingsboard.rule.engine.api.NodeConfiguration;
30 import org.thingsboard.rule.engine.api.NodeDefinition; 30 import org.thingsboard.rule.engine.api.NodeDefinition;
31 import org.thingsboard.rule.engine.api.RuleNode; 31 import org.thingsboard.rule.engine.api.RuleNode;
32 import org.thingsboard.rule.engine.api.TbRelationTypes; 32 import org.thingsboard.rule.engine.api.TbRelationTypes;
  33 +import org.thingsboard.server.common.data.id.TenantId;
33 import org.thingsboard.server.common.data.plugin.ComponentDescriptor; 34 import org.thingsboard.server.common.data.plugin.ComponentDescriptor;
34 import org.thingsboard.server.common.data.plugin.ComponentType; 35 import org.thingsboard.server.common.data.plugin.ComponentType;
35 import org.thingsboard.server.dao.component.ComponentDescriptorService; 36 import org.thingsboard.server.dao.component.ComponentDescriptorService;
@@ -159,18 +160,18 @@ public class AnnotationComponentDiscoveryService implements ComponentDiscoverySe @@ -159,18 +160,18 @@ public class AnnotationComponentDiscoveryService implements ComponentDiscoverySe
159 log.error("Can't initialize component {}, due to {}", def.getBeanClassName(), e.getMessage(), e); 160 log.error("Can't initialize component {}, due to {}", def.getBeanClassName(), e.getMessage(), e);
160 throw new RuntimeException(e); 161 throw new RuntimeException(e);
161 } 162 }
162 - ComponentDescriptor persistedComponent = componentDescriptorService.findByClazz(clazzName); 163 + ComponentDescriptor persistedComponent = componentDescriptorService.findByClazz(TenantId.SYS_TENANT_ID, clazzName);
163 if (persistedComponent == null) { 164 if (persistedComponent == null) {
164 log.info("Persisting new component: {}", scannedComponent); 165 log.info("Persisting new component: {}", scannedComponent);
165 - scannedComponent = componentDescriptorService.saveComponent(scannedComponent); 166 + scannedComponent = componentDescriptorService.saveComponent(TenantId.SYS_TENANT_ID, scannedComponent);
166 } else if (scannedComponent.equals(persistedComponent)) { 167 } else if (scannedComponent.equals(persistedComponent)) {
167 log.info("Component is already persisted: {}", persistedComponent); 168 log.info("Component is already persisted: {}", persistedComponent);
168 scannedComponent = persistedComponent; 169 scannedComponent = persistedComponent;
169 } else { 170 } else {
170 log.info("Component {} will be updated to {}", persistedComponent, scannedComponent); 171 log.info("Component {} will be updated to {}", persistedComponent, scannedComponent);
171 - componentDescriptorService.deleteByClazz(persistedComponent.getClazz()); 172 + componentDescriptorService.deleteByClazz(TenantId.SYS_TENANT_ID, persistedComponent.getClazz());
172 scannedComponent.setId(persistedComponent.getId()); 173 scannedComponent.setId(persistedComponent.getId());
173 - scannedComponent = componentDescriptorService.saveComponent(scannedComponent); 174 + scannedComponent = componentDescriptorService.saveComponent(TenantId.SYS_TENANT_ID, scannedComponent);
174 } 175 }
175 return scannedComponent; 176 return scannedComponent;
176 } 177 }
@@ -25,6 +25,8 @@ import org.thingsboard.server.common.data.ShortCustomerInfo; @@ -25,6 +25,8 @@ import org.thingsboard.server.common.data.ShortCustomerInfo;
25 import org.thingsboard.server.common.data.UUIDConverter; 25 import org.thingsboard.server.common.data.UUIDConverter;
26 import org.thingsboard.server.common.data.id.CustomerId; 26 import org.thingsboard.server.common.data.id.CustomerId;
27 import org.thingsboard.server.common.data.id.DashboardId; 27 import org.thingsboard.server.common.data.id.DashboardId;
  28 +import org.thingsboard.server.common.data.id.EntityId;
  29 +import org.thingsboard.server.common.data.id.TenantId;
28 import org.thingsboard.server.dao.dashboard.DashboardService; 30 import org.thingsboard.server.dao.dashboard.DashboardService;
29 31
30 import java.io.IOException; 32 import java.io.IOException;
@@ -96,7 +98,7 @@ public class DatabaseHelper { @@ -96,7 +98,7 @@ public class DatabaseHelper {
96 } 98 }
97 } 99 }
98 for (CustomerId customerId : customerIds) { 100 for (CustomerId customerId : customerIds) {
99 - dashboardService.assignDashboardToCustomer(dashboardId, customerId); 101 + dashboardService.assignDashboardToCustomer(new TenantId(EntityId.NULL_UUID), dashboardId, customerId);
100 } 102 }
101 }); 103 });
102 } 104 }
@@ -96,7 +96,7 @@ public class DefaultSystemDataLoaderService implements SystemDataLoaderService { @@ -96,7 +96,7 @@ public class DefaultSystemDataLoaderService implements SystemDataLoaderService {
96 ObjectNode node = objectMapper.createObjectNode(); 96 ObjectNode node = objectMapper.createObjectNode();
97 node.put("baseUrl", "http://localhost:8080"); 97 node.put("baseUrl", "http://localhost:8080");
98 generalSettings.setJsonValue(node); 98 generalSettings.setJsonValue(node);
99 - adminSettingsService.saveAdminSettings(generalSettings); 99 + adminSettingsService.saveAdminSettings(TenantId.SYS_TENANT_ID, generalSettings);
100 100
101 AdminSettings mailSettings = new AdminSettings(); 101 AdminSettings mailSettings = new AdminSettings();
102 mailSettings.setKey("mail"); 102 mailSettings.setKey("mail");
@@ -110,7 +110,7 @@ public class DefaultSystemDataLoaderService implements SystemDataLoaderService { @@ -110,7 +110,7 @@ public class DefaultSystemDataLoaderService implements SystemDataLoaderService {
110 node.put("username", ""); 110 node.put("username", "");
111 node.put("password", ""); //NOSONAR, key used to identify password field (not password value itself) 111 node.put("password", ""); //NOSONAR, key used to identify password field (not password value itself)
112 mailSettings.setJsonValue(node); 112 mailSettings.setJsonValue(node);
113 - adminSettingsService.saveAdminSettings(mailSettings); 113 + adminSettingsService.saveAdminSettings(TenantId.SYS_TENANT_ID, mailSettings);
114 } 114 }
115 115
116 @Override 116 @Override
@@ -158,7 +158,7 @@ public class DefaultSystemDataLoaderService implements SystemDataLoaderService { @@ -158,7 +158,7 @@ public class DefaultSystemDataLoaderService implements SystemDataLoaderService {
158 public void deleteSystemWidgetBundle(String bundleAlias) throws Exception { 158 public void deleteSystemWidgetBundle(String bundleAlias) throws Exception {
159 WidgetsBundle widgetsBundle = widgetsBundleService.findWidgetsBundleByTenantIdAndAlias(new TenantId(ModelConstants.NULL_UUID), bundleAlias); 159 WidgetsBundle widgetsBundle = widgetsBundleService.findWidgetsBundleByTenantIdAndAlias(new TenantId(ModelConstants.NULL_UUID), bundleAlias);
160 if (widgetsBundle != null) { 160 if (widgetsBundle != null) {
161 - widgetsBundleService.deleteWidgetsBundle(widgetsBundle.getId()); 161 + widgetsBundleService.deleteWidgetsBundle(TenantId.SYS_TENANT_ID, widgetsBundle.getId());
162 } 162 }
163 } 163 }
164 164
@@ -178,11 +178,11 @@ public class DefaultSystemDataLoaderService implements SystemDataLoaderService { @@ -178,11 +178,11 @@ public class DefaultSystemDataLoaderService implements SystemDataLoaderService {
178 user.setTenantId(tenantId); 178 user.setTenantId(tenantId);
179 user.setCustomerId(customerId); 179 user.setCustomerId(customerId);
180 user = userService.saveUser(user); 180 user = userService.saveUser(user);
181 - UserCredentials userCredentials = userService.findUserCredentialsByUserId(user.getId()); 181 + UserCredentials userCredentials = userService.findUserCredentialsByUserId(TenantId.SYS_TENANT_ID, user.getId());
182 userCredentials.setPassword(passwordEncoder.encode(password)); 182 userCredentials.setPassword(passwordEncoder.encode(password));
183 userCredentials.setEnabled(true); 183 userCredentials.setEnabled(true);
184 userCredentials.setActivateToken(null); 184 userCredentials.setActivateToken(null);
185 - userService.saveUserCredentials(userCredentials); 185 + userService.saveUserCredentials(TenantId.SYS_TENANT_ID, userCredentials);
186 return user; 186 return user;
187 } 187 }
188 188
@@ -203,9 +203,9 @@ public class DefaultSystemDataLoaderService implements SystemDataLoaderService { @@ -203,9 +203,9 @@ public class DefaultSystemDataLoaderService implements SystemDataLoaderService {
203 device.setAdditionalInfo(additionalInfo); 203 device.setAdditionalInfo(additionalInfo);
204 } 204 }
205 device = deviceService.saveDevice(device); 205 device = deviceService.saveDevice(device);
206 - DeviceCredentials deviceCredentials = deviceCredentialsService.findDeviceCredentialsByDeviceId(device.getId()); 206 + DeviceCredentials deviceCredentials = deviceCredentialsService.findDeviceCredentialsByDeviceId(TenantId.SYS_TENANT_ID, device.getId());
207 deviceCredentials.setCredentialsId(accessToken); 207 deviceCredentials.setCredentialsId(accessToken);
208 - deviceCredentialsService.updateDeviceCredentials(deviceCredentials); 208 + deviceCredentialsService.updateDeviceCredentials(TenantId.SYS_TENANT_ID, deviceCredentials);
209 return device; 209 return device;
210 } 210 }
211 211
@@ -23,6 +23,7 @@ import org.springframework.stereotype.Component; @@ -23,6 +23,7 @@ import org.springframework.stereotype.Component;
23 import org.springframework.util.StringUtils; 23 import org.springframework.util.StringUtils;
24 import org.thingsboard.server.common.data.Dashboard; 24 import org.thingsboard.server.common.data.Dashboard;
25 import org.thingsboard.server.common.data.id.CustomerId; 25 import org.thingsboard.server.common.data.id.CustomerId;
  26 +import org.thingsboard.server.common.data.id.EntityId;
26 import org.thingsboard.server.common.data.id.TenantId; 27 import org.thingsboard.server.common.data.id.TenantId;
27 import org.thingsboard.server.common.data.rule.RuleChain; 28 import org.thingsboard.server.common.data.rule.RuleChain;
28 import org.thingsboard.server.common.data.rule.RuleChainMetaData; 29 import org.thingsboard.server.common.data.rule.RuleChainMetaData;
@@ -116,7 +117,7 @@ public class InstallScripts { @@ -116,7 +117,7 @@ public class InstallScripts {
116 ruleChain = ruleChainService.saveRuleChain(ruleChain); 117 ruleChain = ruleChainService.saveRuleChain(ruleChain);
117 118
118 ruleChainMetaData.setRuleChainId(ruleChain.getId()); 119 ruleChainMetaData.setRuleChainId(ruleChain.getId());
119 - ruleChainService.saveRuleChainMetaData(ruleChainMetaData); 120 + ruleChainService.saveRuleChainMetaData(new TenantId(EntityId.NULL_UUID), ruleChainMetaData);
120 } catch (Exception e) { 121 } catch (Exception e) {
121 log.error("Unable to load rule chain from json: [{}]", path.toString()); 122 log.error("Unable to load rule chain from json: [{}]", path.toString());
122 throw new RuntimeException("Unable to load rule chain from json", e); 123 throw new RuntimeException("Unable to load rule chain from json", e);
@@ -169,7 +170,7 @@ public class InstallScripts { @@ -169,7 +170,7 @@ public class InstallScripts {
169 dashboard.setTenantId(tenantId); 170 dashboard.setTenantId(tenantId);
170 Dashboard savedDashboard = dashboardService.saveDashboard(dashboard); 171 Dashboard savedDashboard = dashboardService.saveDashboard(dashboard);
171 if (customerId != null && !customerId.isNullUid()) { 172 if (customerId != null && !customerId.isNullUid()) {
172 - dashboardService.assignDashboardToCustomer(savedDashboard.getId(), customerId); 173 + dashboardService.assignDashboardToCustomer(new TenantId(EntityId.NULL_UUID), savedDashboard.getId(), customerId);
173 } 174 }
174 } catch (Exception e) { 175 } catch (Exception e) {
175 log.error("Unable to load dashboard from json: [{}]", path.toString()); 176 log.error("Unable to load dashboard from json: [{}]", path.toString());
@@ -31,6 +31,8 @@ import org.thingsboard.rule.engine.api.MailService; @@ -31,6 +31,8 @@ import org.thingsboard.rule.engine.api.MailService;
31 import org.thingsboard.server.common.data.AdminSettings; 31 import org.thingsboard.server.common.data.AdminSettings;
32 import org.thingsboard.server.common.data.exception.ThingsboardErrorCode; 32 import org.thingsboard.server.common.data.exception.ThingsboardErrorCode;
33 import org.thingsboard.server.common.data.exception.ThingsboardException; 33 import org.thingsboard.server.common.data.exception.ThingsboardException;
  34 +import org.thingsboard.server.common.data.id.EntityId;
  35 +import org.thingsboard.server.common.data.id.TenantId;
34 import org.thingsboard.server.dao.exception.IncorrectParameterException; 36 import org.thingsboard.server.dao.exception.IncorrectParameterException;
35 import org.thingsboard.server.dao.settings.AdminSettingsService; 37 import org.thingsboard.server.dao.settings.AdminSettingsService;
36 38
@@ -70,7 +72,7 @@ public class DefaultMailService implements MailService { @@ -70,7 +72,7 @@ public class DefaultMailService implements MailService {
70 72
71 @Override 73 @Override
72 public void updateMailConfiguration() { 74 public void updateMailConfiguration() {
73 - AdminSettings settings = adminSettingsService.findAdminSettingsByKey("mail"); 75 + AdminSettings settings = adminSettingsService.findAdminSettingsByKey(new TenantId(EntityId.NULL_UUID), "mail");
74 if (settings != null) { 76 if (settings != null) {
75 JsonNode jsonConfig = settings.getJsonValue(); 77 JsonNode jsonConfig = settings.getJsonValue();
76 mailSender = createMailSender(jsonConfig); 78 mailSender = createMailSender(jsonConfig);
@@ -110,24 +110,24 @@ public class AccessValidator { @@ -110,24 +110,24 @@ public class AccessValidator {
110 } 110 }
111 111
112 public DeferredResult<ResponseEntity> validateEntityAndCallback(SecurityUser currentUser, String entityType, String entityIdStr, 112 public DeferredResult<ResponseEntity> validateEntityAndCallback(SecurityUser currentUser, String entityType, String entityIdStr,
113 - BiConsumer<DeferredResult<ResponseEntity>, EntityId> onSuccess) throws ThingsboardException { 113 + ThreeConsumer<DeferredResult<ResponseEntity>, TenantId, EntityId> onSuccess) throws ThingsboardException {
114 return validateEntityAndCallback(currentUser, entityType, entityIdStr, onSuccess, (result, t) -> handleError(t, result, HttpStatus.INTERNAL_SERVER_ERROR)); 114 return validateEntityAndCallback(currentUser, entityType, entityIdStr, onSuccess, (result, t) -> handleError(t, result, HttpStatus.INTERNAL_SERVER_ERROR));
115 } 115 }
116 116
117 public DeferredResult<ResponseEntity> validateEntityAndCallback(SecurityUser currentUser, String entityType, String entityIdStr, 117 public DeferredResult<ResponseEntity> validateEntityAndCallback(SecurityUser currentUser, String entityType, String entityIdStr,
118 - BiConsumer<DeferredResult<ResponseEntity>, EntityId> onSuccess, 118 + ThreeConsumer<DeferredResult<ResponseEntity>, TenantId, EntityId> onSuccess,
119 BiConsumer<DeferredResult<ResponseEntity>, Throwable> onFailure) throws ThingsboardException { 119 BiConsumer<DeferredResult<ResponseEntity>, Throwable> onFailure) throws ThingsboardException {
120 return validateEntityAndCallback(currentUser, EntityIdFactory.getByTypeAndId(entityType, entityIdStr), 120 return validateEntityAndCallback(currentUser, EntityIdFactory.getByTypeAndId(entityType, entityIdStr),
121 onSuccess, onFailure); 121 onSuccess, onFailure);
122 } 122 }
123 123
124 public DeferredResult<ResponseEntity> validateEntityAndCallback(SecurityUser currentUser, EntityId entityId, 124 public DeferredResult<ResponseEntity> validateEntityAndCallback(SecurityUser currentUser, EntityId entityId,
125 - BiConsumer<DeferredResult<ResponseEntity>, EntityId> onSuccess) throws ThingsboardException { 125 + ThreeConsumer<DeferredResult<ResponseEntity>, TenantId, EntityId> onSuccess) throws ThingsboardException {
126 return validateEntityAndCallback(currentUser, entityId, onSuccess, (result, t) -> handleError(t, result, HttpStatus.INTERNAL_SERVER_ERROR)); 126 return validateEntityAndCallback(currentUser, entityId, onSuccess, (result, t) -> handleError(t, result, HttpStatus.INTERNAL_SERVER_ERROR));
127 } 127 }
128 128
129 public DeferredResult<ResponseEntity> validateEntityAndCallback(SecurityUser currentUser, EntityId entityId, 129 public DeferredResult<ResponseEntity> validateEntityAndCallback(SecurityUser currentUser, EntityId entityId,
130 - BiConsumer<DeferredResult<ResponseEntity>, EntityId> onSuccess, 130 + ThreeConsumer<DeferredResult<ResponseEntity>, TenantId, EntityId> onSuccess,
131 BiConsumer<DeferredResult<ResponseEntity>, Throwable> onFailure) throws ThingsboardException { 131 BiConsumer<DeferredResult<ResponseEntity>, Throwable> onFailure) throws ThingsboardException {
132 132
133 final DeferredResult<ResponseEntity> response = new DeferredResult<>(); 133 final DeferredResult<ResponseEntity> response = new DeferredResult<>();
@@ -136,7 +136,7 @@ public class AccessValidator { @@ -136,7 +136,7 @@ public class AccessValidator {
136 new FutureCallback<DeferredResult<ResponseEntity>>() { 136 new FutureCallback<DeferredResult<ResponseEntity>>() {
137 @Override 137 @Override
138 public void onSuccess(@Nullable DeferredResult<ResponseEntity> result) { 138 public void onSuccess(@Nullable DeferredResult<ResponseEntity> result) {
139 - onSuccess.accept(response, entityId); 139 + onSuccess.accept(response, currentUser.getTenantId(), entityId);
140 } 140 }
141 141
142 @Override 142 @Override
@@ -178,7 +178,7 @@ public class AccessValidator { @@ -178,7 +178,7 @@ public class AccessValidator {
178 if (currentUser.isSystemAdmin()) { 178 if (currentUser.isSystemAdmin()) {
179 callback.onSuccess(ValidationResult.accessDenied(SYSTEM_ADMINISTRATOR_IS_NOT_ALLOWED_TO_PERFORM_THIS_OPERATION)); 179 callback.onSuccess(ValidationResult.accessDenied(SYSTEM_ADMINISTRATOR_IS_NOT_ALLOWED_TO_PERFORM_THIS_OPERATION));
180 } else { 180 } else {
181 - ListenableFuture<Device> deviceFuture = deviceService.findDeviceByIdAsync(new DeviceId(entityId.getId())); 181 + ListenableFuture<Device> deviceFuture = deviceService.findDeviceByIdAsync(currentUser.getTenantId(), new DeviceId(entityId.getId()));
182 Futures.addCallback(deviceFuture, getCallback(callback, device -> { 182 Futures.addCallback(deviceFuture, getCallback(callback, device -> {
183 if (device == null) { 183 if (device == null) {
184 return ValidationResult.entityNotFound(DEVICE_WITH_REQUESTED_ID_NOT_FOUND); 184 return ValidationResult.entityNotFound(DEVICE_WITH_REQUESTED_ID_NOT_FOUND);
@@ -199,7 +199,7 @@ public class AccessValidator { @@ -199,7 +199,7 @@ public class AccessValidator {
199 if (currentUser.isSystemAdmin()) { 199 if (currentUser.isSystemAdmin()) {
200 callback.onSuccess(ValidationResult.accessDenied(SYSTEM_ADMINISTRATOR_IS_NOT_ALLOWED_TO_PERFORM_THIS_OPERATION)); 200 callback.onSuccess(ValidationResult.accessDenied(SYSTEM_ADMINISTRATOR_IS_NOT_ALLOWED_TO_PERFORM_THIS_OPERATION));
201 } else { 201 } else {
202 - ListenableFuture<Asset> assetFuture = assetService.findAssetByIdAsync(new AssetId(entityId.getId())); 202 + ListenableFuture<Asset> assetFuture = assetService.findAssetByIdAsync(currentUser.getTenantId(), new AssetId(entityId.getId()));
203 Futures.addCallback(assetFuture, getCallback(callback, asset -> { 203 Futures.addCallback(assetFuture, getCallback(callback, asset -> {
204 if (asset == null) { 204 if (asset == null) {
205 return ValidationResult.entityNotFound("Asset with requested id wasn't found!"); 205 return ValidationResult.entityNotFound("Asset with requested id wasn't found!");
@@ -220,7 +220,7 @@ public class AccessValidator { @@ -220,7 +220,7 @@ public class AccessValidator {
220 if (currentUser.isCustomerUser()) { 220 if (currentUser.isCustomerUser()) {
221 callback.onSuccess(ValidationResult.accessDenied(CUSTOMER_USER_IS_NOT_ALLOWED_TO_PERFORM_THIS_OPERATION)); 221 callback.onSuccess(ValidationResult.accessDenied(CUSTOMER_USER_IS_NOT_ALLOWED_TO_PERFORM_THIS_OPERATION));
222 } else { 222 } else {
223 - ListenableFuture<RuleChain> ruleChainFuture = ruleChainService.findRuleChainByIdAsync(new RuleChainId(entityId.getId())); 223 + ListenableFuture<RuleChain> ruleChainFuture = ruleChainService.findRuleChainByIdAsync(currentUser.getTenantId(), new RuleChainId(entityId.getId()));
224 Futures.addCallback(ruleChainFuture, getCallback(callback, ruleChain -> { 224 Futures.addCallback(ruleChainFuture, getCallback(callback, ruleChain -> {
225 if (ruleChain == null) { 225 if (ruleChain == null) {
226 return ValidationResult.entityNotFound("Rule chain with requested id wasn't found!"); 226 return ValidationResult.entityNotFound("Rule chain with requested id wasn't found!");
@@ -241,7 +241,7 @@ public class AccessValidator { @@ -241,7 +241,7 @@ public class AccessValidator {
241 if (currentUser.isCustomerUser()) { 241 if (currentUser.isCustomerUser()) {
242 callback.onSuccess(ValidationResult.accessDenied(CUSTOMER_USER_IS_NOT_ALLOWED_TO_PERFORM_THIS_OPERATION)); 242 callback.onSuccess(ValidationResult.accessDenied(CUSTOMER_USER_IS_NOT_ALLOWED_TO_PERFORM_THIS_OPERATION));
243 } else { 243 } else {
244 - ListenableFuture<RuleNode> ruleNodeFuture = ruleChainService.findRuleNodeByIdAsync(new RuleNodeId(entityId.getId())); 244 + ListenableFuture<RuleNode> ruleNodeFuture = ruleChainService.findRuleNodeByIdAsync(currentUser.getTenantId(), new RuleNodeId(entityId.getId()));
245 Futures.addCallback(ruleNodeFuture, getCallback(callback, ruleNodeTmp -> { 245 Futures.addCallback(ruleNodeFuture, getCallback(callback, ruleNodeTmp -> {
246 RuleNode ruleNode = ruleNodeTmp; 246 RuleNode ruleNode = ruleNodeTmp;
247 if (ruleNode == null) { 247 if (ruleNode == null) {
@@ -250,7 +250,7 @@ public class AccessValidator { @@ -250,7 +250,7 @@ public class AccessValidator {
250 return ValidationResult.entityNotFound("Rule chain with requested node id wasn't found!"); 250 return ValidationResult.entityNotFound("Rule chain with requested node id wasn't found!");
251 } else { 251 } else {
252 //TODO: make async 252 //TODO: make async
253 - RuleChain ruleChain = ruleChainService.findRuleChainById(ruleNode.getRuleChainId()); 253 + RuleChain ruleChain = ruleChainService.findRuleChainById(currentUser.getTenantId(), ruleNode.getRuleChainId());
254 if (currentUser.isTenantAdmin() && !ruleChain.getTenantId().equals(currentUser.getTenantId())) { 254 if (currentUser.isTenantAdmin() && !ruleChain.getTenantId().equals(currentUser.getTenantId())) {
255 return ValidationResult.accessDenied("Rule chain doesn't belong to the current Tenant!"); 255 return ValidationResult.accessDenied("Rule chain doesn't belong to the current Tenant!");
256 } else if (currentUser.isSystemAdmin() && !ruleChain.getTenantId().isNullUid()) { 256 } else if (currentUser.isSystemAdmin() && !ruleChain.getTenantId().isNullUid()) {
@@ -267,7 +267,7 @@ public class AccessValidator { @@ -267,7 +267,7 @@ public class AccessValidator {
267 if (currentUser.isSystemAdmin()) { 267 if (currentUser.isSystemAdmin()) {
268 callback.onSuccess(ValidationResult.accessDenied(SYSTEM_ADMINISTRATOR_IS_NOT_ALLOWED_TO_PERFORM_THIS_OPERATION)); 268 callback.onSuccess(ValidationResult.accessDenied(SYSTEM_ADMINISTRATOR_IS_NOT_ALLOWED_TO_PERFORM_THIS_OPERATION));
269 } else { 269 } else {
270 - ListenableFuture<Customer> customerFuture = customerService.findCustomerByIdAsync(new CustomerId(entityId.getId())); 270 + ListenableFuture<Customer> customerFuture = customerService.findCustomerByIdAsync(currentUser.getTenantId(), new CustomerId(entityId.getId()));
271 Futures.addCallback(customerFuture, getCallback(callback, customer -> { 271 Futures.addCallback(customerFuture, getCallback(callback, customer -> {
272 if (customer == null) { 272 if (customer == null) {
273 return ValidationResult.entityNotFound("Customer with requested id wasn't found!"); 273 return ValidationResult.entityNotFound("Customer with requested id wasn't found!");
@@ -290,7 +290,7 @@ public class AccessValidator { @@ -290,7 +290,7 @@ public class AccessValidator {
290 } else if (currentUser.isSystemAdmin()) { 290 } else if (currentUser.isSystemAdmin()) {
291 callback.onSuccess(ValidationResult.ok(null)); 291 callback.onSuccess(ValidationResult.ok(null));
292 } else { 292 } else {
293 - ListenableFuture<Tenant> tenantFuture = tenantService.findTenantByIdAsync(new TenantId(entityId.getId())); 293 + ListenableFuture<Tenant> tenantFuture = tenantService.findTenantByIdAsync(currentUser.getTenantId(), new TenantId(entityId.getId()));
294 Futures.addCallback(tenantFuture, getCallback(callback, tenant -> { 294 Futures.addCallback(tenantFuture, getCallback(callback, tenant -> {
295 if (tenant == null) { 295 if (tenant == null) {
296 return ValidationResult.entityNotFound("Tenant with requested id wasn't found!"); 296 return ValidationResult.entityNotFound("Tenant with requested id wasn't found!");
@@ -307,7 +307,7 @@ public class AccessValidator { @@ -307,7 +307,7 @@ public class AccessValidator {
307 if (currentUser.isSystemAdmin()) { 307 if (currentUser.isSystemAdmin()) {
308 callback.onSuccess(ValidationResult.accessDenied(SYSTEM_ADMINISTRATOR_IS_NOT_ALLOWED_TO_PERFORM_THIS_OPERATION)); 308 callback.onSuccess(ValidationResult.accessDenied(SYSTEM_ADMINISTRATOR_IS_NOT_ALLOWED_TO_PERFORM_THIS_OPERATION));
309 } else { 309 } else {
310 - ListenableFuture<EntityView> entityViewFuture = entityViewService.findEntityViewByIdAsync(new EntityViewId(entityId.getId())); 310 + ListenableFuture<EntityView> entityViewFuture = entityViewService.findEntityViewByIdAsync(currentUser.getTenantId(), new EntityViewId(entityId.getId()));
311 Futures.addCallback(entityViewFuture, getCallback(callback, entityView -> { 311 Futures.addCallback(entityViewFuture, getCallback(callback, entityView -> {
312 if (entityView == null) { 312 if (entityView == null) {
313 return ValidationResult.entityNotFound(ENTITY_VIEW_WITH_REQUESTED_ID_NOT_FOUND); 313 return ValidationResult.entityNotFound(ENTITY_VIEW_WITH_REQUESTED_ID_NOT_FOUND);
@@ -349,4 +349,8 @@ public class AccessValidator { @@ -349,4 +349,8 @@ public class AccessValidator {
349 } 349 }
350 response.setResult(responseEntity); 350 response.setResult(responseEntity);
351 } 351 }
  352 +
  353 + public interface ThreeConsumer<A, B, C> {
  354 + void accept(A a, B b, C c);
  355 + }
352 } 356 }
@@ -29,6 +29,7 @@ import org.thingsboard.server.common.data.Customer; @@ -29,6 +29,7 @@ import org.thingsboard.server.common.data.Customer;
29 import org.thingsboard.server.common.data.User; 29 import org.thingsboard.server.common.data.User;
30 import org.thingsboard.server.common.data.id.CustomerId; 30 import org.thingsboard.server.common.data.id.CustomerId;
31 import org.thingsboard.server.common.data.id.EntityId; 31 import org.thingsboard.server.common.data.id.EntityId;
  32 +import org.thingsboard.server.common.data.id.TenantId;
32 import org.thingsboard.server.common.data.id.UserId; 33 import org.thingsboard.server.common.data.id.UserId;
33 import org.thingsboard.server.common.data.security.Authority; 34 import org.thingsboard.server.common.data.security.Authority;
34 import org.thingsboard.server.common.data.security.UserCredentials; 35 import org.thingsboard.server.common.data.security.UserCredentials;
@@ -72,12 +73,13 @@ public class RefreshTokenAuthenticationProvider implements AuthenticationProvide @@ -72,12 +73,13 @@ public class RefreshTokenAuthenticationProvider implements AuthenticationProvide
72 } 73 }
73 74
74 private SecurityUser authenticateByUserId(UserId userId) { 75 private SecurityUser authenticateByUserId(UserId userId) {
75 - User user = userService.findUserById(userId); 76 + TenantId systemId = new TenantId(EntityId.NULL_UUID);
  77 + User user = userService.findUserById(systemId, userId);
76 if (user == null) { 78 if (user == null) {
77 throw new UsernameNotFoundException("User not found by refresh token"); 79 throw new UsernameNotFoundException("User not found by refresh token");
78 } 80 }
79 81
80 - UserCredentials userCredentials = userService.findUserCredentialsByUserId(user.getId()); 82 + UserCredentials userCredentials = userService.findUserCredentialsByUserId(systemId, user.getId());
81 if (userCredentials == null) { 83 if (userCredentials == null) {
82 throw new UsernameNotFoundException("User credentials not found"); 84 throw new UsernameNotFoundException("User credentials not found");
83 } 85 }
@@ -96,13 +98,14 @@ public class RefreshTokenAuthenticationProvider implements AuthenticationProvide @@ -96,13 +98,14 @@ public class RefreshTokenAuthenticationProvider implements AuthenticationProvide
96 } 98 }
97 99
98 private SecurityUser authenticateByPublicId(String publicId) { 100 private SecurityUser authenticateByPublicId(String publicId) {
  101 + TenantId systemId = new TenantId(EntityId.NULL_UUID);
99 CustomerId customerId; 102 CustomerId customerId;
100 try { 103 try {
101 customerId = new CustomerId(UUID.fromString(publicId)); 104 customerId = new CustomerId(UUID.fromString(publicId));
102 } catch (Exception e) { 105 } catch (Exception e) {
103 throw new BadCredentialsException("Refresh token is not valid"); 106 throw new BadCredentialsException("Refresh token is not valid");
104 } 107 }
105 - Customer publicCustomer = customerService.findCustomerById(customerId); 108 + Customer publicCustomer = customerService.findCustomerById(systemId, customerId);
106 if (publicCustomer == null) { 109 if (publicCustomer == null) {
107 throw new UsernameNotFoundException("Public entity not found by refresh token"); 110 throw new UsernameNotFoundException("Public entity not found by refresh token");
108 } 111 }
@@ -31,6 +31,7 @@ import org.thingsboard.server.common.data.Customer; @@ -31,6 +31,7 @@ import org.thingsboard.server.common.data.Customer;
31 import org.thingsboard.server.common.data.User; 31 import org.thingsboard.server.common.data.User;
32 import org.thingsboard.server.common.data.id.CustomerId; 32 import org.thingsboard.server.common.data.id.CustomerId;
33 import org.thingsboard.server.common.data.id.EntityId; 33 import org.thingsboard.server.common.data.id.EntityId;
  34 +import org.thingsboard.server.common.data.id.TenantId;
34 import org.thingsboard.server.common.data.id.UserId; 35 import org.thingsboard.server.common.data.id.UserId;
35 import org.thingsboard.server.common.data.security.Authority; 36 import org.thingsboard.server.common.data.security.Authority;
36 import org.thingsboard.server.common.data.security.UserCredentials; 37 import org.thingsboard.server.common.data.security.UserCredentials;
@@ -76,12 +77,12 @@ public class RestAuthenticationProvider implements AuthenticationProvider { @@ -76,12 +77,12 @@ public class RestAuthenticationProvider implements AuthenticationProvider {
76 } 77 }
77 78
78 private Authentication authenticateByUsernameAndPassword(UserPrincipal userPrincipal, String username, String password) { 79 private Authentication authenticateByUsernameAndPassword(UserPrincipal userPrincipal, String username, String password) {
79 - User user = userService.findUserByEmail(username); 80 + User user = userService.findUserByEmail(TenantId.SYS_TENANT_ID, username);
80 if (user == null) { 81 if (user == null) {
81 throw new UsernameNotFoundException("User not found: " + username); 82 throw new UsernameNotFoundException("User not found: " + username);
82 } 83 }
83 84
84 - UserCredentials userCredentials = userService.findUserCredentialsByUserId(user.getId()); 85 + UserCredentials userCredentials = userService.findUserCredentialsByUserId(TenantId.SYS_TENANT_ID, user.getId());
85 if (userCredentials == null) { 86 if (userCredentials == null) {
86 throw new UsernameNotFoundException("User credentials not found"); 87 throw new UsernameNotFoundException("User credentials not found");
87 } 88 }
@@ -108,7 +109,7 @@ public class RestAuthenticationProvider implements AuthenticationProvider { @@ -108,7 +109,7 @@ public class RestAuthenticationProvider implements AuthenticationProvider {
108 } catch (Exception e) { 109 } catch (Exception e) {
109 throw new BadCredentialsException("Authentication Failed. Public Id is not valid."); 110 throw new BadCredentialsException("Authentication Failed. Public Id is not valid.");
110 } 111 }
111 - Customer publicCustomer = customerService.findCustomerById(customerId); 112 + Customer publicCustomer = customerService.findCustomerById(TenantId.SYS_TENANT_ID, customerId);
112 if (publicCustomer == null) { 113 if (publicCustomer == null) {
113 throw new UsernameNotFoundException("Public entity not found: " + publicId); 114 throw new UsernameNotFoundException("Public entity not found: " + publicId);
114 } 115 }
@@ -18,8 +18,6 @@ package org.thingsboard.server.service.security.device; @@ -18,8 +18,6 @@ package org.thingsboard.server.service.security.device;
18 import lombok.extern.slf4j.Slf4j; 18 import lombok.extern.slf4j.Slf4j;
19 import org.springframework.beans.factory.annotation.Autowired; 19 import org.springframework.beans.factory.annotation.Autowired;
20 import org.springframework.stereotype.Service; 20 import org.springframework.stereotype.Service;
21 -import org.thingsboard.server.common.data.Device;  
22 -import org.thingsboard.server.common.data.id.DeviceId;  
23 import org.thingsboard.server.common.data.security.DeviceCredentials; 21 import org.thingsboard.server.common.data.security.DeviceCredentials;
24 import org.thingsboard.server.common.data.security.DeviceCredentialsFilter; 22 import org.thingsboard.server.common.data.security.DeviceCredentialsFilter;
25 import org.thingsboard.server.common.transport.auth.DeviceAuthResult; 23 import org.thingsboard.server.common.transport.auth.DeviceAuthResult;
@@ -27,8 +25,6 @@ import org.thingsboard.server.common.transport.auth.DeviceAuthService; @@ -27,8 +25,6 @@ import org.thingsboard.server.common.transport.auth.DeviceAuthService;
27 import org.thingsboard.server.dao.device.DeviceCredentialsService; 25 import org.thingsboard.server.dao.device.DeviceCredentialsService;
28 import org.thingsboard.server.dao.device.DeviceService; 26 import org.thingsboard.server.dao.device.DeviceService;
29 27
30 -import java.util.Optional;  
31 -  
32 @Service 28 @Service
33 @Slf4j 29 @Slf4j
34 public class DefaultDeviceAuthService implements DeviceAuthService { 30 public class DefaultDeviceAuthService implements DeviceAuthService {
@@ -65,8 +61,4 @@ public class DefaultDeviceAuthService implements DeviceAuthService { @@ -65,8 +61,4 @@ public class DefaultDeviceAuthService implements DeviceAuthService {
65 } 61 }
66 } 62 }
67 63
68 - @Override  
69 - public Optional<Device> findDeviceById(DeviceId deviceId) {  
70 - return Optional.ofNullable(deviceService.findDeviceById(deviceId));  
71 - }  
72 -} 64 +}
@@ -21,6 +21,7 @@ import io.jsonwebtoken.Jwts; @@ -21,6 +21,7 @@ import io.jsonwebtoken.Jwts;
21 import io.jsonwebtoken.SignatureAlgorithm; 21 import io.jsonwebtoken.SignatureAlgorithm;
22 import org.apache.commons.lang3.StringUtils; 22 import org.apache.commons.lang3.StringUtils;
23 import org.springframework.beans.factory.annotation.Autowired; 23 import org.springframework.beans.factory.annotation.Autowired;
  24 +import org.springframework.security.core.GrantedAuthority;
24 import org.springframework.stereotype.Component; 25 import org.springframework.stereotype.Component;
25 import org.thingsboard.server.common.data.id.CustomerId; 26 import org.thingsboard.server.common.data.id.CustomerId;
26 import org.thingsboard.server.common.data.id.TenantId; 27 import org.thingsboard.server.common.data.id.TenantId;
@@ -69,7 +70,7 @@ public class JwtTokenFactory { @@ -69,7 +70,7 @@ public class JwtTokenFactory {
69 UserPrincipal principal = securityUser.getUserPrincipal(); 70 UserPrincipal principal = securityUser.getUserPrincipal();
70 String subject = principal.getValue(); 71 String subject = principal.getValue();
71 Claims claims = Jwts.claims().setSubject(subject); 72 Claims claims = Jwts.claims().setSubject(subject);
72 - claims.put(SCOPES, securityUser.getAuthorities().stream().map(s -> s.getAuthority()).collect(Collectors.toList())); 73 + claims.put(SCOPES, securityUser.getAuthorities().stream().map(GrantedAuthority::getAuthority).collect(Collectors.toList()));
73 claims.put(USER_ID, securityUser.getId().getId().toString()); 74 claims.put(USER_ID, securityUser.getId().getId().toString());
74 claims.put(FIRST_NAME, securityUser.getFirstName()); 75 claims.put(FIRST_NAME, securityUser.getFirstName());
75 claims.put(LAST_NAME, securityUser.getLastName()); 76 claims.put(LAST_NAME, securityUser.getLastName());
@@ -207,7 +207,7 @@ public class DefaultDeviceStateService implements DeviceStateService { @@ -207,7 +207,7 @@ public class DefaultDeviceStateService implements DeviceStateService {
207 if (proto.getDeleted()) { 207 if (proto.getDeleted()) {
208 queueExecutor.submit(() -> onDeviceDeleted(tenantId, deviceId)); 208 queueExecutor.submit(() -> onDeviceDeleted(tenantId, deviceId));
209 } else { 209 } else {
210 - Device device = deviceService.findDeviceById(deviceId); 210 + Device device = deviceService.findDeviceById(TenantId.SYS_TENANT_ID, deviceId);
211 if (device != null) { 211 if (device != null) {
212 if (proto.getAdded()) { 212 if (proto.getAdded()) {
213 onDeviceAdded(device); 213 onDeviceAdded(device);
@@ -320,7 +320,7 @@ public class DefaultDeviceStateService implements DeviceStateService { @@ -320,7 +320,7 @@ public class DefaultDeviceStateService implements DeviceStateService {
320 DeviceStateData deviceStateData = deviceStates.get(deviceId); 320 DeviceStateData deviceStateData = deviceStates.get(deviceId);
321 if (deviceStateData == null) { 321 if (deviceStateData == null) {
322 if (!routingService.resolveById(deviceId).isPresent()) { 322 if (!routingService.resolveById(deviceId).isPresent()) {
323 - Device device = deviceService.findDeviceById(deviceId); 323 + Device device = deviceService.findDeviceById(TenantId.SYS_TENANT_ID, deviceId);
324 if (device != null) { 324 if (device != null) {
325 try { 325 try {
326 deviceStateData = fetchDeviceState(device).get(); 326 deviceStateData = fetchDeviceState(device).get();
@@ -414,7 +414,7 @@ public class DefaultDeviceStateService implements DeviceStateService { @@ -414,7 +414,7 @@ public class DefaultDeviceStateService implements DeviceStateService {
414 } 414 }
415 415
416 private ListenableFuture<DeviceStateData> fetchDeviceState(Device device) { 416 private ListenableFuture<DeviceStateData> fetchDeviceState(Device device) {
417 - ListenableFuture<List<AttributeKvEntry>> attributes = attributesService.find(device.getId(), DataConstants.SERVER_SCOPE, PERSISTENT_ATTRIBUTES); 417 + ListenableFuture<List<AttributeKvEntry>> attributes = attributesService.find(TenantId.SYS_TENANT_ID, device.getId(), DataConstants.SERVER_SCOPE, PERSISTENT_ATTRIBUTES);
418 return Futures.transform(attributes, new Function<List<AttributeKvEntry>, DeviceStateData>() { 418 return Futures.transform(attributes, new Function<List<AttributeKvEntry>, DeviceStateData>() {
419 @Nullable 419 @Nullable
420 @Override 420 @Override
@@ -465,11 +465,11 @@ public class DefaultDeviceStateService implements DeviceStateService { @@ -465,11 +465,11 @@ public class DefaultDeviceStateService implements DeviceStateService {
465 } 465 }
466 466
467 private void saveAttribute(DeviceId deviceId, String key, long value) { 467 private void saveAttribute(DeviceId deviceId, String key, long value) {
468 - tsSubService.saveAttrAndNotify(deviceId, DataConstants.SERVER_SCOPE, key, value, new AttributeSaveCallback(deviceId, key, value)); 468 + tsSubService.saveAttrAndNotify(TenantId.SYS_TENANT_ID, deviceId, DataConstants.SERVER_SCOPE, key, value, new AttributeSaveCallback(deviceId, key, value));
469 } 469 }
470 470
471 private void saveAttribute(DeviceId deviceId, String key, boolean value) { 471 private void saveAttribute(DeviceId deviceId, String key, boolean value) {
472 - tsSubService.saveAttrAndNotify(deviceId, DataConstants.SERVER_SCOPE, key, value, new AttributeSaveCallback(deviceId, key, value)); 472 + tsSubService.saveAttrAndNotify(TenantId.SYS_TENANT_ID, deviceId, DataConstants.SERVER_SCOPE, key, value, new AttributeSaveCallback(deviceId, key, value));
473 } 473 }
474 474
475 private class AttributeSaveCallback implements FutureCallback<Void> { 475 private class AttributeSaveCallback implements FutureCallback<Void> {
@@ -63,6 +63,7 @@ import java.util.Map; @@ -63,6 +63,7 @@ import java.util.Map;
63 import java.util.Optional; 63 import java.util.Optional;
64 import java.util.Set; 64 import java.util.Set;
65 import java.util.TreeMap; 65 import java.util.TreeMap;
  66 +import java.util.UUID;
66 import java.util.concurrent.ConcurrentHashMap; 67 import java.util.concurrent.ConcurrentHashMap;
67 import java.util.concurrent.ExecutorService; 68 import java.util.concurrent.ExecutorService;
68 import java.util.concurrent.Executors; 69 import java.util.concurrent.Executors;
@@ -131,7 +132,7 @@ public class DefaultTelemetrySubscriptionService implements TelemetrySubscriptio @@ -131,7 +132,7 @@ public class DefaultTelemetrySubscriptionService implements TelemetrySubscriptio
131 long startTime = 0L; 132 long startTime = 0L;
132 long endTime = 0L; 133 long endTime = 0L;
133 if (entityId.getEntityType().equals(EntityType.ENTITY_VIEW) && TelemetryFeature.TIMESERIES.equals(sub.getType())) { 134 if (entityId.getEntityType().equals(EntityType.ENTITY_VIEW) && TelemetryFeature.TIMESERIES.equals(sub.getType())) {
134 - EntityView entityView = entityViewService.findEntityViewById(new EntityViewId(entityId.getId())); 135 + EntityView entityView = entityViewService.findEntityViewById(TenantId.SYS_TENANT_ID, new EntityViewId(entityId.getId()));
135 entityId = entityView.getEntityId(); 136 entityId = entityView.getEntityId();
136 startTime = entityView.getStartTimeMs(); 137 startTime = entityView.getStartTimeMs();
137 endTime = entityView.getEndTimeMs(); 138 endTime = entityView.getEndTimeMs();
@@ -160,7 +161,7 @@ public class DefaultTelemetrySubscriptionService implements TelemetrySubscriptio @@ -160,7 +161,7 @@ public class DefaultTelemetrySubscriptionService implements TelemetrySubscriptio
160 .stream().filter(entry -> entityView.getKeys().getTimeseries().contains(entry.getKey())) 161 .stream().filter(entry -> entityView.getKeys().getTimeseries().contains(entry.getKey()))
161 .collect(Collectors.toMap(Map.Entry::getKey, Map.Entry::getValue)); 162 .collect(Collectors.toMap(Map.Entry::getKey, Map.Entry::getValue));
162 } 163 }
163 - return new SubscriptionState(sub.getWsSessionId(), sub.getSubscriptionId(), entityId, sub.getType(), false, keyStates, sub.getScope()); 164 + return new SubscriptionState(sub.getWsSessionId(), sub.getSubscriptionId(), sub.getTenantId(), entityId, sub.getType(), false, keyStates, sub.getScope());
164 } 165 }
165 166
166 @Override 167 @Override
@@ -185,45 +186,45 @@ public class DefaultTelemetrySubscriptionService implements TelemetrySubscriptio @@ -185,45 +186,45 @@ public class DefaultTelemetrySubscriptionService implements TelemetrySubscriptio
185 } 186 }
186 187
187 @Override 188 @Override
188 - public void saveAndNotify(EntityId entityId, List<TsKvEntry> ts, FutureCallback<Void> callback) {  
189 - saveAndNotify(entityId, ts, 0L, callback); 189 + public void saveAndNotify(TenantId tenantId, EntityId entityId, List<TsKvEntry> ts, FutureCallback<Void> callback) {
  190 + saveAndNotify(tenantId, entityId, ts, 0L, callback);
190 } 191 }
191 192
192 @Override 193 @Override
193 - public void saveAndNotify(EntityId entityId, List<TsKvEntry> ts, long ttl, FutureCallback<Void> callback) {  
194 - ListenableFuture<List<Void>> saveFuture = tsService.save(entityId, ts, ttl); 194 + public void saveAndNotify(TenantId tenantId, EntityId entityId, List<TsKvEntry> ts, long ttl, FutureCallback<Void> callback) {
  195 + ListenableFuture<List<Void>> saveFuture = tsService.save(tenantId, entityId, ts, ttl);
195 addMainCallback(saveFuture, callback); 196 addMainCallback(saveFuture, callback);
196 addWsCallback(saveFuture, success -> onTimeseriesUpdate(entityId, ts)); 197 addWsCallback(saveFuture, success -> onTimeseriesUpdate(entityId, ts));
197 } 198 }
198 199
199 @Override 200 @Override
200 - public void saveAndNotify(EntityId entityId, String scope, List<AttributeKvEntry> attributes, FutureCallback<Void> callback) {  
201 - ListenableFuture<List<Void>> saveFuture = attrService.save(entityId, scope, attributes); 201 + public void saveAndNotify(TenantId tenantId, EntityId entityId, String scope, List<AttributeKvEntry> attributes, FutureCallback<Void> callback) {
  202 + ListenableFuture<List<Void>> saveFuture = attrService.save(tenantId, entityId, scope, attributes);
202 addMainCallback(saveFuture, callback); 203 addMainCallback(saveFuture, callback);
203 addWsCallback(saveFuture, success -> onAttributesUpdate(entityId, scope, attributes)); 204 addWsCallback(saveFuture, success -> onAttributesUpdate(entityId, scope, attributes));
204 } 205 }
205 206
206 @Override 207 @Override
207 - public void saveAttrAndNotify(EntityId entityId, String scope, String key, long value, FutureCallback<Void> callback) {  
208 - saveAndNotify(entityId, scope, Collections.singletonList(new BaseAttributeKvEntry(new LongDataEntry(key, value) 208 + public void saveAttrAndNotify(TenantId tenantId, EntityId entityId, String scope, String key, long value, FutureCallback<Void> callback) {
  209 + saveAndNotify(tenantId, entityId, scope, Collections.singletonList(new BaseAttributeKvEntry(new LongDataEntry(key, value)
209 , System.currentTimeMillis())), callback); 210 , System.currentTimeMillis())), callback);
210 } 211 }
211 212
212 @Override 213 @Override
213 - public void saveAttrAndNotify(EntityId entityId, String scope, String key, String value, FutureCallback<Void> callback) {  
214 - saveAndNotify(entityId, scope, Collections.singletonList(new BaseAttributeKvEntry(new StringDataEntry(key, value) 214 + public void saveAttrAndNotify(TenantId tenantId, EntityId entityId, String scope, String key, String value, FutureCallback<Void> callback) {
  215 + saveAndNotify(tenantId, entityId, scope, Collections.singletonList(new BaseAttributeKvEntry(new StringDataEntry(key, value)
215 , System.currentTimeMillis())), callback); 216 , System.currentTimeMillis())), callback);
216 } 217 }
217 218
218 @Override 219 @Override
219 - public void saveAttrAndNotify(EntityId entityId, String scope, String key, double value, FutureCallback<Void> callback) {  
220 - saveAndNotify(entityId, scope, Collections.singletonList(new BaseAttributeKvEntry(new DoubleDataEntry(key, value) 220 + public void saveAttrAndNotify(TenantId tenantId, EntityId entityId, String scope, String key, double value, FutureCallback<Void> callback) {
  221 + saveAndNotify(tenantId, entityId, scope, Collections.singletonList(new BaseAttributeKvEntry(new DoubleDataEntry(key, value)
221 , System.currentTimeMillis())), callback); 222 , System.currentTimeMillis())), callback);
222 } 223 }
223 224
224 @Override 225 @Override
225 - public void saveAttrAndNotify(EntityId entityId, String scope, String key, boolean value, FutureCallback<Void> callback) {  
226 - saveAndNotify(entityId, scope, Collections.singletonList(new BaseAttributeKvEntry(new BooleanDataEntry(key, value) 226 + public void saveAttrAndNotify(TenantId tenantId, EntityId entityId, String scope, String key, boolean value, FutureCallback<Void> callback) {
  227 + saveAndNotify(tenantId, entityId, scope, Collections.singletonList(new BaseAttributeKvEntry(new BooleanDataEntry(key, value)
227 , System.currentTimeMillis())), callback); 228 , System.currentTimeMillis())), callback);
228 } 229 }
229 230
@@ -246,6 +247,7 @@ public class DefaultTelemetrySubscriptionService implements TelemetrySubscriptio @@ -246,6 +247,7 @@ public class DefaultTelemetrySubscriptionService implements TelemetrySubscriptio
246 Collectors.toMap(ClusterAPIProtos.SubscriptionKetStateProto::getKey, ClusterAPIProtos.SubscriptionKetStateProto::getTs)); 247 Collectors.toMap(ClusterAPIProtos.SubscriptionKetStateProto::getKey, ClusterAPIProtos.SubscriptionKetStateProto::getTs));
247 Subscription subscription = new Subscription( 248 Subscription subscription = new Subscription(
248 new SubscriptionState(proto.getSessionId(), proto.getSubscriptionId(), 249 new SubscriptionState(proto.getSessionId(), proto.getSubscriptionId(),
  250 + new TenantId(UUID.fromString(proto.getTenantId())),
249 EntityIdFactory.getByTypeAndId(proto.getEntityType(), proto.getEntityId()), 251 EntityIdFactory.getByTypeAndId(proto.getEntityType(), proto.getEntityId()),
250 TelemetryFeature.valueOf(proto.getType()), proto.getAllKeys(), statesMap, proto.getScope()), 252 TelemetryFeature.valueOf(proto.getType()), proto.getAllKeys(), statesMap, proto.getScope()),
251 false, new ServerAddress(serverAddress.getHost(), serverAddress.getPort(), serverAddress.getServerType())); 253 false, new ServerAddress(serverAddress.getHost(), serverAddress.getPort(), serverAddress.getServerType()));
@@ -372,7 +374,7 @@ public class DefaultTelemetrySubscriptionService implements TelemetrySubscriptio @@ -372,7 +374,7 @@ public class DefaultTelemetrySubscriptionService implements TelemetrySubscriptio
372 registerSubscription(sessionId, entityId, subscription); 374 registerSubscription(sessionId, entityId, subscription);
373 if (subscription.getType() == TelemetryFeature.ATTRIBUTES) { 375 if (subscription.getType() == TelemetryFeature.ATTRIBUTES) {
374 final Map<String, Long> keyStates = subscription.getKeyStates(); 376 final Map<String, Long> keyStates = subscription.getKeyStates();
375 - DonAsynchron.withCallback(attrService.find(entityId, DataConstants.CLIENT_SCOPE, keyStates.keySet()), values -> { 377 + DonAsynchron.withCallback(attrService.find(subscription.getSub().getTenantId(), entityId, DataConstants.CLIENT_SCOPE, keyStates.keySet()), values -> {
376 List<TsKvEntry> missedUpdates = new ArrayList<>(); 378 List<TsKvEntry> missedUpdates = new ArrayList<>();
377 values.forEach(latestEntry -> { 379 values.forEach(latestEntry -> {
378 if (latestEntry.getLastUpdateTs() > keyStates.get(latestEntry.getKey())) { 380 if (latestEntry.getLastUpdateTs() > keyStates.get(latestEntry.getKey())) {
@@ -395,7 +397,7 @@ public class DefaultTelemetrySubscriptionService implements TelemetrySubscriptio @@ -395,7 +397,7 @@ public class DefaultTelemetrySubscriptionService implements TelemetrySubscriptio
395 } 397 }
396 }); 398 });
397 if (!queries.isEmpty()) { 399 if (!queries.isEmpty()) {
398 - DonAsynchron.withCallback(tsService.findAll(entityId, queries), 400 + DonAsynchron.withCallback(tsService.findAll(subscription.getSub().getTenantId(), entityId, queries),
399 missedUpdates -> { 401 missedUpdates -> {
400 if (missedUpdates != null && !missedUpdates.isEmpty()) { 402 if (missedUpdates != null && !missedUpdates.isEmpty()) {
401 tellRemoteSubUpdate(address, sessionId, new SubscriptionUpdate(subscription.getSubscriptionId(), missedUpdates)); 403 tellRemoteSubUpdate(address, sessionId, new SubscriptionUpdate(subscription.getSubscriptionId(), missedUpdates));
@@ -606,6 +608,7 @@ public class DefaultTelemetrySubscriptionService implements TelemetrySubscriptio @@ -606,6 +608,7 @@ public class DefaultTelemetrySubscriptionService implements TelemetrySubscriptio
606 ClusterAPIProtos.SubscriptionProto.Builder builder = ClusterAPIProtos.SubscriptionProto.newBuilder(); 608 ClusterAPIProtos.SubscriptionProto.Builder builder = ClusterAPIProtos.SubscriptionProto.newBuilder();
607 builder.setSessionId(sessionId); 609 builder.setSessionId(sessionId);
608 builder.setSubscriptionId(sub.getSubscriptionId()); 610 builder.setSubscriptionId(sub.getSubscriptionId());
  611 + builder.setTenantId(sub.getSub().getTenantId().getId().toString());
609 builder.setEntityType(sub.getEntityId().getEntityType().name()); 612 builder.setEntityType(sub.getEntityId().getEntityType().name());
610 builder.setEntityId(sub.getEntityId().getId().toString()); 613 builder.setEntityId(sub.getEntityId().getId().toString());
611 builder.setType(sub.getType().name()); 614 builder.setType(sub.getType().name());
@@ -28,6 +28,7 @@ import org.springframework.util.StringUtils; @@ -28,6 +28,7 @@ import org.springframework.util.StringUtils;
28 import org.thingsboard.server.common.data.DataConstants; 28 import org.thingsboard.server.common.data.DataConstants;
29 import org.thingsboard.server.common.data.id.EntityId; 29 import org.thingsboard.server.common.data.id.EntityId;
30 import org.thingsboard.server.common.data.id.EntityIdFactory; 30 import org.thingsboard.server.common.data.id.EntityIdFactory;
  31 +import org.thingsboard.server.common.data.id.TenantId;
31 import org.thingsboard.server.common.data.kv.Aggregation; 32 import org.thingsboard.server.common.data.kv.Aggregation;
32 import org.thingsboard.server.common.data.kv.AttributeKvEntry; 33 import org.thingsboard.server.common.data.kv.AttributeKvEntry;
33 import org.thingsboard.server.common.data.kv.BaseReadTsKvQuery; 34 import org.thingsboard.server.common.data.kv.BaseReadTsKvQuery;
@@ -206,7 +207,7 @@ public class DefaultTelemetryWebSocketService implements TelemetryWebSocketServi @@ -206,7 +207,7 @@ public class DefaultTelemetryWebSocketService implements TelemetryWebSocketServi
206 keys.forEach(key -> subState.put(key, 0L)); 207 keys.forEach(key -> subState.put(key, 0L));
207 attributesData.forEach(v -> subState.put(v.getKey(), v.getTs())); 208 attributesData.forEach(v -> subState.put(v.getKey(), v.getTs()));
208 209
209 - SubscriptionState sub = new SubscriptionState(sessionId, cmd.getCmdId(), entityId, TelemetryFeature.ATTRIBUTES, false, subState, cmd.getScope()); 210 + SubscriptionState sub = new SubscriptionState(sessionId, cmd.getCmdId(), sessionRef.getSecurityCtx().getTenantId(), entityId, TelemetryFeature.ATTRIBUTES, false, subState, cmd.getScope());
210 subscriptionManager.addLocalWsSubscription(sessionId, entityId, sub); 211 subscriptionManager.addLocalWsSubscription(sessionId, entityId, sub);
211 } 212 }
212 213
@@ -226,9 +227,9 @@ public class DefaultTelemetryWebSocketService implements TelemetryWebSocketServi @@ -226,9 +227,9 @@ public class DefaultTelemetryWebSocketService implements TelemetryWebSocketServi
226 }; 227 };
227 228
228 if (StringUtils.isEmpty(cmd.getScope())) { 229 if (StringUtils.isEmpty(cmd.getScope())) {
229 - accessValidator.validate(sessionRef.getSecurityCtx(), entityId, getAttributesFetchCallback(entityId, keys, callback)); 230 + accessValidator.validate(sessionRef.getSecurityCtx(), entityId, getAttributesFetchCallback(sessionRef.getSecurityCtx().getTenantId(), entityId, keys, callback));
230 } else { 231 } else {
231 - accessValidator.validate(sessionRef.getSecurityCtx(), entityId, getAttributesFetchCallback(entityId, cmd.getScope(), keys, callback)); 232 + accessValidator.validate(sessionRef.getSecurityCtx(), entityId, getAttributesFetchCallback(sessionRef.getSecurityCtx().getTenantId(), entityId, cmd.getScope(), keys, callback));
232 } 233 }
233 } 234 }
234 235
@@ -279,7 +280,7 @@ public class DefaultTelemetryWebSocketService implements TelemetryWebSocketServi @@ -279,7 +280,7 @@ public class DefaultTelemetryWebSocketService implements TelemetryWebSocketServi
279 } 280 }
280 }; 281 };
281 accessValidator.validate(sessionRef.getSecurityCtx(), entityId, 282 accessValidator.validate(sessionRef.getSecurityCtx(), entityId,
282 - on(r -> Futures.addCallback(tsService.findAll(entityId, queries), callback, executor), callback::onFailure)); 283 + on(r -> Futures.addCallback(tsService.findAll(sessionRef.getSecurityCtx().getTenantId(), entityId, queries), callback, executor), callback::onFailure));
283 } 284 }
284 285
285 private void handleWsAttributesSubscription(TelemetryWebSocketSessionRef sessionRef, 286 private void handleWsAttributesSubscription(TelemetryWebSocketSessionRef sessionRef,
@@ -293,7 +294,7 @@ public class DefaultTelemetryWebSocketService implements TelemetryWebSocketServi @@ -293,7 +294,7 @@ public class DefaultTelemetryWebSocketService implements TelemetryWebSocketServi
293 Map<String, Long> subState = new HashMap<>(attributesData.size()); 294 Map<String, Long> subState = new HashMap<>(attributesData.size());
294 attributesData.forEach(v -> subState.put(v.getKey(), v.getTs())); 295 attributesData.forEach(v -> subState.put(v.getKey(), v.getTs()));
295 296
296 - SubscriptionState sub = new SubscriptionState(sessionId, cmd.getCmdId(), entityId, TelemetryFeature.ATTRIBUTES, true, subState, cmd.getScope()); 297 + SubscriptionState sub = new SubscriptionState(sessionId, cmd.getCmdId(), sessionRef.getSecurityCtx().getTenantId(), entityId, TelemetryFeature.ATTRIBUTES, true, subState, cmd.getScope());
297 subscriptionManager.addLocalWsSubscription(sessionId, entityId, sub); 298 subscriptionManager.addLocalWsSubscription(sessionId, entityId, sub);
298 } 299 }
299 300
@@ -308,9 +309,9 @@ public class DefaultTelemetryWebSocketService implements TelemetryWebSocketServi @@ -308,9 +309,9 @@ public class DefaultTelemetryWebSocketService implements TelemetryWebSocketServi
308 309
309 310
310 if (StringUtils.isEmpty(cmd.getScope())) { 311 if (StringUtils.isEmpty(cmd.getScope())) {
311 - accessValidator.validate(sessionRef.getSecurityCtx(), entityId, getAttributesFetchCallback(entityId, callback)); 312 + accessValidator.validate(sessionRef.getSecurityCtx(), entityId, getAttributesFetchCallback(sessionRef.getSecurityCtx().getTenantId(), entityId, callback));
312 } else { 313 } else {
313 - accessValidator.validate(sessionRef.getSecurityCtx(), entityId, getAttributesFetchCallback(entityId, cmd.getScope(), callback)); 314 + accessValidator.validate(sessionRef.getSecurityCtx(), entityId, getAttributesFetchCallback(sessionRef.getSecurityCtx().getTenantId(), entityId, cmd.getScope(), callback));
314 } 315 }
315 } 316 }
316 317
@@ -347,14 +348,14 @@ public class DefaultTelemetryWebSocketService implements TelemetryWebSocketServi @@ -347,14 +348,14 @@ public class DefaultTelemetryWebSocketService implements TelemetryWebSocketServi
347 348
348 final FutureCallback<List<TsKvEntry>> callback = getSubscriptionCallback(sessionRef, cmd, sessionId, entityId, startTs, keys); 349 final FutureCallback<List<TsKvEntry>> callback = getSubscriptionCallback(sessionRef, cmd, sessionId, entityId, startTs, keys);
349 accessValidator.validate(sessionRef.getSecurityCtx(), entityId, 350 accessValidator.validate(sessionRef.getSecurityCtx(), entityId,
350 - on(r -> Futures.addCallback(tsService.findAll(entityId, queries), callback, executor), callback::onFailure)); 351 + on(r -> Futures.addCallback(tsService.findAll(sessionRef.getSecurityCtx().getTenantId(), entityId, queries), callback, executor), callback::onFailure));
351 } else { 352 } else {
352 List<String> keys = new ArrayList<>(getKeys(cmd).orElse(Collections.emptySet())); 353 List<String> keys = new ArrayList<>(getKeys(cmd).orElse(Collections.emptySet()));
353 startTs = System.currentTimeMillis(); 354 startTs = System.currentTimeMillis();
354 log.debug("[{}] fetching latest timeseries data for keys: ({}) for device : {}", sessionId, cmd.getKeys(), entityId); 355 log.debug("[{}] fetching latest timeseries data for keys: ({}) for device : {}", sessionId, cmd.getKeys(), entityId);
355 final FutureCallback<List<TsKvEntry>> callback = getSubscriptionCallback(sessionRef, cmd, sessionId, entityId, startTs, keys); 356 final FutureCallback<List<TsKvEntry>> callback = getSubscriptionCallback(sessionRef, cmd, sessionId, entityId, startTs, keys);
356 accessValidator.validate(sessionRef.getSecurityCtx(), entityId, 357 accessValidator.validate(sessionRef.getSecurityCtx(), entityId,
357 - on(r -> Futures.addCallback(tsService.findLatest(entityId, keys), callback, executor), callback::onFailure)); 358 + on(r -> Futures.addCallback(tsService.findLatest(sessionRef.getSecurityCtx().getTenantId(), entityId, keys), callback, executor), callback::onFailure));
358 } 359 }
359 } 360 }
360 361
@@ -366,7 +367,7 @@ public class DefaultTelemetryWebSocketService implements TelemetryWebSocketServi @@ -366,7 +367,7 @@ public class DefaultTelemetryWebSocketService implements TelemetryWebSocketServi
366 sendWsMsg(sessionRef, new SubscriptionUpdate(cmd.getCmdId(), data)); 367 sendWsMsg(sessionRef, new SubscriptionUpdate(cmd.getCmdId(), data));
367 Map<String, Long> subState = new HashMap<>(data.size()); 368 Map<String, Long> subState = new HashMap<>(data.size());
368 data.forEach(v -> subState.put(v.getKey(), v.getTs())); 369 data.forEach(v -> subState.put(v.getKey(), v.getTs()));
369 - SubscriptionState sub = new SubscriptionState(sessionId, cmd.getCmdId(), entityId, TelemetryFeature.TIMESERIES, true, subState, cmd.getScope()); 370 + SubscriptionState sub = new SubscriptionState(sessionId, cmd.getCmdId(), sessionRef.getSecurityCtx().getTenantId(), entityId, TelemetryFeature.TIMESERIES, true, subState, cmd.getScope());
370 subscriptionManager.addLocalWsSubscription(sessionId, entityId, sub); 371 subscriptionManager.addLocalWsSubscription(sessionId, entityId, sub);
371 } 372 }
372 373
@@ -384,7 +385,7 @@ public class DefaultTelemetryWebSocketService implements TelemetryWebSocketServi @@ -384,7 +385,7 @@ public class DefaultTelemetryWebSocketService implements TelemetryWebSocketServi
384 } 385 }
385 }; 386 };
386 accessValidator.validate(sessionRef.getSecurityCtx(), entityId, 387 accessValidator.validate(sessionRef.getSecurityCtx(), entityId,
387 - on(r -> Futures.addCallback(tsService.findAllLatest(entityId), callback, executor), callback::onFailure)); 388 + on(r -> Futures.addCallback(tsService.findAllLatest(sessionRef.getSecurityCtx().getTenantId(), entityId), callback, executor), callback::onFailure));
388 } 389 }
389 390
390 private FutureCallback<List<TsKvEntry>> getSubscriptionCallback(final TelemetryWebSocketSessionRef sessionRef, final TimeseriesSubscriptionCmd cmd, final String sessionId, final EntityId entityId, final long startTs, final List<String> keys) { 391 private FutureCallback<List<TsKvEntry>> getSubscriptionCallback(final TelemetryWebSocketSessionRef sessionRef, final TimeseriesSubscriptionCmd cmd, final String sessionId, final EntityId entityId, final long startTs, final List<String> keys) {
@@ -396,7 +397,7 @@ public class DefaultTelemetryWebSocketService implements TelemetryWebSocketServi @@ -396,7 +397,7 @@ public class DefaultTelemetryWebSocketService implements TelemetryWebSocketServi
396 Map<String, Long> subState = new HashMap<>(keys.size()); 397 Map<String, Long> subState = new HashMap<>(keys.size());
397 keys.forEach(key -> subState.put(key, startTs)); 398 keys.forEach(key -> subState.put(key, startTs));
398 data.forEach(v -> subState.put(v.getKey(), v.getTs())); 399 data.forEach(v -> subState.put(v.getKey(), v.getTs()));
399 - SubscriptionState sub = new SubscriptionState(sessionId, cmd.getCmdId(), entityId, TelemetryFeature.TIMESERIES, false, subState, cmd.getScope()); 400 + SubscriptionState sub = new SubscriptionState(sessionId, cmd.getCmdId(), sessionRef.getSecurityCtx().getTenantId(), entityId, TelemetryFeature.TIMESERIES, false, subState, cmd.getScope());
400 subscriptionManager.addLocalWsSubscription(sessionId, entityId, sub); 401 subscriptionManager.addLocalWsSubscription(sessionId, entityId, sub);
401 } 402 }
402 403
@@ -472,13 +473,13 @@ public class DefaultTelemetryWebSocketService implements TelemetryWebSocketServi @@ -472,13 +473,13 @@ public class DefaultTelemetryWebSocketService implements TelemetryWebSocketServi
472 }, executor); 473 }, executor);
473 } 474 }
474 475
475 - private <T> FutureCallback<ValidationResult> getAttributesFetchCallback(final EntityId entityId, final List<String> keys, final FutureCallback<List<AttributeKvEntry>> callback) { 476 + private <T> FutureCallback<ValidationResult> getAttributesFetchCallback(final TenantId tenantId, final EntityId entityId, final List<String> keys, final FutureCallback<List<AttributeKvEntry>> callback) {
476 return new FutureCallback<ValidationResult>() { 477 return new FutureCallback<ValidationResult>() {
477 @Override 478 @Override
478 public void onSuccess(@Nullable ValidationResult result) { 479 public void onSuccess(@Nullable ValidationResult result) {
479 List<ListenableFuture<List<AttributeKvEntry>>> futures = new ArrayList<>(); 480 List<ListenableFuture<List<AttributeKvEntry>>> futures = new ArrayList<>();
480 for (String scope : DataConstants.allScopes()) { 481 for (String scope : DataConstants.allScopes()) {
481 - futures.add(attributesService.find(entityId, scope, keys)); 482 + futures.add(attributesService.find(tenantId, entityId, scope, keys));
482 } 483 }
483 484
484 ListenableFuture<List<AttributeKvEntry>> future = mergeAllAttributesFutures(futures); 485 ListenableFuture<List<AttributeKvEntry>> future = mergeAllAttributesFutures(futures);
@@ -492,11 +493,11 @@ public class DefaultTelemetryWebSocketService implements TelemetryWebSocketServi @@ -492,11 +493,11 @@ public class DefaultTelemetryWebSocketService implements TelemetryWebSocketServi
492 }; 493 };
493 } 494 }
494 495
495 - private <T> FutureCallback<ValidationResult> getAttributesFetchCallback(final EntityId entityId, final String scope, final List<String> keys, final FutureCallback<List<AttributeKvEntry>> callback) { 496 + private <T> FutureCallback<ValidationResult> getAttributesFetchCallback(final TenantId tenantId, final EntityId entityId, final String scope, final List<String> keys, final FutureCallback<List<AttributeKvEntry>> callback) {
496 return new FutureCallback<ValidationResult>() { 497 return new FutureCallback<ValidationResult>() {
497 @Override 498 @Override
498 public void onSuccess(@Nullable ValidationResult result) { 499 public void onSuccess(@Nullable ValidationResult result) {
499 - Futures.addCallback(attributesService.find(entityId, scope, keys), callback); 500 + Futures.addCallback(attributesService.find(tenantId, entityId, scope, keys), callback);
500 } 501 }
501 502
502 @Override 503 @Override
@@ -506,13 +507,13 @@ public class DefaultTelemetryWebSocketService implements TelemetryWebSocketServi @@ -506,13 +507,13 @@ public class DefaultTelemetryWebSocketService implements TelemetryWebSocketServi
506 }; 507 };
507 } 508 }
508 509
509 - private <T> FutureCallback<ValidationResult> getAttributesFetchCallback(final EntityId entityId, final FutureCallback<List<AttributeKvEntry>> callback) { 510 + private <T> FutureCallback<ValidationResult> getAttributesFetchCallback(final TenantId tenantId, final EntityId entityId, final FutureCallback<List<AttributeKvEntry>> callback) {
510 return new FutureCallback<ValidationResult>() { 511 return new FutureCallback<ValidationResult>() {
511 @Override 512 @Override
512 public void onSuccess(@Nullable ValidationResult result) { 513 public void onSuccess(@Nullable ValidationResult result) {
513 List<ListenableFuture<List<AttributeKvEntry>>> futures = new ArrayList<>(); 514 List<ListenableFuture<List<AttributeKvEntry>>> futures = new ArrayList<>();
514 for (String scope : DataConstants.allScopes()) { 515 for (String scope : DataConstants.allScopes()) {
515 - futures.add(attributesService.findAll(entityId, scope)); 516 + futures.add(attributesService.findAll(tenantId, entityId, scope));
516 } 517 }
517 518
518 ListenableFuture<List<AttributeKvEntry>> future = mergeAllAttributesFutures(futures); 519 ListenableFuture<List<AttributeKvEntry>> future = mergeAllAttributesFutures(futures);
@@ -526,11 +527,11 @@ public class DefaultTelemetryWebSocketService implements TelemetryWebSocketServi @@ -526,11 +527,11 @@ public class DefaultTelemetryWebSocketService implements TelemetryWebSocketServi
526 }; 527 };
527 } 528 }
528 529
529 - private <T> FutureCallback<ValidationResult> getAttributesFetchCallback(final EntityId entityId, final String scope, final FutureCallback<List<AttributeKvEntry>> callback) { 530 + private <T> FutureCallback<ValidationResult> getAttributesFetchCallback(final TenantId tenantId, final EntityId entityId, final String scope, final FutureCallback<List<AttributeKvEntry>> callback) {
530 return new FutureCallback<ValidationResult>() { 531 return new FutureCallback<ValidationResult>() {
531 @Override 532 @Override
532 public void onSuccess(@Nullable ValidationResult result) { 533 public void onSuccess(@Nullable ValidationResult result) {
533 - Futures.addCallback(attributesService.findAll(entityId, scope), callback); 534 + Futures.addCallback(attributesService.findAll(tenantId, entityId, scope), callback);
534 } 535 }
535 536
536 @Override 537 @Override
@@ -17,6 +17,7 @@ package org.thingsboard.server.service.telemetry; @@ -17,6 +17,7 @@ package org.thingsboard.server.service.telemetry;
17 17
18 import org.thingsboard.rule.engine.api.RuleEngineTelemetryService; 18 import org.thingsboard.rule.engine.api.RuleEngineTelemetryService;
19 import org.thingsboard.server.common.data.id.EntityId; 19 import org.thingsboard.server.common.data.id.EntityId;
  20 +import org.thingsboard.server.common.data.id.TenantId;
20 import org.thingsboard.server.common.msg.cluster.ServerAddress; 21 import org.thingsboard.server.common.msg.cluster.ServerAddress;
21 import org.thingsboard.server.service.telemetry.sub.SubscriptionState; 22 import org.thingsboard.server.service.telemetry.sub.SubscriptionState;
22 23
@@ -18,6 +18,7 @@ package org.thingsboard.server.service.telemetry.sub; @@ -18,6 +18,7 @@ package org.thingsboard.server.service.telemetry.sub;
18 import lombok.AllArgsConstructor; 18 import lombok.AllArgsConstructor;
19 import lombok.Getter; 19 import lombok.Getter;
20 import org.thingsboard.server.common.data.id.EntityId; 20 import org.thingsboard.server.common.data.id.EntityId;
  21 +import org.thingsboard.server.common.data.id.TenantId;
21 import org.thingsboard.server.service.telemetry.TelemetryFeature; 22 import org.thingsboard.server.service.telemetry.TelemetryFeature;
22 23
23 import java.util.Map; 24 import java.util.Map;
@@ -30,6 +31,7 @@ public class SubscriptionState { @@ -30,6 +31,7 @@ public class SubscriptionState {
30 31
31 @Getter private final String wsSessionId; 32 @Getter private final String wsSessionId;
32 @Getter private final int subscriptionId; 33 @Getter private final int subscriptionId;
  34 + @Getter private final TenantId tenantId;
33 @Getter private final EntityId entityId; 35 @Getter private final EntityId entityId;
34 @Getter private final TelemetryFeature type; 36 @Getter private final TelemetryFeature type;
35 @Getter private final boolean allKeys; 37 @Getter private final boolean allKeys;
@@ -26,6 +26,7 @@ import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty; @@ -26,6 +26,7 @@ import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
26 import org.springframework.stereotype.Service; 26 import org.springframework.stereotype.Service;
27 import org.thingsboard.server.common.data.Device; 27 import org.thingsboard.server.common.data.Device;
28 import org.thingsboard.server.common.data.id.DeviceId; 28 import org.thingsboard.server.common.data.id.DeviceId;
  29 +import org.thingsboard.server.common.data.id.TenantId;
29 import org.thingsboard.server.common.data.relation.EntityRelation; 30 import org.thingsboard.server.common.data.relation.EntityRelation;
30 import org.thingsboard.server.common.data.security.DeviceCredentials; 31 import org.thingsboard.server.common.data.security.DeviceCredentials;
31 import org.thingsboard.server.common.data.security.DeviceCredentialsType; 32 import org.thingsboard.server.common.data.security.DeviceCredentialsType;
@@ -107,7 +108,7 @@ public class LocalTransportApiService implements TransportApiService { @@ -107,7 +108,7 @@ public class LocalTransportApiService implements TransportApiService {
107 108
108 private ListenableFuture<TransportApiResponseMsg> handle(GetOrCreateDeviceFromGatewayRequestMsg requestMsg) { 109 private ListenableFuture<TransportApiResponseMsg> handle(GetOrCreateDeviceFromGatewayRequestMsg requestMsg) {
109 DeviceId gatewayId = new DeviceId(new UUID(requestMsg.getGatewayIdMSB(), requestMsg.getGatewayIdLSB())); 110 DeviceId gatewayId = new DeviceId(new UUID(requestMsg.getGatewayIdMSB(), requestMsg.getGatewayIdLSB()));
110 - ListenableFuture<Device> gatewayFuture = deviceService.findDeviceByIdAsync(gatewayId); 111 + ListenableFuture<Device> gatewayFuture = deviceService.findDeviceByIdAsync(TenantId.SYS_TENANT_ID, gatewayId);
111 return Futures.transform(gatewayFuture, gateway -> { 112 return Futures.transform(gatewayFuture, gateway -> {
112 deviceCreationLock.lock(); 113 deviceCreationLock.lock();
113 try { 114 try {
@@ -119,7 +120,7 @@ public class LocalTransportApiService implements TransportApiService { @@ -119,7 +120,7 @@ public class LocalTransportApiService implements TransportApiService {
119 device.setType(requestMsg.getDeviceType()); 120 device.setType(requestMsg.getDeviceType());
120 device.setCustomerId(gateway.getCustomerId()); 121 device.setCustomerId(gateway.getCustomerId());
121 device = deviceService.saveDevice(device); 122 device = deviceService.saveDevice(device);
122 - relationService.saveRelationAsync(new EntityRelation(gateway.getId(), device.getId(), "Created")); 123 + relationService.saveRelationAsync(TenantId.SYS_TENANT_ID, new EntityRelation(gateway.getId(), device.getId(), "Created"));
123 deviceStateService.onDeviceAdded(device); 124 deviceStateService.onDeviceAdded(device);
124 } 125 }
125 return TransportApiResponseMsg.newBuilder() 126 return TransportApiResponseMsg.newBuilder()
@@ -135,7 +136,7 @@ public class LocalTransportApiService implements TransportApiService { @@ -135,7 +136,7 @@ public class LocalTransportApiService implements TransportApiService {
135 136
136 137
137 private ListenableFuture<TransportApiResponseMsg> getDeviceInfo(DeviceId deviceId) { 138 private ListenableFuture<TransportApiResponseMsg> getDeviceInfo(DeviceId deviceId) {
138 - return Futures.transform(deviceService.findDeviceByIdAsync(deviceId), device -> { 139 + return Futures.transform(deviceService.findDeviceByIdAsync(TenantId.SYS_TENANT_ID, deviceId), device -> {
139 if (device == null) { 140 if (device == null) {
140 log.trace("[{}] Failed to lookup device by id", deviceId); 141 log.trace("[{}] Failed to lookup device by id", deviceId);
141 return getEmptyTransportApiResponse(); 142 return getEmptyTransportApiResponse();
@@ -67,11 +67,12 @@ message SubscriptionProto { @@ -67,11 +67,12 @@ message SubscriptionProto {
67 string sessionId = 1; 67 string sessionId = 1;
68 int32 subscriptionId = 2; 68 int32 subscriptionId = 2;
69 string entityType = 3; 69 string entityType = 3;
70 - string entityId = 4;  
71 - string type = 5;  
72 - bool allKeys = 6;  
73 - repeated SubscriptionKetStateProto keyStates = 7;  
74 - string scope = 8; 70 + string tenantId = 4;
  71 + string entityId = 5;
  72 + string type = 6;
  73 + bool allKeys = 7;
  74 + repeated SubscriptionKetStateProto keyStates = 8;
  75 + string scope = 9;
75 } 76 }
76 77
77 message SubscriptionUpdateProto { 78 message SubscriptionUpdateProto {
@@ -142,9 +142,9 @@ public abstract class AbstractRuleEngineFlowIntegrationTest extends AbstractRule @@ -142,9 +142,9 @@ public abstract class AbstractRuleEngineFlowIntegrationTest extends AbstractRule
142 device.setType("default"); 142 device.setType("default");
143 device = doPost("/api/device", device, Device.class); 143 device = doPost("/api/device", device, Device.class);
144 144
145 - attributesService.save(device.getId(), DataConstants.SERVER_SCOPE, 145 + attributesService.save(device.getTenantId(), device.getId(), DataConstants.SERVER_SCOPE,
146 Collections.singletonList(new BaseAttributeKvEntry(new StringDataEntry("serverAttributeKey1", "serverAttributeValue1"), System.currentTimeMillis()))); 146 Collections.singletonList(new BaseAttributeKvEntry(new StringDataEntry("serverAttributeKey1", "serverAttributeValue1"), System.currentTimeMillis())));
147 - attributesService.save(device.getId(), DataConstants.SERVER_SCOPE, 147 + attributesService.save(device.getTenantId(), device.getId(), DataConstants.SERVER_SCOPE,
148 Collections.singletonList(new BaseAttributeKvEntry(new StringDataEntry("serverAttributeKey2", "serverAttributeValue2"), System.currentTimeMillis()))); 148 Collections.singletonList(new BaseAttributeKvEntry(new StringDataEntry("serverAttributeKey2", "serverAttributeValue2"), System.currentTimeMillis())));
149 149
150 150
@@ -257,9 +257,9 @@ public abstract class AbstractRuleEngineFlowIntegrationTest extends AbstractRule @@ -257,9 +257,9 @@ public abstract class AbstractRuleEngineFlowIntegrationTest extends AbstractRule
257 device.setType("default"); 257 device.setType("default");
258 device = doPost("/api/device", device, Device.class); 258 device = doPost("/api/device", device, Device.class);
259 259
260 - attributesService.save(device.getId(), DataConstants.SERVER_SCOPE, 260 + attributesService.save(device.getTenantId(), device.getId(), DataConstants.SERVER_SCOPE,
261 Collections.singletonList(new BaseAttributeKvEntry(new StringDataEntry("serverAttributeKey1", "serverAttributeValue1"), System.currentTimeMillis()))); 261 Collections.singletonList(new BaseAttributeKvEntry(new StringDataEntry("serverAttributeKey1", "serverAttributeValue1"), System.currentTimeMillis())));
262 - attributesService.save(device.getId(), DataConstants.SERVER_SCOPE, 262 + attributesService.save(device.getTenantId(), device.getId(), DataConstants.SERVER_SCOPE,
263 Collections.singletonList(new BaseAttributeKvEntry(new StringDataEntry("serverAttributeKey2", "serverAttributeValue2"), System.currentTimeMillis()))); 263 Collections.singletonList(new BaseAttributeKvEntry(new StringDataEntry("serverAttributeKey2", "serverAttributeValue2"), System.currentTimeMillis())));
264 264
265 265
@@ -131,7 +131,7 @@ public abstract class AbstractRuleEngineLifecycleIntegrationTest extends Abstrac @@ -131,7 +131,7 @@ public abstract class AbstractRuleEngineLifecycleIntegrationTest extends Abstrac
131 device.setType("default"); 131 device.setType("default");
132 device = doPost("/api/device", device, Device.class); 132 device = doPost("/api/device", device, Device.class);
133 133
134 - attributesService.save(device.getId(), DataConstants.SERVER_SCOPE, 134 + attributesService.save(device.getTenantId(), device.getId(), DataConstants.SERVER_SCOPE,
135 Collections.singletonList(new BaseAttributeKvEntry(new StringDataEntry("serverAttributeKey", "serverAttributeValue"), System.currentTimeMillis()))); 135 Collections.singletonList(new BaseAttributeKvEntry(new StringDataEntry("serverAttributeKey", "serverAttributeValue"), System.currentTimeMillis())));
136 136
137 Thread.sleep(1000); 137 Thread.sleep(1000);
@@ -24,6 +24,9 @@ import org.thingsboard.server.common.data.EntityType; @@ -24,6 +24,9 @@ import org.thingsboard.server.common.data.EntityType;
24 24
25 public final class TenantId extends UUIDBased implements EntityId { 25 public final class TenantId extends UUIDBased implements EntityId {
26 26
  27 + @JsonIgnore
  28 + public static final TenantId SYS_TENANT_ID = new TenantId(EntityId.NULL_UUID);
  29 +
27 private static final long serialVersionUID = 1L; 30 private static final long serialVersionUID = 1L;
28 31
29 @JsonCreator 32 @JsonCreator
@@ -25,6 +25,4 @@ public interface DeviceAuthService { @@ -25,6 +25,4 @@ public interface DeviceAuthService {
25 25
26 DeviceAuthResult process(DeviceCredentialsFilter credentials); 26 DeviceAuthResult process(DeviceCredentialsFilter credentials);
27 27
28 - Optional<Device> findDeviceById(DeviceId deviceId);  
29 -  
30 } 28 }
@@ -53,6 +53,6 @@ cassandra.query.buffer_size=100000 @@ -53,6 +53,6 @@ cassandra.query.buffer_size=100000
53 cassandra.query.concurrent_limit=1000 53 cassandra.query.concurrent_limit=1000
54 cassandra.query.permit_max_wait_time=20000 54 cassandra.query.permit_max_wait_time=20000
55 cassandra.query.rate_limit_print_interval_ms=30000 55 cassandra.query.rate_limit_print_interval_ms=30000
56 -cassandra.query.tenant_rate_limits.enabled=true 56 +cassandra.query.tenant_rate_limits.enabled=false
57 cassandra.query.tenant_rate_limits.configuration=5000:1,100000:60 57 cassandra.query.tenant_rate_limits.configuration=5000:1,100000:60
58 58
@@ -30,19 +30,19 @@ import java.util.Set; @@ -30,19 +30,19 @@ import java.util.Set;
30 */ 30 */
31 public interface RuleEngineTelemetryService { 31 public interface RuleEngineTelemetryService {
32 32
33 - void saveAndNotify(EntityId entityId, List<TsKvEntry> ts, FutureCallback<Void> callback); 33 + void saveAndNotify(TenantId tenantId, EntityId entityId, List<TsKvEntry> ts, FutureCallback<Void> callback);
34 34
35 - void saveAndNotify(EntityId entityId, List<TsKvEntry> ts, long ttl, FutureCallback<Void> callback); 35 + void saveAndNotify(TenantId tenantId, EntityId entityId, List<TsKvEntry> ts, long ttl, FutureCallback<Void> callback);
36 36
37 - void saveAndNotify(EntityId entityId, String scope, List<AttributeKvEntry> attributes, FutureCallback<Void> callback); 37 + void saveAndNotify(TenantId tenantId, EntityId entityId, String scope, List<AttributeKvEntry> attributes, FutureCallback<Void> callback);
38 38
39 - void saveAttrAndNotify(EntityId entityId, String scope, String key, long value, FutureCallback<Void> callback); 39 + void saveAttrAndNotify(TenantId tenantId, EntityId entityId, String scope, String key, long value, FutureCallback<Void> callback);
40 40
41 - void saveAttrAndNotify(EntityId entityId, String scope, String key, String value, FutureCallback<Void> callback); 41 + void saveAttrAndNotify(TenantId tenantId, EntityId entityId, String scope, String key, String value, FutureCallback<Void> callback);
42 42
43 - void saveAttrAndNotify(EntityId entityId, String scope, String key, double value, FutureCallback<Void> callback); 43 + void saveAttrAndNotify(TenantId tenantId, EntityId entityId, String scope, String key, double value, FutureCallback<Void> callback);
44 44
45 - void saveAttrAndNotify(EntityId entityId, String scope, String key, boolean value, FutureCallback<Void> callback); 45 + void saveAttrAndNotify(TenantId tenantId, EntityId entityId, String scope, String key, boolean value, FutureCallback<Void> callback);
46 46
47 void onSharedAttributesUpdate(TenantId tenantId, DeviceId deviceId, Set<AttributeKvEntry> attributes); 47 void onSharedAttributesUpdate(TenantId tenantId, DeviceId deviceId, Set<AttributeKvEntry> attributes);
48 48
@@ -66,7 +66,7 @@ public class TbClearAlarmNode extends TbAbstractAlarmNode<TbClearAlarmNodeConfig @@ -66,7 +66,7 @@ public class TbClearAlarmNode extends TbAbstractAlarmNode<TbClearAlarmNodeConfig
66 private ListenableFuture<AlarmResult> clearAlarm(TbContext ctx, TbMsg msg, Alarm alarm) { 66 private ListenableFuture<AlarmResult> clearAlarm(TbContext ctx, TbMsg msg, Alarm alarm) {
67 ListenableFuture<JsonNode> asyncDetails = buildAlarmDetails(ctx, msg, alarm.getDetails()); 67 ListenableFuture<JsonNode> asyncDetails = buildAlarmDetails(ctx, msg, alarm.getDetails());
68 return Futures.transformAsync(asyncDetails, details -> { 68 return Futures.transformAsync(asyncDetails, details -> {
69 - ListenableFuture<Boolean> clearFuture = ctx.getAlarmService().clearAlarm(alarm.getId(), details, System.currentTimeMillis()); 69 + ListenableFuture<Boolean> clearFuture = ctx.getAlarmService().clearAlarm(ctx.getTenantId(), alarm.getId(), details, System.currentTimeMillis());
70 return Futures.transformAsync(clearFuture, cleared -> { 70 return Futures.transformAsync(clearFuture, cleared -> {
71 if (cleared && details != null) { 71 if (cleared && details != null) {
72 alarm.setDetails(details); 72 alarm.setDetails(details);
@@ -91,7 +91,7 @@ public class TbCopyAttributesToEntityViewNode implements TbNode { @@ -91,7 +91,7 @@ public class TbCopyAttributesToEntityViewNode implements TbNode {
91 Set<AttributeKvEntry> attributes = JsonConverter.convertToAttributes(new JsonParser().parse(msg.getData())); 91 Set<AttributeKvEntry> attributes = JsonConverter.convertToAttributes(new JsonParser().parse(msg.getData()));
92 List<AttributeKvEntry> filteredAttributes = 92 List<AttributeKvEntry> filteredAttributes =
93 attributes.stream().filter(attr -> attributeContainsInEntityView(scope, attr.getKey(), entityView)).collect(Collectors.toList()); 93 attributes.stream().filter(attr -> attributeContainsInEntityView(scope, attr.getKey(), entityView)).collect(Collectors.toList());
94 - ctx.getTelemetryService().saveAndNotify(entityView.getId(), scope, filteredAttributes, 94 + ctx.getTelemetryService().saveAndNotify(ctx.getTenantId(), entityView.getId(), scope, filteredAttributes,
95 new FutureCallback<Void>() { 95 new FutureCallback<Void>() {
96 @Override 96 @Override
97 public void onSuccess(@Nullable Void result) { 97 public void onSuccess(@Nullable Void result) {
@@ -116,7 +116,7 @@ public class TbCopyAttributesToEntityViewNode implements TbNode { @@ -116,7 +116,7 @@ public class TbCopyAttributesToEntityViewNode implements TbNode {
116 List<String> filteredAttributes = 116 List<String> filteredAttributes =
117 attributes.stream().filter(attr -> attributeContainsInEntityView(scope, attr, entityView)).collect(Collectors.toList()); 117 attributes.stream().filter(attr -> attributeContainsInEntityView(scope, attr, entityView)).collect(Collectors.toList());
118 if (filteredAttributes != null && !filteredAttributes.isEmpty()) { 118 if (filteredAttributes != null && !filteredAttributes.isEmpty()) {
119 - ctx.getAttributesService().removeAll(entityView.getId(), scope, filteredAttributes); 119 + ctx.getAttributesService().removeAll(ctx.getTenantId(), entityView.getId(), scope, filteredAttributes);
120 transformAndTellNext(ctx, msg, entityView); 120 transformAndTellNext(ctx, msg, entityView);
121 } 121 }
122 } 122 }
@@ -67,7 +67,7 @@ public class TbCheckRelationNode implements TbNode { @@ -67,7 +67,7 @@ public class TbCheckRelationNode implements TbNode {
67 to = EntityIdFactory.getByTypeAndId(config.getEntityType(), config.getEntityId()); 67 to = EntityIdFactory.getByTypeAndId(config.getEntityType(), config.getEntityId());
68 from = msg.getOriginator(); 68 from = msg.getOriginator();
69 } 69 }
70 - withCallback(ctx.getRelationService().checkRelation(from, to, config.getRelationType(), RelationTypeGroup.COMMON), 70 + withCallback(ctx.getRelationService().checkRelation(ctx.getTenantId(), from, to, config.getRelationType(), RelationTypeGroup.COMMON),
71 filterResult -> ctx.tellNext(msg, filterResult ? "True" : "False"), t -> ctx.tellFailure(msg, t), ctx.getDbCallbackExecutor()); 71 filterResult -> ctx.tellNext(msg, filterResult ? "True" : "False"), t -> ctx.tellFailure(msg, t), ctx.getDbCallbackExecutor());
72 } 72 }
73 73
@@ -77,7 +77,7 @@ public abstract class TbAbstractGetAttributesNode<C extends TbGetAttributesNodeC @@ -77,7 +77,7 @@ public abstract class TbAbstractGetAttributesNode<C extends TbGetAttributesNodeC
77 if (CollectionUtils.isEmpty(keys)) { 77 if (CollectionUtils.isEmpty(keys)) {
78 return Futures.immediateFuture(null); 78 return Futures.immediateFuture(null);
79 } 79 }
80 - ListenableFuture<List<AttributeKvEntry>> latest = ctx.getAttributesService().find(entityId, scope, keys); 80 + ListenableFuture<List<AttributeKvEntry>> latest = ctx.getAttributesService().find(ctx.getTenantId(), entityId, scope, keys);
81 return Futures.transform(latest, l -> { 81 return Futures.transform(latest, l -> {
82 l.forEach(r -> { 82 l.forEach(r -> {
83 if (r.getValue() != null) { 83 if (r.getValue() != null) {
@@ -94,7 +94,7 @@ public abstract class TbAbstractGetAttributesNode<C extends TbGetAttributesNodeC @@ -94,7 +94,7 @@ public abstract class TbAbstractGetAttributesNode<C extends TbGetAttributesNodeC
94 if (CollectionUtils.isEmpty(keys)) { 94 if (CollectionUtils.isEmpty(keys)) {
95 return Futures.immediateFuture(null); 95 return Futures.immediateFuture(null);
96 } 96 }
97 - ListenableFuture<List<TsKvEntry>> latest = ctx.getTimeseriesService().findLatest(entityId, keys); 97 + ListenableFuture<List<TsKvEntry>> latest = ctx.getTimeseriesService().findLatest(ctx.getTenantId(), entityId, keys);
98 return Futures.transform(latest, l -> { 98 return Futures.transform(latest, l -> {
99 l.forEach(r -> { 99 l.forEach(r -> {
100 if (r.getValue() != null) { 100 if (r.getValue() != null) {
@@ -71,13 +71,13 @@ public abstract class TbEntityGetAttrNode<T extends EntityId> implements TbNode @@ -71,13 +71,13 @@ public abstract class TbEntityGetAttrNode<T extends EntityId> implements TbNode
71 } 71 }
72 72
73 private ListenableFuture<List<KvEntry>> getAttributesAsync(TbContext ctx, EntityId entityId) { 73 private ListenableFuture<List<KvEntry>> getAttributesAsync(TbContext ctx, EntityId entityId) {
74 - ListenableFuture<List<AttributeKvEntry>> latest = ctx.getAttributesService().find(entityId, SERVER_SCOPE, config.getAttrMapping().keySet()); 74 + ListenableFuture<List<AttributeKvEntry>> latest = ctx.getAttributesService().find(ctx.getTenantId(), entityId, SERVER_SCOPE, config.getAttrMapping().keySet());
75 return Futures.transform(latest, l -> 75 return Futures.transform(latest, l ->
76 l.stream().map(i -> (KvEntry) i).collect(Collectors.toList())); 76 l.stream().map(i -> (KvEntry) i).collect(Collectors.toList()));
77 } 77 }
78 78
79 private ListenableFuture<List<KvEntry>> getLatestTelemetry(TbContext ctx, EntityId entityId) { 79 private ListenableFuture<List<KvEntry>> getLatestTelemetry(TbContext ctx, EntityId entityId) {
80 - ListenableFuture<List<TsKvEntry>> latest = ctx.getTimeseriesService().findLatest(entityId, config.getAttrMapping().keySet()); 80 + ListenableFuture<List<TsKvEntry>> latest = ctx.getTimeseriesService().findLatest(ctx.getTenantId(), entityId, config.getAttrMapping().keySet());
81 return Futures.transform(latest, l -> 81 return Futures.transform(latest, l ->
82 l.stream().map(i -> (KvEntry) i).collect(Collectors.toList())); 82 l.stream().map(i -> (KvEntry) i).collect(Collectors.toList()));
83 } 83 }
@@ -83,7 +83,7 @@ public class TbGetTelemetryNode implements TbNode { @@ -83,7 +83,7 @@ public class TbGetTelemetryNode implements TbNode {
83 } else { 83 } else {
84 try { 84 try {
85 List<ReadTsKvQuery> queries = buildQueries(); 85 List<ReadTsKvQuery> queries = buildQueries();
86 - ListenableFuture<List<TsKvEntry>> list = ctx.getTimeseriesService().findAll(msg.getOriginator(), queries); 86 + ListenableFuture<List<TsKvEntry>> list = ctx.getTimeseriesService().findAll(ctx.getTenantId(), msg.getOriginator(), queries);
87 DonAsynchron.withCallback(list, data -> { 87 DonAsynchron.withCallback(list, data -> {
88 process(data, msg); 88 process(data, msg);
89 TbMsg newMsg = ctx.newMsg(msg.getType(), msg.getOriginator(), msg.getMetaData(), msg.getData()); 89 TbMsg newMsg = ctx.newMsg(msg.getType(), msg.getOriginator(), msg.getMetaData(), msg.getData());
@@ -64,7 +64,7 @@ public class TbMsgAttributesNode implements TbNode { @@ -64,7 +64,7 @@ public class TbMsgAttributesNode implements TbNode {
64 64
65 String src = msg.getData(); 65 String src = msg.getData();
66 Set<AttributeKvEntry> attributes = JsonConverter.convertToAttributes(new JsonParser().parse(src)); 66 Set<AttributeKvEntry> attributes = JsonConverter.convertToAttributes(new JsonParser().parse(src));
67 - ctx.getTelemetryService().saveAndNotify(msg.getOriginator(), config.getScope(), new ArrayList<>(attributes), new TelemetryNodeCallback(ctx, msg)); 67 + ctx.getTelemetryService().saveAndNotify(ctx.getTenantId(), msg.getOriginator(), config.getScope(), new ArrayList<>(attributes), new TelemetryNodeCallback(ctx, msg));
68 if (msg.getOriginator().getEntityType() == EntityType.DEVICE && DataConstants.SHARED_SCOPE.equals(config.getScope())) { 68 if (msg.getOriginator().getEntityType() == EntityType.DEVICE && DataConstants.SHARED_SCOPE.equals(config.getScope())) {
69 ctx.getTelemetryService().onSharedAttributesUpdate(ctx.getTenantId(), new DeviceId(msg.getOriginator().getId()), attributes); 69 ctx.getTelemetryService().onSharedAttributesUpdate(ctx.getTenantId(), new DeviceId(msg.getOriginator().getId()), attributes);
70 } 70 }
@@ -86,7 +86,7 @@ public class TbMsgTimeseriesNode implements TbNode { @@ -86,7 +86,7 @@ public class TbMsgTimeseriesNode implements TbNode {
86 } 86 }
87 String ttlValue = msg.getMetaData().getValue("TTL"); 87 String ttlValue = msg.getMetaData().getValue("TTL");
88 long ttl = !StringUtils.isEmpty(ttlValue) ? Long.valueOf(ttlValue) : config.getDefaultTTL(); 88 long ttl = !StringUtils.isEmpty(ttlValue) ? Long.valueOf(ttlValue) : config.getDefaultTTL();
89 - ctx.getTelemetryService().saveAndNotify(msg.getOriginator(), tsKvEntryList, ttl, new TelemetryNodeCallback(ctx, msg)); 89 + ctx.getTelemetryService().saveAndNotify(ctx.getTenantId(), msg.getOriginator(), tsKvEntryList, ttl, new TelemetryNodeCallback(ctx, msg));
90 } 90 }
91 91
92 @Override 92 @Override
@@ -32,11 +32,11 @@ public class EntitiesCustomerIdAsyncLoader { @@ -32,11 +32,11 @@ public class EntitiesCustomerIdAsyncLoader {
32 case CUSTOMER: 32 case CUSTOMER:
33 return Futures.immediateFuture((CustomerId) original); 33 return Futures.immediateFuture((CustomerId) original);
34 case USER: 34 case USER:
35 - return getCustomerAsync(ctx.getUserService().findUserByIdAsync((UserId) original)); 35 + return getCustomerAsync(ctx.getUserService().findUserByIdAsync(ctx.getTenantId(), (UserId) original));
36 case ASSET: 36 case ASSET:
37 - return getCustomerAsync(ctx.getAssetService().findAssetByIdAsync((AssetId) original)); 37 + return getCustomerAsync(ctx.getAssetService().findAssetByIdAsync(ctx.getTenantId(), (AssetId) original));
38 case DEVICE: 38 case DEVICE:
39 - return getCustomerAsync(ctx.getDeviceService().findDeviceByIdAsync((DeviceId) original)); 39 + return getCustomerAsync(ctx.getDeviceService().findDeviceByIdAsync(ctx.getTenantId(), (DeviceId) original));
40 default: 40 default:
41 return Futures.immediateFailedFuture(new TbNodeException("Unexpected original EntityType " + original)); 41 return Futures.immediateFailedFuture(new TbNodeException("Unexpected original EntityType " + original));
42 } 42 }
@@ -37,26 +37,26 @@ public class EntitiesFieldsAsyncLoader { @@ -37,26 +37,26 @@ public class EntitiesFieldsAsyncLoader {
37 public static ListenableFuture<EntityFieldsData> findAsync(TbContext ctx, EntityId original) { 37 public static ListenableFuture<EntityFieldsData> findAsync(TbContext ctx, EntityId original) {
38 switch (original.getEntityType()) { 38 switch (original.getEntityType()) {
39 case TENANT: 39 case TENANT:
40 - return getAsync(ctx.getTenantService().findTenantByIdAsync((TenantId) original),  
41 - t -> new EntityFieldsData(t)); 40 + return getAsync(ctx.getTenantService().findTenantByIdAsync(ctx.getTenantId(), (TenantId) original),
  41 + EntityFieldsData::new);
42 case CUSTOMER: 42 case CUSTOMER:
43 - return getAsync(ctx.getCustomerService().findCustomerByIdAsync((CustomerId) original),  
44 - t -> new EntityFieldsData(t)); 43 + return getAsync(ctx.getCustomerService().findCustomerByIdAsync(ctx.getTenantId(), (CustomerId) original),
  44 + EntityFieldsData::new);
45 case USER: 45 case USER:
46 - return getAsync(ctx.getUserService().findUserByIdAsync((UserId) original),  
47 - t -> new EntityFieldsData(t)); 46 + return getAsync(ctx.getUserService().findUserByIdAsync(ctx.getTenantId(), (UserId) original),
  47 + EntityFieldsData::new);
48 case ASSET: 48 case ASSET:
49 - return getAsync(ctx.getAssetService().findAssetByIdAsync((AssetId) original),  
50 - t -> new EntityFieldsData(t)); 49 + return getAsync(ctx.getAssetService().findAssetByIdAsync(ctx.getTenantId(), (AssetId) original),
  50 + EntityFieldsData::new);
51 case DEVICE: 51 case DEVICE:
52 - return getAsync(ctx.getDeviceService().findDeviceByIdAsync((DeviceId) original),  
53 - t -> new EntityFieldsData(t)); 52 + return getAsync(ctx.getDeviceService().findDeviceByIdAsync(ctx.getTenantId(), (DeviceId) original),
  53 + EntityFieldsData::new);
54 case ALARM: 54 case ALARM:
55 - return getAsync(ctx.getAlarmService().findAlarmByIdAsync((AlarmId) original),  
56 - t -> new EntityFieldsData(t)); 55 + return getAsync(ctx.getAlarmService().findAlarmByIdAsync(ctx.getTenantId(), (AlarmId) original),
  56 + EntityFieldsData::new);
57 case RULE_CHAIN: 57 case RULE_CHAIN:
58 - return getAsync(ctx.getRuleChainService().findRuleChainByIdAsync((RuleChainId) original),  
59 - t -> new EntityFieldsData(t)); 58 + return getAsync(ctx.getRuleChainService().findRuleChainByIdAsync(ctx.getTenantId(), (RuleChainId) original),
  59 + EntityFieldsData::new);
60 default: 60 default:
61 return Futures.immediateFailedFuture(new TbNodeException("Unexpected original EntityType " + original)); 61 return Futures.immediateFailedFuture(new TbNodeException("Unexpected original EntityType " + original));
62 } 62 }
@@ -37,7 +37,7 @@ public class EntitiesRelatedDeviceIdAsyncLoader { @@ -37,7 +37,7 @@ public class EntitiesRelatedDeviceIdAsyncLoader {
37 DeviceService deviceService = ctx.getDeviceService(); 37 DeviceService deviceService = ctx.getDeviceService();
38 DeviceSearchQuery query = buildQuery(originator, deviceRelationsQuery); 38 DeviceSearchQuery query = buildQuery(originator, deviceRelationsQuery);
39 39
40 - ListenableFuture<List<Device>> asyncDevices = deviceService.findDevicesByQuery(query); 40 + ListenableFuture<List<Device>> asyncDevices = deviceService.findDevicesByQuery(ctx.getTenantId(), query);
41 41
42 return Futures.transformAsync(asyncDevices, d -> CollectionUtils.isNotEmpty(d) ? Futures.immediateFuture(d.get(0).getId()) 42 return Futures.transformAsync(asyncDevices, d -> CollectionUtils.isNotEmpty(d) ? Futures.immediateFuture(d.get(0).getId())
43 : Futures.immediateFuture(null)); 43 : Futures.immediateFuture(null));
@@ -36,7 +36,7 @@ public class EntitiesRelatedEntityIdAsyncLoader { @@ -36,7 +36,7 @@ public class EntitiesRelatedEntityIdAsyncLoader {
36 RelationsQuery relationsQuery) { 36 RelationsQuery relationsQuery) {
37 RelationService relationService = ctx.getRelationService(); 37 RelationService relationService = ctx.getRelationService();
38 EntityRelationsQuery query = buildQuery(originator, relationsQuery); 38 EntityRelationsQuery query = buildQuery(originator, relationsQuery);
39 - ListenableFuture<List<EntityRelation>> asyncRelation = relationService.findByQuery(query); 39 + ListenableFuture<List<EntityRelation>> asyncRelation = relationService.findByQuery(ctx.getTenantId(), query);
40 if (relationsQuery.getDirection() == EntitySearchDirection.FROM) { 40 if (relationsQuery.getDirection() == EntitySearchDirection.FROM) {
41 return Futures.transformAsync(asyncRelation, r -> CollectionUtils.isNotEmpty(r) ? Futures.immediateFuture(r.get(0).getTo()) 41 return Futures.transformAsync(asyncRelation, r -> CollectionUtils.isNotEmpty(r) ? Futures.immediateFuture(r.get(0).getTo())
42 : Futures.immediateFuture(null)); 42 : Futures.immediateFuture(null));
@@ -32,17 +32,17 @@ public class EntitiesTenantIdAsyncLoader { @@ -32,17 +32,17 @@ public class EntitiesTenantIdAsyncLoader {
32 case TENANT: 32 case TENANT:
33 return Futures.immediateFuture((TenantId) original); 33 return Futures.immediateFuture((TenantId) original);
34 case CUSTOMER: 34 case CUSTOMER:
35 - return getTenantAsync(ctx.getCustomerService().findCustomerByIdAsync((CustomerId) original)); 35 + return getTenantAsync(ctx.getCustomerService().findCustomerByIdAsync(ctx.getTenantId(), (CustomerId) original));
36 case USER: 36 case USER:
37 - return getTenantAsync(ctx.getUserService().findUserByIdAsync((UserId) original)); 37 + return getTenantAsync(ctx.getUserService().findUserByIdAsync(ctx.getTenantId(), (UserId) original));
38 case ASSET: 38 case ASSET:
39 - return getTenantAsync(ctx.getAssetService().findAssetByIdAsync((AssetId) original)); 39 + return getTenantAsync(ctx.getAssetService().findAssetByIdAsync(ctx.getTenantId(), (AssetId) original));
40 case DEVICE: 40 case DEVICE:
41 - return getTenantAsync(ctx.getDeviceService().findDeviceByIdAsync((DeviceId) original)); 41 + return getTenantAsync(ctx.getDeviceService().findDeviceByIdAsync(ctx.getTenantId(), (DeviceId) original));
42 case ALARM: 42 case ALARM:
43 - return getTenantAsync(ctx.getAlarmService().findAlarmByIdAsync((AlarmId) original)); 43 + return getTenantAsync(ctx.getAlarmService().findAlarmByIdAsync(ctx.getTenantId(), (AlarmId) original));
44 case RULE_CHAIN: 44 case RULE_CHAIN:
45 - return getTenantAsync(ctx.getRuleChainService().findRuleChainByIdAsync((RuleChainId) original)); 45 + return getTenantAsync(ctx.getRuleChainService().findRuleChainByIdAsync(ctx.getTenantId(), (RuleChainId) original));
46 default: 46 default:
47 return Futures.immediateFailedFuture(new TbNodeException("Unexpected original EntityType " + original)); 47 return Futures.immediateFailedFuture(new TbNodeException("Unexpected original EntityType " + original));
48 } 48 }
@@ -269,7 +269,7 @@ public class TbAlarmNodeTest { @@ -269,7 +269,7 @@ public class TbAlarmNodeTest {
269 269
270 // when(detailsJs.executeJson(msg)).thenReturn(null); 270 // when(detailsJs.executeJson(msg)).thenReturn(null);
271 when(alarmService.findLatestByOriginatorAndType(tenantId, originator, "SomeType")).thenReturn(Futures.immediateFuture(activeAlarm)); 271 when(alarmService.findLatestByOriginatorAndType(tenantId, originator, "SomeType")).thenReturn(Futures.immediateFuture(activeAlarm));
272 - when(alarmService.clearAlarm(eq(activeAlarm.getId()), org.mockito.Mockito.any(JsonNode.class), anyLong())).thenReturn(Futures.immediateFuture(true)); 272 + when(alarmService.clearAlarm(eq(activeAlarm.getTenantId()), eq(activeAlarm.getId()), org.mockito.Mockito.any(JsonNode.class), anyLong())).thenReturn(Futures.immediateFuture(true));
273 // doAnswer((Answer<Alarm>) invocationOnMock -> (Alarm) (invocationOnMock.getArguments())[0]).when(alarmService).createOrUpdateAlarm(activeAlarm); 273 // doAnswer((Answer<Alarm>) invocationOnMock -> (Alarm) (invocationOnMock.getArguments())[0]).when(alarmService).createOrUpdateAlarm(activeAlarm);
274 274
275 node.onMsg(ctx, msg); 275 node.onMsg(ctx, msg);
@@ -48,6 +48,8 @@ import java.util.Map; @@ -48,6 +48,8 @@ import java.util.Map;
48 48
49 import static org.junit.Assert.assertEquals; 49 import static org.junit.Assert.assertEquals;
50 import static org.junit.Assert.assertTrue; 50 import static org.junit.Assert.assertTrue;
  51 +import static org.mockito.Matchers.any;
  52 +import static org.mockito.Matchers.eq;
51 import static org.mockito.Matchers.same; 53 import static org.mockito.Matchers.same;
52 import static org.mockito.Mockito.verify; 54 import static org.mockito.Mockito.verify;
53 import static org.mockito.Mockito.when; 55 import static org.mockito.Mockito.when;
@@ -103,10 +105,10 @@ public class TbGetCustomerAttributeNodeTest { @@ -103,10 +105,10 @@ public class TbGetCustomerAttributeNodeTest {
103 msg = new TbMsg(UUIDs.timeBased(), "USER", userId, new TbMsgMetaData(), "{}", ruleChainId, ruleNodeId, 0L); 105 msg = new TbMsg(UUIDs.timeBased(), "USER", userId, new TbMsgMetaData(), "{}", ruleChainId, ruleNodeId, 0L);
104 106
105 when(ctx.getUserService()).thenReturn(userService); 107 when(ctx.getUserService()).thenReturn(userService);
106 - when(userService.findUserByIdAsync(userId)).thenReturn(Futures.immediateFuture(user)); 108 + when(userService.findUserByIdAsync(any(), eq(userId))).thenReturn(Futures.immediateFuture(user));
107 109
108 when(ctx.getAttributesService()).thenReturn(attributesService); 110 when(ctx.getAttributesService()).thenReturn(attributesService);
109 - when(attributesService.find(customerId, SERVER_SCOPE, Collections.singleton("temperature"))) 111 + when(attributesService.find(any(), eq(customerId), eq(SERVER_SCOPE), eq(Collections.singleton("temperature"))))
110 .thenThrow(new IllegalStateException("something wrong")); 112 .thenThrow(new IllegalStateException("something wrong"));
111 113
112 node.onMsg(ctx, msg); 114 node.onMsg(ctx, msg);
@@ -128,10 +130,10 @@ public class TbGetCustomerAttributeNodeTest { @@ -128,10 +130,10 @@ public class TbGetCustomerAttributeNodeTest {
128 msg = new TbMsg(UUIDs.timeBased(), "USER", userId, new TbMsgMetaData(), "{}", ruleChainId, ruleNodeId, 0L); 130 msg = new TbMsg(UUIDs.timeBased(), "USER", userId, new TbMsgMetaData(), "{}", ruleChainId, ruleNodeId, 0L);
129 131
130 when(ctx.getUserService()).thenReturn(userService); 132 when(ctx.getUserService()).thenReturn(userService);
131 - when(userService.findUserByIdAsync(userId)).thenReturn(Futures.immediateFuture(user)); 133 + when(userService.findUserByIdAsync(any(), eq(userId))).thenReturn(Futures.immediateFuture(user));
132 134
133 when(ctx.getAttributesService()).thenReturn(attributesService); 135 when(ctx.getAttributesService()).thenReturn(attributesService);
134 - when(attributesService.find(customerId, SERVER_SCOPE, Collections.singleton("temperature"))) 136 + when(attributesService.find(any(), eq(customerId), eq(SERVER_SCOPE), eq(Collections.singleton("temperature"))))
135 .thenReturn(Futures.immediateFailedFuture(new IllegalStateException("something wrong"))); 137 .thenReturn(Futures.immediateFailedFuture(new IllegalStateException("something wrong")));
136 138
137 node.onMsg(ctx, msg); 139 node.onMsg(ctx, msg);
@@ -153,7 +155,7 @@ public class TbGetCustomerAttributeNodeTest { @@ -153,7 +155,7 @@ public class TbGetCustomerAttributeNodeTest {
153 msg = new TbMsg(UUIDs.timeBased(), "USER", userId, new TbMsgMetaData(), "{}", ruleChainId, ruleNodeId, 0L); 155 msg = new TbMsg(UUIDs.timeBased(), "USER", userId, new TbMsgMetaData(), "{}", ruleChainId, ruleNodeId, 0L);
154 156
155 when(ctx.getUserService()).thenReturn(userService); 157 when(ctx.getUserService()).thenReturn(userService);
156 - when(userService.findUserByIdAsync(userId)).thenReturn(Futures.immediateFuture(null)); 158 + when(userService.findUserByIdAsync(any(), eq(userId))).thenReturn(Futures.immediateFuture(null));
157 159
158 160
159 node.onMsg(ctx, msg); 161 node.onMsg(ctx, msg);
@@ -178,7 +180,7 @@ public class TbGetCustomerAttributeNodeTest { @@ -178,7 +180,7 @@ public class TbGetCustomerAttributeNodeTest {
178 msg = new TbMsg(UUIDs.timeBased(), "USER", userId, new TbMsgMetaData(), "{}", ruleChainId, ruleNodeId, 0L); 180 msg = new TbMsg(UUIDs.timeBased(), "USER", userId, new TbMsgMetaData(), "{}", ruleChainId, ruleNodeId, 0L);
179 181
180 when(ctx.getUserService()).thenReturn(userService); 182 when(ctx.getUserService()).thenReturn(userService);
181 - when(userService.findUserByIdAsync(userId)).thenReturn(Futures.immediateFuture(user)); 183 + when(userService.findUserByIdAsync(any(), eq(userId))).thenReturn(Futures.immediateFuture(user));
182 184
183 entityAttributeFetched(customerId); 185 entityAttributeFetched(customerId);
184 } 186 }
@@ -193,7 +195,7 @@ public class TbGetCustomerAttributeNodeTest { @@ -193,7 +195,7 @@ public class TbGetCustomerAttributeNodeTest {
193 msg = new TbMsg(UUIDs.timeBased(), "USER", assetId, new TbMsgMetaData(), "{}", ruleChainId, ruleNodeId, 0L); 195 msg = new TbMsg(UUIDs.timeBased(), "USER", assetId, new TbMsgMetaData(), "{}", ruleChainId, ruleNodeId, 0L);
194 196
195 when(ctx.getAssetService()).thenReturn(assetService); 197 when(ctx.getAssetService()).thenReturn(assetService);
196 - when(assetService.findAssetByIdAsync(assetId)).thenReturn(Futures.immediateFuture(asset)); 198 + when(assetService.findAssetByIdAsync(any(), eq(assetId))).thenReturn(Futures.immediateFuture(asset));
197 199
198 entityAttributeFetched(customerId); 200 entityAttributeFetched(customerId);
199 } 201 }
@@ -208,7 +210,7 @@ public class TbGetCustomerAttributeNodeTest { @@ -208,7 +210,7 @@ public class TbGetCustomerAttributeNodeTest {
208 msg = new TbMsg(UUIDs.timeBased(), "USER", deviceId, new TbMsgMetaData(), "{}", ruleChainId, ruleNodeId, 0L); 210 msg = new TbMsg(UUIDs.timeBased(), "USER", deviceId, new TbMsgMetaData(), "{}", ruleChainId, ruleNodeId, 0L);
209 211
210 when(ctx.getDeviceService()).thenReturn(deviceService); 212 when(ctx.getDeviceService()).thenReturn(deviceService);
211 - when(deviceService.findDeviceByIdAsync(deviceId)).thenReturn(Futures.immediateFuture(device)); 213 + when(deviceService.findDeviceByIdAsync(any(), eq(deviceId))).thenReturn(Futures.immediateFuture(device));
212 214
213 entityAttributeFetched(customerId); 215 entityAttributeFetched(customerId);
214 } 216 }
@@ -235,12 +237,12 @@ public class TbGetCustomerAttributeNodeTest { @@ -235,12 +237,12 @@ public class TbGetCustomerAttributeNodeTest {
235 msg = new TbMsg(UUIDs.timeBased(), "USER", deviceId, new TbMsgMetaData(), "{}", ruleChainId, ruleNodeId, 0L); 237 msg = new TbMsg(UUIDs.timeBased(), "USER", deviceId, new TbMsgMetaData(), "{}", ruleChainId, ruleNodeId, 0L);
236 238
237 when(ctx.getDeviceService()).thenReturn(deviceService); 239 when(ctx.getDeviceService()).thenReturn(deviceService);
238 - when(deviceService.findDeviceByIdAsync(deviceId)).thenReturn(Futures.immediateFuture(device)); 240 + when(deviceService.findDeviceByIdAsync(any(), eq(deviceId))).thenReturn(Futures.immediateFuture(device));
239 241
240 List<TsKvEntry> timeseries = Lists.newArrayList(new BasicTsKvEntry(1L, new StringDataEntry("temperature", "highest"))); 242 List<TsKvEntry> timeseries = Lists.newArrayList(new BasicTsKvEntry(1L, new StringDataEntry("temperature", "highest")));
241 243
242 when(ctx.getTimeseriesService()).thenReturn(timeseriesService); 244 when(ctx.getTimeseriesService()).thenReturn(timeseriesService);
243 - when(timeseriesService.findLatest(customerId, Collections.singleton("temperature"))) 245 + when(timeseriesService.findLatest(any(), eq(customerId), eq(Collections.singleton("temperature"))))
244 .thenReturn(Futures.immediateFuture(timeseries)); 246 .thenReturn(Futures.immediateFuture(timeseries));
245 247
246 node.onMsg(ctx, msg); 248 node.onMsg(ctx, msg);
@@ -252,7 +254,7 @@ public class TbGetCustomerAttributeNodeTest { @@ -252,7 +254,7 @@ public class TbGetCustomerAttributeNodeTest {
252 List<AttributeKvEntry> attributes = Lists.newArrayList(new BaseAttributeKvEntry(new StringDataEntry("temperature", "high"), 1L)); 254 List<AttributeKvEntry> attributes = Lists.newArrayList(new BaseAttributeKvEntry(new StringDataEntry("temperature", "high"), 1L));
253 255
254 when(ctx.getAttributesService()).thenReturn(attributesService); 256 when(ctx.getAttributesService()).thenReturn(attributesService);
255 - when(attributesService.find(customerId, SERVER_SCOPE, Collections.singleton("temperature"))) 257 + when(attributesService.find(any(), eq(customerId), eq(SERVER_SCOPE), eq(Collections.singleton("temperature"))))
256 .thenReturn(Futures.immediateFuture(attributes)); 258 .thenReturn(Futures.immediateFuture(attributes));
257 259
258 node.onMsg(ctx, msg); 260 node.onMsg(ctx, msg);
@@ -42,6 +42,8 @@ import org.thingsboard.server.dao.asset.AssetService; @@ -42,6 +42,8 @@ import org.thingsboard.server.dao.asset.AssetService;
42 import java.util.concurrent.Callable; 42 import java.util.concurrent.Callable;
43 43
44 import static org.junit.Assert.assertEquals; 44 import static org.junit.Assert.assertEquals;
  45 +import static org.mockito.Matchers.any;
  46 +import static org.mockito.Matchers.eq;
45 import static org.mockito.Matchers.same; 47 import static org.mockito.Matchers.same;
46 import static org.mockito.Mockito.verify; 48 import static org.mockito.Mockito.verify;
47 import static org.mockito.Mockito.when; 49 import static org.mockito.Mockito.when;
@@ -92,7 +94,7 @@ public class TbChangeOriginatorNodeTest { @@ -92,7 +94,7 @@ public class TbChangeOriginatorNodeTest {
92 TbMsg msg = new TbMsg(UUIDs.timeBased(), "ASSET", assetId, new TbMsgMetaData(), "{}", ruleChainId, ruleNodeId, 0L); 94 TbMsg msg = new TbMsg(UUIDs.timeBased(), "ASSET", assetId, new TbMsgMetaData(), "{}", ruleChainId, ruleNodeId, 0L);
93 95
94 when(ctx.getAssetService()).thenReturn(assetService); 96 when(ctx.getAssetService()).thenReturn(assetService);
95 - when(assetService.findAssetByIdAsync(assetId)).thenReturn(Futures.immediateFuture(asset)); 97 + when(assetService.findAssetByIdAsync(any(),eq( assetId))).thenReturn(Futures.immediateFuture(asset));
96 98
97 node.onMsg(ctx, msg); 99 node.onMsg(ctx, msg);
98 100
@@ -120,7 +122,7 @@ public class TbChangeOriginatorNodeTest { @@ -120,7 +122,7 @@ public class TbChangeOriginatorNodeTest {
120 TbMsg msg = new TbMsg(UUIDs.timeBased(), "ASSET", assetId, new TbMsgMetaData(), "{}", ruleChainId, ruleNodeId, 0L); 122 TbMsg msg = new TbMsg(UUIDs.timeBased(), "ASSET", assetId, new TbMsgMetaData(), "{}", ruleChainId, ruleNodeId, 0L);
121 123
122 when(ctx.getAssetService()).thenReturn(assetService); 124 when(ctx.getAssetService()).thenReturn(assetService);
123 - when(assetService.findAssetByIdAsync(assetId)).thenReturn(Futures.immediateFuture(asset)); 125 + when(assetService.findAssetByIdAsync(any(), eq(assetId))).thenReturn(Futures.immediateFuture(asset));
124 126
125 node.onMsg(ctx, msg); 127 node.onMsg(ctx, msg);
126 ArgumentCaptor<TbMsg> msgCaptor = ArgumentCaptor.forClass(TbMsg.class); 128 ArgumentCaptor<TbMsg> msgCaptor = ArgumentCaptor.forClass(TbMsg.class);
@@ -147,7 +149,7 @@ public class TbChangeOriginatorNodeTest { @@ -147,7 +149,7 @@ public class TbChangeOriginatorNodeTest {
147 TbMsg msg = new TbMsg(UUIDs.timeBased(), "ASSET", assetId, new TbMsgMetaData(), "{}", ruleChainId, ruleNodeId, 0L); 149 TbMsg msg = new TbMsg(UUIDs.timeBased(), "ASSET", assetId, new TbMsgMetaData(), "{}", ruleChainId, ruleNodeId, 0L);
148 150
149 when(ctx.getAssetService()).thenReturn(assetService); 151 when(ctx.getAssetService()).thenReturn(assetService);
150 - when(assetService.findAssetByIdAsync(assetId)).thenReturn(Futures.immediateFuture(null)); 152 + when(assetService.findAssetByIdAsync(any(), eq(assetId))).thenReturn(Futures.immediateFuture(null));
151 153
152 node.onMsg(ctx, msg); 154 node.onMsg(ctx, msg);
153 verify(ctx).tellNext(same(msg), same(FAILURE)); 155 verify(ctx).tellNext(same(msg), same(FAILURE));