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