Commit 80e8b2efaf5b6e454e676f4de9d322a00ca31896

Authored by Unknown
2 parents 4597e5d4 377b53f8

Merge remote-tracking branch 'origin/master'

Showing 88 changed files with 948 additions and 1619 deletions

Too many changes to show.

To preserve performance only 88 of 188 files are displayed.

@@ -32,6 +32,8 @@ import org.thingsboard.server.actors.shared.rule.SystemRuleManager; @@ -32,6 +32,8 @@ import org.thingsboard.server.actors.shared.rule.SystemRuleManager;
32 import org.thingsboard.server.actors.tenant.RuleChainDeviceMsg; 32 import org.thingsboard.server.actors.tenant.RuleChainDeviceMsg;
33 import org.thingsboard.server.actors.tenant.TenantActor; 33 import org.thingsboard.server.actors.tenant.TenantActor;
34 import org.thingsboard.server.common.data.Tenant; 34 import org.thingsboard.server.common.data.Tenant;
  35 +import org.thingsboard.server.common.data.id.PluginId;
  36 +import org.thingsboard.server.common.data.id.RuleId;
35 import org.thingsboard.server.common.data.id.TenantId; 37 import org.thingsboard.server.common.data.id.TenantId;
36 import org.thingsboard.server.common.data.page.PageDataIterable; 38 import org.thingsboard.server.common.data.page.PageDataIterable;
37 import org.thingsboard.server.common.msg.cluster.ClusterEventMsg; 39 import org.thingsboard.server.common.msg.cluster.ClusterEventMsg;
@@ -149,14 +151,16 @@ public class AppActor extends ContextAwareActor { @@ -149,14 +151,16 @@ public class AppActor extends ContextAwareActor {
149 private void onComponentLifecycleMsg(ComponentLifecycleMsg msg) { 151 private void onComponentLifecycleMsg(ComponentLifecycleMsg msg) {
150 ActorRef target = null; 152 ActorRef target = null;
151 if (SYSTEM_TENANT.equals(msg.getTenantId())) { 153 if (SYSTEM_TENANT.equals(msg.getTenantId())) {
152 - if (msg.getPluginId().isPresent()) {  
153 - target = pluginManager.getOrCreatePluginActor(this.context(), msg.getPluginId().get());  
154 - } else if (msg.getRuleId().isPresent()) {  
155 - Optional<ActorRef> ref = ruleManager.update(this.context(), msg.getRuleId().get(), msg.getEvent()); 154 + Optional<PluginId> pluginId = msg.getPluginId();
  155 + Optional<RuleId> ruleId = msg.getRuleId();
  156 + if (pluginId.isPresent()) {
  157 + target = pluginManager.getOrCreatePluginActor(this.context(), pluginId.get());
  158 + } else if (ruleId.isPresent()) {
  159 + Optional<ActorRef> ref = ruleManager.update(this.context(), ruleId.get(), msg.getEvent());
156 if (ref.isPresent()) { 160 if (ref.isPresent()) {
157 target = ref.get(); 161 target = ref.get();
158 } else { 162 } else {
159 - logger.debug("Failed to find actor for rule: [{}]", msg.getRuleId()); 163 + logger.debug("Failed to find actor for rule: [{}]", ruleId);
160 return; 164 return;
161 } 165 }
162 } 166 }
@@ -272,130 +272,150 @@ public final class PluginProcessingContext implements PluginContext { @@ -272,130 +272,150 @@ public final class PluginProcessingContext implements PluginContext {
272 private void validate(EntityId entityId, ValidationCallback callback) { 272 private void validate(EntityId entityId, ValidationCallback callback) {
273 if (securityCtx.isPresent()) { 273 if (securityCtx.isPresent()) {
274 final PluginApiCallSecurityContext ctx = securityCtx.get(); 274 final PluginApiCallSecurityContext ctx = securityCtx.get();
275 - if (ctx.isTenantAdmin() || ctx.isCustomerUser() || ctx.isSystemAdmin()) {  
276 - switch (entityId.getEntityType()) {  
277 - case DEVICE:  
278 - if (ctx.isSystemAdmin()) {  
279 - callback.onSuccess(this, Boolean.FALSE);  
280 - } else {  
281 - ListenableFuture<Device> deviceFuture = pluginCtx.deviceService.findDeviceByIdAsync(new DeviceId(entityId.getId()));  
282 - Futures.addCallback(deviceFuture, getCallback(callback, device -> {  
283 - if (device == null) {  
284 - return Boolean.FALSE;  
285 - } else {  
286 - if (!device.getTenantId().equals(ctx.getTenantId())) {  
287 - return Boolean.FALSE;  
288 - } else if (ctx.isCustomerUser() && !device.getCustomerId().equals(ctx.getCustomerId())) {  
289 - return Boolean.FALSE;  
290 - } else {  
291 - return Boolean.TRUE;  
292 - }  
293 - }  
294 - }));  
295 - }  
296 - return;  
297 - case ASSET:  
298 - if (ctx.isSystemAdmin()) {  
299 - callback.onSuccess(this, Boolean.FALSE);  
300 - } else {  
301 - ListenableFuture<Asset> assetFuture = pluginCtx.assetService.findAssetByIdAsync(new AssetId(entityId.getId()));  
302 - Futures.addCallback(assetFuture, getCallback(callback, asset -> {  
303 - if (asset == null) {  
304 - return Boolean.FALSE;  
305 - } else {  
306 - if (!asset.getTenantId().equals(ctx.getTenantId())) {  
307 - return Boolean.FALSE;  
308 - } else if (ctx.isCustomerUser() && !asset.getCustomerId().equals(ctx.getCustomerId())) {  
309 - return Boolean.FALSE;  
310 - } else {  
311 - return Boolean.TRUE;  
312 - }  
313 - }  
314 - }));  
315 - }  
316 - return;  
317 - case RULE:  
318 - if (ctx.isCustomerUser()) {  
319 - callback.onSuccess(this, Boolean.FALSE);  
320 - } else {  
321 - ListenableFuture<RuleMetaData> ruleFuture = pluginCtx.ruleService.findRuleByIdAsync(new RuleId(entityId.getId()));  
322 - Futures.addCallback(ruleFuture, getCallback(callback, rule -> {  
323 - if (rule == null) {  
324 - return Boolean.FALSE;  
325 - } else {  
326 - if (ctx.isTenantAdmin() && !rule.getTenantId().equals(ctx.getTenantId())) {  
327 - return Boolean.FALSE;  
328 - } else if (ctx.isSystemAdmin() && !rule.getTenantId().isNullUid()) {  
329 - return Boolean.FALSE;  
330 - } else {  
331 - return Boolean.TRUE;  
332 - }  
333 - }  
334 - }));  
335 - }  
336 - return;  
337 - case PLUGIN:  
338 - if (ctx.isCustomerUser()) {  
339 - callback.onSuccess(this, Boolean.FALSE);  
340 - } else {  
341 - ListenableFuture<PluginMetaData> pluginFuture = pluginCtx.pluginService.findPluginByIdAsync(new PluginId(entityId.getId()));  
342 - Futures.addCallback(pluginFuture, getCallback(callback, plugin -> {  
343 - if (plugin == null) {  
344 - return Boolean.FALSE;  
345 - } else {  
346 - if (ctx.isTenantAdmin() && !plugin.getTenantId().equals(ctx.getTenantId())) {  
347 - return Boolean.FALSE;  
348 - } else if (ctx.isSystemAdmin() && !plugin.getTenantId().isNullUid()) {  
349 - return Boolean.FALSE;  
350 - } else {  
351 - return Boolean.TRUE;  
352 - }  
353 - }  
354 - }));  
355 - }  
356 - return;  
357 - case CUSTOMER:  
358 - if (ctx.isSystemAdmin()) {  
359 - callback.onSuccess(this, Boolean.FALSE);  
360 - } else {  
361 - ListenableFuture<Customer> customerFuture = pluginCtx.customerService.findCustomerByIdAsync(new CustomerId(entityId.getId()));  
362 - Futures.addCallback(customerFuture, getCallback(callback, customer -> {  
363 - if (customer == null) {  
364 - return Boolean.FALSE;  
365 - } else {  
366 - if (!customer.getTenantId().equals(ctx.getTenantId())) {  
367 - return Boolean.FALSE;  
368 - } else if (ctx.isCustomerUser() && !customer.getId().equals(ctx.getCustomerId())) {  
369 - return Boolean.FALSE;  
370 - } else {  
371 - return Boolean.TRUE;  
372 - }  
373 - }  
374 - }));  
375 - }  
376 - return;  
377 - case TENANT:  
378 - if (ctx.isCustomerUser()) {  
379 - callback.onSuccess(this, Boolean.FALSE);  
380 - } else if (ctx.isSystemAdmin()) {  
381 - callback.onSuccess(this, Boolean.TRUE);  
382 - } else {  
383 - ListenableFuture<Tenant> tenantFuture = pluginCtx.tenantService.findTenantByIdAsync(new TenantId(entityId.getId()));  
384 - Futures.addCallback(tenantFuture, getCallback(callback, tenant -> tenant != null && tenant.getId().equals(ctx.getTenantId())));  
385 - }  
386 - return;  
387 - default:  
388 - //TODO: add support of other entities  
389 - throw new IllegalStateException("Not Implemented!");  
390 - }  
391 - } else {  
392 - callback.onSuccess(this, Boolean.FALSE); 275 + switch (entityId.getEntityType()) {
  276 + case DEVICE:
  277 + validateDevice(ctx, entityId, callback);
  278 + return;
  279 + case ASSET:
  280 + validateAsset(ctx, entityId, callback);
  281 + return;
  282 + case RULE:
  283 + validateRule(ctx, entityId, callback);
  284 + return;
  285 + case PLUGIN:
  286 + validatePlugin(ctx, entityId, callback);
  287 + return;
  288 + case CUSTOMER:
  289 + validateCustomer(ctx, entityId, callback);
  290 + return;
  291 + case TENANT:
  292 + validateTenant(ctx, entityId, callback);
  293 + return;
  294 + default:
  295 + //TODO: add support of other entities
  296 + throw new IllegalStateException("Not Implemented!");
393 } 297 }
394 } else { 298 } else {
395 callback.onSuccess(this, Boolean.TRUE); 299 callback.onSuccess(this, Boolean.TRUE);
396 } 300 }
397 } 301 }
398 302
  303 + private void validateDevice(final PluginApiCallSecurityContext ctx, EntityId entityId, ValidationCallback callback) {
  304 + if (ctx.isSystemAdmin()) {
  305 + callback.onSuccess(this, Boolean.FALSE);
  306 + } else {
  307 + ListenableFuture<Device> deviceFuture = pluginCtx.deviceService.findDeviceByIdAsync(new DeviceId(entityId.getId()));
  308 + Futures.addCallback(deviceFuture, getCallback(callback, device -> {
  309 + if (device == null) {
  310 + return Boolean.FALSE;
  311 + } else {
  312 + if (!device.getTenantId().equals(ctx.getTenantId())) {
  313 + return Boolean.FALSE;
  314 + } else if (ctx.isCustomerUser() && !device.getCustomerId().equals(ctx.getCustomerId())) {
  315 + return Boolean.FALSE;
  316 + } else {
  317 + return Boolean.TRUE;
  318 + }
  319 + }
  320 + }));
  321 + }
  322 + }
  323 +
  324 + private void validateAsset(final PluginApiCallSecurityContext ctx, EntityId entityId, ValidationCallback callback) {
  325 + if (ctx.isSystemAdmin()) {
  326 + callback.onSuccess(this, Boolean.FALSE);
  327 + } else {
  328 + ListenableFuture<Asset> assetFuture = pluginCtx.assetService.findAssetByIdAsync(new AssetId(entityId.getId()));
  329 + Futures.addCallback(assetFuture, getCallback(callback, asset -> {
  330 + if (asset == null) {
  331 + return Boolean.FALSE;
  332 + } else {
  333 + if (!asset.getTenantId().equals(ctx.getTenantId())) {
  334 + return Boolean.FALSE;
  335 + } else if (ctx.isCustomerUser() && !asset.getCustomerId().equals(ctx.getCustomerId())) {
  336 + return Boolean.FALSE;
  337 + } else {
  338 + return Boolean.TRUE;
  339 + }
  340 + }
  341 + }));
  342 + }
  343 + }
  344 +
  345 + private void validateRule(final PluginApiCallSecurityContext ctx, EntityId entityId, ValidationCallback callback) {
  346 + if (ctx.isCustomerUser()) {
  347 + callback.onSuccess(this, Boolean.FALSE);
  348 + } else {
  349 + ListenableFuture<RuleMetaData> ruleFuture = pluginCtx.ruleService.findRuleByIdAsync(new RuleId(entityId.getId()));
  350 + Futures.addCallback(ruleFuture, getCallback(callback, rule -> {
  351 + if (rule == null) {
  352 + return Boolean.FALSE;
  353 + } else {
  354 + if (ctx.isTenantAdmin() && !rule.getTenantId().equals(ctx.getTenantId())) {
  355 + return Boolean.FALSE;
  356 + } else if (ctx.isSystemAdmin() && !rule.getTenantId().isNullUid()) {
  357 + return Boolean.FALSE;
  358 + } else {
  359 + return Boolean.TRUE;
  360 + }
  361 + }
  362 + }));
  363 + }
  364 + }
  365 +
  366 + private void validatePlugin(final PluginApiCallSecurityContext ctx, EntityId entityId, ValidationCallback callback) {
  367 + if (ctx.isCustomerUser()) {
  368 + callback.onSuccess(this, Boolean.FALSE);
  369 + } else {
  370 + ListenableFuture<PluginMetaData> pluginFuture = pluginCtx.pluginService.findPluginByIdAsync(new PluginId(entityId.getId()));
  371 + Futures.addCallback(pluginFuture, getCallback(callback, plugin -> {
  372 + if (plugin == null) {
  373 + return Boolean.FALSE;
  374 + } else {
  375 + if (ctx.isTenantAdmin() && !plugin.getTenantId().equals(ctx.getTenantId())) {
  376 + return Boolean.FALSE;
  377 + } else if (ctx.isSystemAdmin() && !plugin.getTenantId().isNullUid()) {
  378 + return Boolean.FALSE;
  379 + } else {
  380 + return Boolean.TRUE;
  381 + }
  382 + }
  383 + }));
  384 + }
  385 + }
  386 +
  387 + private void validateCustomer(final PluginApiCallSecurityContext ctx, EntityId entityId, ValidationCallback callback) {
  388 + if (ctx.isSystemAdmin()) {
  389 + callback.onSuccess(this, Boolean.FALSE);
  390 + } else {
  391 + ListenableFuture<Customer> customerFuture = pluginCtx.customerService.findCustomerByIdAsync(new CustomerId(entityId.getId()));
  392 + Futures.addCallback(customerFuture, getCallback(callback, customer -> {
  393 + if (customer == null) {
  394 + return Boolean.FALSE;
  395 + } else {
  396 + if (!customer.getTenantId().equals(ctx.getTenantId())) {
  397 + return Boolean.FALSE;
  398 + } else if (ctx.isCustomerUser() && !customer.getId().equals(ctx.getCustomerId())) {
  399 + return Boolean.FALSE;
  400 + } else {
  401 + return Boolean.TRUE;
  402 + }
  403 + }
  404 + }));
  405 + }
  406 + }
  407 +
  408 + private void validateTenant(final PluginApiCallSecurityContext ctx, EntityId entityId, ValidationCallback callback) {
  409 + if (ctx.isCustomerUser()) {
  410 + callback.onSuccess(this, Boolean.FALSE);
  411 + } else if (ctx.isSystemAdmin()) {
  412 + callback.onSuccess(this, Boolean.TRUE);
  413 + } else {
  414 + ListenableFuture<Tenant> tenantFuture = pluginCtx.tenantService.findTenantByIdAsync(new TenantId(entityId.getId()));
  415 + Futures.addCallback(tenantFuture, getCallback(callback, tenant -> tenant != null && tenant.getId().equals(ctx.getTenantId())));
  416 + }
  417 + }
  418 +
399 @Override 419 @Override
400 public ListenableFuture<List<EntityRelation>> findByFromAndType(EntityId from, String relationType) { 420 public ListenableFuture<List<EntityRelation>> findByFromAndType(EntityId from, String relationType) {
401 return this.pluginCtx.relationService.findByFromAndType(from, relationType, RelationTypeGroup.COMMON); 421 return this.pluginCtx.relationService.findByFromAndType(from, relationType, RelationTypeGroup.COMMON);
@@ -59,7 +59,7 @@ public class RuleToPluginMsgWrapper implements ToPluginActorMsg, RuleAwareMsg { @@ -59,7 +59,7 @@ public class RuleToPluginMsgWrapper implements ToPluginActorMsg, RuleAwareMsg {
59 } 59 }
60 60
61 61
62 - public RuleToPluginMsg<?> getMsg() { 62 + public RuleToPluginMsg getMsg() {
63 return msg; 63 return msg;
64 } 64 }
65 65
@@ -45,6 +45,7 @@ import java.util.UUID; @@ -45,6 +45,7 @@ import java.util.UUID;
45 @Slf4j 45 @Slf4j
46 public class BasicRpcSessionListener implements GrpcSessionListener { 46 public class BasicRpcSessionListener implements GrpcSessionListener {
47 47
  48 + public static final String SESSION_RECEIVED_SESSION_ACTOR_MSG = "{} session [{}] received session actor msg {}";
48 private final ActorSystemContext context; 49 private final ActorSystemContext context;
49 private final ActorService service; 50 private final ActorService service;
50 private final ActorRef manager; 51 private final ActorRef manager;
@@ -93,25 +94,25 @@ public class BasicRpcSessionListener implements GrpcSessionListener { @@ -93,25 +94,25 @@ public class BasicRpcSessionListener implements GrpcSessionListener {
93 94
94 @Override 95 @Override
95 public void onToDeviceSessionActorRpcMsg(GrpcSession session, ClusterAPIProtos.ToDeviceSessionActorRpcMessage msg) { 96 public void onToDeviceSessionActorRpcMsg(GrpcSession session, ClusterAPIProtos.ToDeviceSessionActorRpcMessage msg) {
96 - log.trace("{} session [{}] received session actor msg {}", getType(session), session.getRemoteServer(), msg); 97 + log.trace(SESSION_RECEIVED_SESSION_ACTOR_MSG, getType(session), session.getRemoteServer(), msg);
97 service.onMsg((ToDeviceSessionActorMsg) deserialize(msg.getData().toByteArray())); 98 service.onMsg((ToDeviceSessionActorMsg) deserialize(msg.getData().toByteArray()));
98 } 99 }
99 100
100 @Override 101 @Override
101 public void onToDeviceRpcRequestRpcMsg(GrpcSession session, ClusterAPIProtos.ToDeviceRpcRequestRpcMessage msg) { 102 public void onToDeviceRpcRequestRpcMsg(GrpcSession session, ClusterAPIProtos.ToDeviceRpcRequestRpcMessage msg) {
102 - log.trace("{} session [{}] received session actor msg {}", getType(session), session.getRemoteServer(), msg); 103 + log.trace(SESSION_RECEIVED_SESSION_ACTOR_MSG, getType(session), session.getRemoteServer(), msg);
103 service.onMsg(deserialize(session.getRemoteServer(), msg)); 104 service.onMsg(deserialize(session.getRemoteServer(), msg));
104 } 105 }
105 106
106 @Override 107 @Override
107 public void onFromDeviceRpcResponseRpcMsg(GrpcSession session, ClusterAPIProtos.ToPluginRpcResponseRpcMessage msg) { 108 public void onFromDeviceRpcResponseRpcMsg(GrpcSession session, ClusterAPIProtos.ToPluginRpcResponseRpcMessage msg) {
108 - log.trace("{} session [{}] received session actor msg {}", getType(session), session.getRemoteServer(), msg); 109 + log.trace(SESSION_RECEIVED_SESSION_ACTOR_MSG, getType(session), session.getRemoteServer(), msg);
109 service.onMsg(deserialize(session.getRemoteServer(), msg)); 110 service.onMsg(deserialize(session.getRemoteServer(), msg));
110 } 111 }
111 112
112 @Override 113 @Override
113 public void onToAllNodesRpcMessage(GrpcSession session, ClusterAPIProtos.ToAllNodesRpcMessage msg) { 114 public void onToAllNodesRpcMessage(GrpcSession session, ClusterAPIProtos.ToAllNodesRpcMessage msg) {
114 - log.trace("{} session [{}] received session actor msg {}", getType(session), session.getRemoteServer(), msg); 115 + log.trace(SESSION_RECEIVED_SESSION_ACTOR_MSG, getType(session), session.getRemoteServer(), msg);
115 service.onMsg((ToAllNodesMsg) deserialize(msg.getData().toByteArray())); 116 service.onMsg((ToAllNodesMsg) deserialize(msg.getData().toByteArray()));
116 } 117 }
117 118
@@ -322,7 +322,7 @@ class RuleActorMessageProcessor extends ComponentMsgProcessor<RuleId> { @@ -322,7 +322,7 @@ class RuleActorMessageProcessor extends ComponentMsgProcessor<RuleId> {
322 322
323 @Override 323 @Override
324 public void onClusterEventMsg(ClusterEventMsg msg) throws Exception { 324 public void onClusterEventMsg(ClusterEventMsg msg) throws Exception {
325 - 325 + //Do nothing
326 } 326 }
327 327
328 private void stopAction() { 328 private void stopAction() {
@@ -104,6 +104,9 @@ public abstract class ComponentActor<T extends EntityId, P extends ComponentMsgP @@ -104,6 +104,9 @@ public abstract class ComponentActor<T extends EntityId, P extends ComponentMsgP
104 break; 104 break;
105 case DELETED: 105 case DELETED:
106 processor.onStop(context()); 106 processor.onStop(context());
  107 + break;
  108 + default:
  109 + break;
107 } 110 }
108 logLifecycleEvent(msg.getEvent()); 111 logLifecycleEvent(msg.getEvent());
109 } catch (Exception e) { 112 } catch (Exception e) {
@@ -23,7 +23,7 @@ public abstract class ContextBasedCreator<T> implements Creator<T> { @@ -23,7 +23,7 @@ public abstract class ContextBasedCreator<T> implements Creator<T> {
23 23
24 private static final long serialVersionUID = 1L; 24 private static final long serialVersionUID = 1L;
25 25
26 - protected final ActorSystemContext context; 26 + protected final transient ActorSystemContext context;
27 27
28 public ContextBasedCreator(ActorSystemContext context) { 28 public ContextBasedCreator(ActorSystemContext context) {
29 super(); 29 super();
@@ -202,7 +202,7 @@ public class DefaultActorService implements ActorService { @@ -202,7 +202,7 @@ public class DefaultActorService implements ActorService {
202 202
203 @Override 203 @Override
204 public void onServerUpdated(ServerInstance server) { 204 public void onServerUpdated(ServerInstance server) {
205 - 205 + //Do nothing
206 } 206 }
207 207
208 @Override 208 @Override
@@ -77,6 +77,8 @@ class ASyncMsgProcessor extends AbstractSessionActorMsgProcessor { @@ -77,6 +77,8 @@ class ASyncMsgProcessor extends AbstractSessionActorMsgProcessor {
77 case UNSUBSCRIBE_RPC_COMMANDS_REQUEST: 77 case UNSUBSCRIBE_RPC_COMMANDS_REQUEST:
78 subscribedToRpcCommands = false; 78 subscribedToRpcCommands = false;
79 break; 79 break;
  80 + default:
  81 + break;
80 } 82 }
81 currentTargetServer = forwardToAppActor(ctx, pendingMsg); 83 currentTargetServer = forwardToAppActor(ctx, pendingMsg);
82 } 84 }
@@ -94,6 +96,8 @@ class ASyncMsgProcessor extends AbstractSessionActorMsgProcessor { @@ -94,6 +96,8 @@ class ASyncMsgProcessor extends AbstractSessionActorMsgProcessor {
94 pendingMap.remove(responseMsg.getRequestId()); 96 pendingMap.remove(responseMsg.getRequestId());
95 } 97 }
96 break; 98 break;
  99 + default:
  100 + break;
97 } 101 }
98 sessionCtx.onMsg(new BasicSessionActorToAdaptorMsg(this.sessionCtx, msg)); 102 sessionCtx.onMsg(new BasicSessionActorToAdaptorMsg(this.sessionCtx, msg));
99 } else { 103 } else {
@@ -109,6 +113,7 @@ class ASyncMsgProcessor extends AbstractSessionActorMsgProcessor { @@ -109,6 +113,7 @@ class ASyncMsgProcessor extends AbstractSessionActorMsgProcessor {
109 // TODO Auto-generated method stub 113 // TODO Auto-generated method stub
110 } 114 }
111 115
  116 + @Override
112 protected void cleanupSession(ActorContext ctx) { 117 protected void cleanupSession(ActorContext ctx) {
113 toDeviceMsg(new SessionCloseMsg()).ifPresent(m -> forwardToAppActor(ctx, m)); 118 toDeviceMsg(new SessionCloseMsg()).ifPresent(m -> forwardToAppActor(ctx, m));
114 } 119 }
@@ -31,6 +31,7 @@ public class TenantPluginManager extends PluginManager { @@ -31,6 +31,7 @@ public class TenantPluginManager extends PluginManager {
31 this.tenantId = tenantId; 31 this.tenantId = tenantId;
32 } 32 }
33 33
  34 + @Override
34 public void init(ActorContext context) { 35 public void init(ActorContext context) {
35 if (systemContext.isTenantComponentsInitEnabled()) { 36 if (systemContext.isTenantComponentsInitEnabled()) {
36 super.init(context); 37 super.init(context);
@@ -32,6 +32,8 @@ import org.thingsboard.server.actors.shared.plugin.TenantPluginManager; @@ -32,6 +32,8 @@ import org.thingsboard.server.actors.shared.plugin.TenantPluginManager;
32 import org.thingsboard.server.actors.shared.rule.RuleManager; 32 import org.thingsboard.server.actors.shared.rule.RuleManager;
33 import org.thingsboard.server.actors.shared.rule.TenantRuleManager; 33 import org.thingsboard.server.actors.shared.rule.TenantRuleManager;
34 import org.thingsboard.server.common.data.id.DeviceId; 34 import org.thingsboard.server.common.data.id.DeviceId;
  35 +import org.thingsboard.server.common.data.id.PluginId;
  36 +import org.thingsboard.server.common.data.id.RuleId;
35 import org.thingsboard.server.common.data.id.TenantId; 37 import org.thingsboard.server.common.data.id.TenantId;
36 import org.thingsboard.server.common.msg.cluster.ClusterEventMsg; 38 import org.thingsboard.server.common.msg.cluster.ClusterEventMsg;
37 import org.thingsboard.server.common.msg.device.ToDeviceActorMsg; 39 import org.thingsboard.server.common.msg.device.ToDeviceActorMsg;
@@ -126,16 +128,18 @@ public class TenantActor extends ContextAwareActor { @@ -126,16 +128,18 @@ public class TenantActor extends ContextAwareActor {
126 } 128 }
127 129
128 private void onComponentLifecycleMsg(ComponentLifecycleMsg msg) { 130 private void onComponentLifecycleMsg(ComponentLifecycleMsg msg) {
129 - if (msg.getPluginId().isPresent()) {  
130 - ActorRef pluginActor = pluginManager.getOrCreatePluginActor(this.context(), msg.getPluginId().get()); 131 + Optional<PluginId> pluginId = msg.getPluginId();
  132 + Optional<RuleId> ruleId = msg.getRuleId();
  133 + if (pluginId.isPresent()) {
  134 + ActorRef pluginActor = pluginManager.getOrCreatePluginActor(this.context(), pluginId.get());
131 pluginActor.tell(msg, ActorRef.noSender()); 135 pluginActor.tell(msg, ActorRef.noSender());
132 - } else if (msg.getRuleId().isPresent()) { 136 + } else if (ruleId.isPresent()) {
133 ActorRef target; 137 ActorRef target;
134 - Optional<ActorRef> ref = ruleManager.update(this.context(), msg.getRuleId().get(), msg.getEvent()); 138 + Optional<ActorRef> ref = ruleManager.update(this.context(), ruleId.get(), msg.getEvent());
135 if (ref.isPresent()) { 139 if (ref.isPresent()) {
136 target = ref.get(); 140 target = ref.get();
137 } else { 141 } else {
138 - logger.debug("Failed to find actor for rule: [{}]", msg.getRuleId()); 142 + logger.debug("Failed to find actor for rule: [{}]", ruleId);
139 return; 143 return;
140 } 144 }
141 target.tell(msg, ActorRef.noSender()); 145 target.tell(msg, ActorRef.noSender());
@@ -33,6 +33,7 @@ public class MvcCorsProperties { @@ -33,6 +33,7 @@ public class MvcCorsProperties {
33 private Map<String, CorsConfiguration> mappings = new HashMap<>(); 33 private Map<String, CorsConfiguration> mappings = new HashMap<>();
34 34
35 public MvcCorsProperties() { 35 public MvcCorsProperties() {
  36 + super();
36 } 37 }
37 38
38 public Map<String, CorsConfiguration> getMappings() { 39 public Map<String, CorsConfiguration> getMappings() {
@@ -64,7 +64,7 @@ public class ThingsboardSecurityConfiguration extends WebSecurityConfigurerAdapt @@ -64,7 +64,7 @@ public class ThingsboardSecurityConfiguration extends WebSecurityConfigurerAdapt
64 public static final String FORM_BASED_LOGIN_ENTRY_POINT = "/api/auth/login"; 64 public static final String FORM_BASED_LOGIN_ENTRY_POINT = "/api/auth/login";
65 public static final String PUBLIC_LOGIN_ENTRY_POINT = "/api/auth/login/public"; 65 public static final String PUBLIC_LOGIN_ENTRY_POINT = "/api/auth/login/public";
66 public static final String TOKEN_REFRESH_ENTRY_POINT = "/api/auth/token"; 66 public static final String TOKEN_REFRESH_ENTRY_POINT = "/api/auth/token";
67 - public static final String[] NON_TOKEN_BASED_AUTH_ENTRY_POINTS = new String[] {"/index.html", "/static/**", "/api/noauth/**", "/webjars/**"}; 67 + protected static final String[] NON_TOKEN_BASED_AUTH_ENTRY_POINTS = new String[] {"/index.html", "/static/**", "/api/noauth/**", "/webjars/**"};
68 public static final String TOKEN_BASED_AUTH_ENTRY_POINT = "/api/**"; 68 public static final String TOKEN_BASED_AUTH_ENTRY_POINT = "/api/**";
69 public static final String WS_TOKEN_BASED_AUTH_ENTRY_POINT = "/api/ws/**"; 69 public static final String WS_TOKEN_BASED_AUTH_ENTRY_POINT = "/api/ws/**";
70 70
@@ -76,6 +76,7 @@ public class WebSocketConfiguration implements WebSocketConfigurer { @@ -76,6 +76,7 @@ public class WebSocketConfiguration implements WebSocketConfigurer {
76 @Override 76 @Override
77 public void afterHandshake(ServerHttpRequest request, ServerHttpResponse response, WebSocketHandler wsHandler, 77 public void afterHandshake(ServerHttpRequest request, ServerHttpResponse response, WebSocketHandler wsHandler,
78 Exception exception) { 78 Exception exception) {
  79 + //Do nothing
79 } 80 }
80 }); 81 });
81 } 82 }
@@ -30,13 +30,16 @@ import org.thingsboard.server.exception.ThingsboardException; @@ -30,13 +30,16 @@ import org.thingsboard.server.exception.ThingsboardException;
30 @RequestMapping("/api") 30 @RequestMapping("/api")
31 public class AlarmController extends BaseController { 31 public class AlarmController extends BaseController {
32 32
  33 + public static final String ALARM_ID = "alarmId";
  34 +
33 @PreAuthorize("hasAnyAuthority('SYS_ADMIN', 'TENANT_ADMIN', 'CUSTOMER_USER')") 35 @PreAuthorize("hasAnyAuthority('SYS_ADMIN', 'TENANT_ADMIN', 'CUSTOMER_USER')")
34 @RequestMapping(value = "/alarm/{alarmId}", method = RequestMethod.GET) 36 @RequestMapping(value = "/alarm/{alarmId}", method = RequestMethod.GET)
35 @ResponseBody 37 @ResponseBody
36 - public Alarm getAlarmById(@PathVariable("alarmId") String strAlarmId) throws ThingsboardException {  
37 - checkParameter("alarmId", strAlarmId); 38 + public Alarm getAlarmById(@PathVariable(ALARM_ID) String strAlarmId) throws ThingsboardException {
  39 + checkParameter(ALARM_ID, strAlarmId);
38 try { 40 try {
39 AlarmId alarmId = new AlarmId(toUUID(strAlarmId)); 41 AlarmId alarmId = new AlarmId(toUUID(strAlarmId));
  42 +
40 return checkAlarmId(alarmId); 43 return checkAlarmId(alarmId);
41 } catch (Exception e) { 44 } catch (Exception e) {
42 throw handleException(e); 45 throw handleException(e);
@@ -46,8 +49,8 @@ public class AlarmController extends BaseController { @@ -46,8 +49,8 @@ public class AlarmController extends BaseController {
46 @PreAuthorize("hasAnyAuthority('SYS_ADMIN', 'TENANT_ADMIN', 'CUSTOMER_USER')") 49 @PreAuthorize("hasAnyAuthority('SYS_ADMIN', 'TENANT_ADMIN', 'CUSTOMER_USER')")
47 @RequestMapping(value = "/alarm/info/{alarmId}", method = RequestMethod.GET) 50 @RequestMapping(value = "/alarm/info/{alarmId}", method = RequestMethod.GET)
48 @ResponseBody 51 @ResponseBody
49 - public AlarmInfo getAlarmInfoById(@PathVariable("alarmId") String strAlarmId) throws ThingsboardException {  
50 - checkParameter("alarmId", strAlarmId); 52 + public AlarmInfo getAlarmInfoById(@PathVariable(ALARM_ID) String strAlarmId) throws ThingsboardException {
  53 + checkParameter(ALARM_ID, strAlarmId);
51 try { 54 try {
52 AlarmId alarmId = new AlarmId(toUUID(strAlarmId)); 55 AlarmId alarmId = new AlarmId(toUUID(strAlarmId));
53 return checkAlarmInfoId(alarmId); 56 return checkAlarmInfoId(alarmId);
@@ -71,8 +74,8 @@ public class AlarmController extends BaseController { @@ -71,8 +74,8 @@ public class AlarmController extends BaseController {
71 @PreAuthorize("hasAnyAuthority('SYS_ADMIN', 'TENANT_ADMIN', 'CUSTOMER_USER')") 74 @PreAuthorize("hasAnyAuthority('SYS_ADMIN', 'TENANT_ADMIN', 'CUSTOMER_USER')")
72 @RequestMapping(value = "/alarm/{alarmId}/ack", method = RequestMethod.POST) 75 @RequestMapping(value = "/alarm/{alarmId}/ack", method = RequestMethod.POST)
73 @ResponseStatus(value = HttpStatus.OK) 76 @ResponseStatus(value = HttpStatus.OK)
74 - public void ackAlarm(@PathVariable("alarmId") String strAlarmId) throws ThingsboardException {  
75 - checkParameter("alarmId", strAlarmId); 77 + public void ackAlarm(@PathVariable(ALARM_ID) String strAlarmId) throws ThingsboardException {
  78 + checkParameter(ALARM_ID, strAlarmId);
76 try { 79 try {
77 AlarmId alarmId = new AlarmId(toUUID(strAlarmId)); 80 AlarmId alarmId = new AlarmId(toUUID(strAlarmId));
78 checkAlarmId(alarmId); 81 checkAlarmId(alarmId);
@@ -85,8 +88,8 @@ public class AlarmController extends BaseController { @@ -85,8 +88,8 @@ public class AlarmController extends BaseController {
85 @PreAuthorize("hasAnyAuthority('SYS_ADMIN', 'TENANT_ADMIN', 'CUSTOMER_USER')") 88 @PreAuthorize("hasAnyAuthority('SYS_ADMIN', 'TENANT_ADMIN', 'CUSTOMER_USER')")
86 @RequestMapping(value = "/alarm/{alarmId}/clear", method = RequestMethod.POST) 89 @RequestMapping(value = "/alarm/{alarmId}/clear", method = RequestMethod.POST)
87 @ResponseStatus(value = HttpStatus.OK) 90 @ResponseStatus(value = HttpStatus.OK)
88 - public void clearAlarm(@PathVariable("alarmId") String strAlarmId) throws ThingsboardException {  
89 - checkParameter("alarmId", strAlarmId); 91 + public void clearAlarm(@PathVariable(ALARM_ID) String strAlarmId) throws ThingsboardException {
  92 + checkParameter(ALARM_ID, strAlarmId);
90 try { 93 try {
91 AlarmId alarmId = new AlarmId(toUUID(strAlarmId)); 94 AlarmId alarmId = new AlarmId(toUUID(strAlarmId));
92 checkAlarmId(alarmId); 95 checkAlarmId(alarmId);
@@ -43,11 +43,13 @@ import java.util.stream.Collectors; @@ -43,11 +43,13 @@ import java.util.stream.Collectors;
43 @RequestMapping("/api") 43 @RequestMapping("/api")
44 public class AssetController extends BaseController { 44 public class AssetController extends BaseController {
45 45
  46 + public static final String ASSET_ID = "assetId";
  47 +
46 @PreAuthorize("hasAnyAuthority('TENANT_ADMIN', 'CUSTOMER_USER')") 48 @PreAuthorize("hasAnyAuthority('TENANT_ADMIN', 'CUSTOMER_USER')")
47 @RequestMapping(value = "/asset/{assetId}", method = RequestMethod.GET) 49 @RequestMapping(value = "/asset/{assetId}", method = RequestMethod.GET)
48 @ResponseBody 50 @ResponseBody
49 - public Asset getAssetById(@PathVariable("assetId") String strAssetId) throws ThingsboardException {  
50 - checkParameter("assetId", strAssetId); 51 + public Asset getAssetById(@PathVariable(ASSET_ID) String strAssetId) throws ThingsboardException {
  52 + checkParameter(ASSET_ID, strAssetId);
51 try { 53 try {
52 AssetId assetId = new AssetId(toUUID(strAssetId)); 54 AssetId assetId = new AssetId(toUUID(strAssetId));
53 return checkAssetId(assetId); 55 return checkAssetId(assetId);
@@ -80,8 +82,8 @@ public class AssetController extends BaseController { @@ -80,8 +82,8 @@ public class AssetController extends BaseController {
80 @PreAuthorize("hasAuthority('TENANT_ADMIN')") 82 @PreAuthorize("hasAuthority('TENANT_ADMIN')")
81 @RequestMapping(value = "/asset/{assetId}", method = RequestMethod.DELETE) 83 @RequestMapping(value = "/asset/{assetId}", method = RequestMethod.DELETE)
82 @ResponseStatus(value = HttpStatus.OK) 84 @ResponseStatus(value = HttpStatus.OK)
83 - public void deleteAsset(@PathVariable("assetId") String strAssetId) throws ThingsboardException {  
84 - checkParameter("assetId", strAssetId); 85 + public void deleteAsset(@PathVariable(ASSET_ID) String strAssetId) throws ThingsboardException {
  86 + checkParameter(ASSET_ID, strAssetId);
85 try { 87 try {
86 AssetId assetId = new AssetId(toUUID(strAssetId)); 88 AssetId assetId = new AssetId(toUUID(strAssetId));
87 checkAssetId(assetId); 89 checkAssetId(assetId);
@@ -95,9 +97,9 @@ public class AssetController extends BaseController { @@ -95,9 +97,9 @@ public class AssetController extends BaseController {
95 @RequestMapping(value = "/customer/{customerId}/asset/{assetId}", method = RequestMethod.POST) 97 @RequestMapping(value = "/customer/{customerId}/asset/{assetId}", method = RequestMethod.POST)
96 @ResponseBody 98 @ResponseBody
97 public Asset assignAssetToCustomer(@PathVariable("customerId") String strCustomerId, 99 public Asset assignAssetToCustomer(@PathVariable("customerId") String strCustomerId,
98 - @PathVariable("assetId") String strAssetId) throws ThingsboardException { 100 + @PathVariable(ASSET_ID) String strAssetId) throws ThingsboardException {
99 checkParameter("customerId", strCustomerId); 101 checkParameter("customerId", strCustomerId);
100 - checkParameter("assetId", strAssetId); 102 + checkParameter(ASSET_ID, strAssetId);
101 try { 103 try {
102 CustomerId customerId = new CustomerId(toUUID(strCustomerId)); 104 CustomerId customerId = new CustomerId(toUUID(strCustomerId));
103 checkCustomerId(customerId); 105 checkCustomerId(customerId);
@@ -114,8 +116,8 @@ public class AssetController extends BaseController { @@ -114,8 +116,8 @@ public class AssetController extends BaseController {
114 @PreAuthorize("hasAuthority('TENANT_ADMIN')") 116 @PreAuthorize("hasAuthority('TENANT_ADMIN')")
115 @RequestMapping(value = "/customer/asset/{assetId}", method = RequestMethod.DELETE) 117 @RequestMapping(value = "/customer/asset/{assetId}", method = RequestMethod.DELETE)
116 @ResponseBody 118 @ResponseBody
117 - public Asset unassignAssetFromCustomer(@PathVariable("assetId") String strAssetId) throws ThingsboardException {  
118 - checkParameter("assetId", strAssetId); 119 + public Asset unassignAssetFromCustomer(@PathVariable(ASSET_ID) String strAssetId) throws ThingsboardException {
  120 + checkParameter(ASSET_ID, strAssetId);
119 try { 121 try {
120 AssetId assetId = new AssetId(toUUID(strAssetId)); 122 AssetId assetId = new AssetId(toUUID(strAssetId));
121 Asset asset = checkAssetId(assetId); 123 Asset asset = checkAssetId(assetId);
@@ -131,8 +133,8 @@ public class AssetController extends BaseController { @@ -131,8 +133,8 @@ public class AssetController extends BaseController {
131 @PreAuthorize("hasAuthority('TENANT_ADMIN')") 133 @PreAuthorize("hasAuthority('TENANT_ADMIN')")
132 @RequestMapping(value = "/customer/public/asset/{assetId}", method = RequestMethod.POST) 134 @RequestMapping(value = "/customer/public/asset/{assetId}", method = RequestMethod.POST)
133 @ResponseBody 135 @ResponseBody
134 - public Asset assignAssetToPublicCustomer(@PathVariable("assetId") String strAssetId) throws ThingsboardException {  
135 - checkParameter("assetId", strAssetId); 136 + public Asset assignAssetToPublicCustomer(@PathVariable(ASSET_ID) String strAssetId) throws ThingsboardException {
  137 + checkParameter(ASSET_ID, strAssetId);
136 try { 138 try {
137 AssetId assetId = new AssetId(toUUID(strAssetId)); 139 AssetId assetId = new AssetId(toUUID(strAssetId));
138 Asset asset = checkAssetId(assetId); 140 Asset asset = checkAssetId(assetId);
@@ -61,9 +61,6 @@ public class AuthController extends BaseController { @@ -61,9 +61,6 @@ public class AuthController extends BaseController {
61 private RefreshTokenRepository refreshTokenRepository; 61 private RefreshTokenRepository refreshTokenRepository;
62 62
63 @Autowired 63 @Autowired
64 - private UserService userService;  
65 -  
66 - @Autowired  
67 private MailService mailService; 64 private MailService mailService;
68 65
69 @PreAuthorize("isAuthenticated()") 66 @PreAuthorize("isAuthenticated()")
@@ -103,13 +100,13 @@ public class AuthController extends BaseController { @@ -103,13 +100,13 @@ public class AuthController extends BaseController {
103 HttpStatus responseStatus; 100 HttpStatus responseStatus;
104 UserCredentials userCredentials = userService.findUserCredentialsByActivateToken(activateToken); 101 UserCredentials userCredentials = userService.findUserCredentialsByActivateToken(activateToken);
105 if (userCredentials != null) { 102 if (userCredentials != null) {
106 - String createPasswordURI = "/login/createPassword"; 103 + String createURI = "/login/createPassword";
107 try { 104 try {
108 - URI location = new URI(createPasswordURI + "?activateToken=" + activateToken); 105 + URI location = new URI(createURI + "?activateToken=" + activateToken);
109 headers.setLocation(location); 106 headers.setLocation(location);
110 responseStatus = HttpStatus.SEE_OTHER; 107 responseStatus = HttpStatus.SEE_OTHER;
111 } catch (URISyntaxException e) { 108 } catch (URISyntaxException e) {
112 - log.error("Unable to create URI with address [{}]", createPasswordURI); 109 + log.error("Unable to create URI with address [{}]", createURI);
113 responseStatus = HttpStatus.BAD_REQUEST; 110 responseStatus = HttpStatus.BAD_REQUEST;
114 } 111 }
115 } else { 112 } else {
@@ -126,10 +123,10 @@ public class AuthController extends BaseController { @@ -126,10 +123,10 @@ public class AuthController extends BaseController {
126 try { 123 try {
127 UserCredentials userCredentials = userService.requestPasswordReset(email); 124 UserCredentials userCredentials = userService.requestPasswordReset(email);
128 String baseUrl = constructBaseUrl(request); 125 String baseUrl = constructBaseUrl(request);
129 - String resetPasswordUrl = String.format("%s/api/noauth/resetPassword?resetToken=%s", baseUrl, 126 + String resetUrl = String.format("%s/api/noauth/resetPassword?resetToken=%s", baseUrl,
130 userCredentials.getResetToken()); 127 userCredentials.getResetToken());
131 128
132 - mailService.sendResetPasswordEmail(resetPasswordUrl, email); 129 + mailService.sendResetPasswordEmail(resetUrl, email);
133 } catch (Exception e) { 130 } catch (Exception e) {
134 throw handleException(e); 131 throw handleException(e);
135 } 132 }
@@ -140,15 +137,15 @@ public class AuthController extends BaseController { @@ -140,15 +137,15 @@ public class AuthController extends BaseController {
140 @RequestParam(value = "resetToken") String resetToken) { 137 @RequestParam(value = "resetToken") String resetToken) {
141 HttpHeaders headers = new HttpHeaders(); 138 HttpHeaders headers = new HttpHeaders();
142 HttpStatus responseStatus; 139 HttpStatus responseStatus;
143 - String resetPasswordURI = "/login/resetPassword"; 140 + String resetURI = "/login/resetPassword";
144 UserCredentials userCredentials = userService.findUserCredentialsByResetToken(resetToken); 141 UserCredentials userCredentials = userService.findUserCredentialsByResetToken(resetToken);
145 if (userCredentials != null) { 142 if (userCredentials != null) {
146 try { 143 try {
147 - URI location = new URI(resetPasswordURI + "?resetToken=" + resetToken); 144 + URI location = new URI(resetURI + "?resetToken=" + resetToken);
148 headers.setLocation(location); 145 headers.setLocation(location);
149 responseStatus = HttpStatus.SEE_OTHER; 146 responseStatus = HttpStatus.SEE_OTHER;
150 } catch (URISyntaxException e) { 147 } catch (URISyntaxException e) {
151 - log.error("Unable to create URI with address [{}]", resetPasswordURI); 148 + log.error("Unable to create URI with address [{}]", resetURI);
152 responseStatus = HttpStatus.BAD_REQUEST; 149 responseStatus = HttpStatus.BAD_REQUEST;
153 } 150 }
154 } else { 151 } else {
@@ -70,6 +70,8 @@ import static org.thingsboard.server.dao.service.Validator.validateId; @@ -70,6 +70,8 @@ import static org.thingsboard.server.dao.service.Validator.validateId;
70 @Slf4j 70 @Slf4j
71 public abstract class BaseController { 71 public abstract class BaseController {
72 72
  73 + public static final String INCORRECT_TENANT_ID = "Incorrect tenantId ";
  74 + public static final String YOU_DON_T_HAVE_PERMISSION_TO_PERFORM_THIS_OPERATION = "You don't have permission to perform this operation!";
73 @Autowired 75 @Autowired
74 private ThingsboardErrorResponseHandler errorResponseHandler; 76 private ThingsboardErrorResponseHandler errorResponseHandler;
75 77
@@ -209,11 +211,11 @@ public abstract class BaseController { @@ -209,11 +211,11 @@ public abstract class BaseController {
209 } 211 }
210 212
211 void checkTenantId(TenantId tenantId) throws ThingsboardException { 213 void checkTenantId(TenantId tenantId) throws ThingsboardException {
212 - validateId(tenantId, "Incorrect tenantId " + tenantId); 214 + validateId(tenantId, INCORRECT_TENANT_ID + tenantId);
213 SecurityUser authUser = getCurrentUser(); 215 SecurityUser authUser = getCurrentUser();
214 if (authUser.getAuthority() != Authority.SYS_ADMIN && 216 if (authUser.getAuthority() != Authority.SYS_ADMIN &&
215 (authUser.getTenantId() == null || !authUser.getTenantId().equals(tenantId))) { 217 (authUser.getTenantId() == null || !authUser.getTenantId().equals(tenantId))) {
216 - throw new ThingsboardException("You don't have permission to perform this operation!", 218 + throw new ThingsboardException(YOU_DON_T_HAVE_PERMISSION_TO_PERFORM_THIS_OPERATION,
217 ThingsboardErrorCode.PERMISSION_DENIED); 219 ThingsboardErrorCode.PERMISSION_DENIED);
218 } 220 }
219 } 221 }
@@ -229,7 +231,7 @@ public abstract class BaseController { @@ -229,7 +231,7 @@ public abstract class BaseController {
229 if (authUser.getAuthority() == Authority.SYS_ADMIN || 231 if (authUser.getAuthority() == Authority.SYS_ADMIN ||
230 (authUser.getAuthority() != Authority.TENANT_ADMIN && 232 (authUser.getAuthority() != Authority.TENANT_ADMIN &&
231 (authUser.getCustomerId() == null || !authUser.getCustomerId().equals(customerId)))) { 233 (authUser.getCustomerId() == null || !authUser.getCustomerId().equals(customerId)))) {
232 - throw new ThingsboardException("You don't have permission to perform this operation!", 234 + throw new ThingsboardException(YOU_DON_T_HAVE_PERMISSION_TO_PERFORM_THIS_OPERATION,
233 ThingsboardErrorCode.PERMISSION_DENIED); 235 ThingsboardErrorCode.PERMISSION_DENIED);
234 } 236 }
235 Customer customer = customerService.findCustomerById(customerId); 237 Customer customer = customerService.findCustomerById(customerId);
@@ -382,7 +384,7 @@ public abstract class BaseController { @@ -382,7 +384,7 @@ public abstract class BaseController {
382 if (widgetsBundle.getTenantId() != null && !widgetsBundle.getTenantId().getId().equals(ModelConstants.NULL_UUID)) { 384 if (widgetsBundle.getTenantId() != null && !widgetsBundle.getTenantId().getId().equals(ModelConstants.NULL_UUID)) {
383 checkTenantId(widgetsBundle.getTenantId()); 385 checkTenantId(widgetsBundle.getTenantId());
384 } else if (modify && getCurrentUser().getAuthority() != Authority.SYS_ADMIN) { 386 } else if (modify && getCurrentUser().getAuthority() != Authority.SYS_ADMIN) {
385 - throw new ThingsboardException("You don't have permission to perform this operation!", 387 + throw new ThingsboardException(YOU_DON_T_HAVE_PERMISSION_TO_PERFORM_THIS_OPERATION,
386 ThingsboardErrorCode.PERMISSION_DENIED); 388 ThingsboardErrorCode.PERMISSION_DENIED);
387 } 389 }
388 } 390 }
@@ -403,7 +405,7 @@ public abstract class BaseController { @@ -403,7 +405,7 @@ public abstract class BaseController {
403 if (widgetType.getTenantId() != null && !widgetType.getTenantId().getId().equals(ModelConstants.NULL_UUID)) { 405 if (widgetType.getTenantId() != null && !widgetType.getTenantId().getId().equals(ModelConstants.NULL_UUID)) {
404 checkTenantId(widgetType.getTenantId()); 406 checkTenantId(widgetType.getTenantId());
405 } else if (modify && getCurrentUser().getAuthority() != Authority.SYS_ADMIN) { 407 } else if (modify && getCurrentUser().getAuthority() != Authority.SYS_ADMIN) {
406 - throw new ThingsboardException("You don't have permission to perform this operation!", 408 + throw new ThingsboardException(YOU_DON_T_HAVE_PERMISSION_TO_PERFORM_THIS_OPERATION,
407 ThingsboardErrorCode.PERMISSION_DENIED); 409 ThingsboardErrorCode.PERMISSION_DENIED);
408 } 410 }
409 } 411 }
@@ -437,7 +439,7 @@ public abstract class BaseController { @@ -437,7 +439,7 @@ public abstract class BaseController {
437 SecurityUser authUser = getCurrentUser(); 439 SecurityUser authUser = getCurrentUser();
438 if (authUser.getAuthority() == Authority.CUSTOMER_USER) { 440 if (authUser.getAuthority() == Authority.CUSTOMER_USER) {
439 if (dashboard.getCustomerId() == null || dashboard.getCustomerId().getId().equals(ModelConstants.NULL_UUID)) { 441 if (dashboard.getCustomerId() == null || dashboard.getCustomerId().getId().equals(ModelConstants.NULL_UUID)) {
440 - throw new ThingsboardException("You don't have permission to perform this operation!", 442 + throw new ThingsboardException(YOU_DON_T_HAVE_PERMISSION_TO_PERFORM_THIS_OPERATION,
441 ThingsboardErrorCode.PERMISSION_DENIED); 443 ThingsboardErrorCode.PERMISSION_DENIED);
442 } 444 }
443 } 445 }
@@ -480,11 +482,11 @@ public abstract class BaseController { @@ -480,11 +482,11 @@ public abstract class BaseController {
480 checkNotNull(plugin); 482 checkNotNull(plugin);
481 SecurityUser authUser = getCurrentUser(); 483 SecurityUser authUser = getCurrentUser();
482 TenantId tenantId = plugin.getTenantId(); 484 TenantId tenantId = plugin.getTenantId();
483 - validateId(tenantId, "Incorrect tenantId " + tenantId); 485 + validateId(tenantId, INCORRECT_TENANT_ID + tenantId);
484 if (authUser.getAuthority() != Authority.SYS_ADMIN) { 486 if (authUser.getAuthority() != Authority.SYS_ADMIN) {
485 if (authUser.getTenantId() == null || 487 if (authUser.getTenantId() == null ||
486 !tenantId.getId().equals(ModelConstants.NULL_UUID) && !authUser.getTenantId().equals(tenantId)) { 488 !tenantId.getId().equals(ModelConstants.NULL_UUID) && !authUser.getTenantId().equals(tenantId)) {
487 - throw new ThingsboardException("You don't have permission to perform this operation!", 489 + throw new ThingsboardException(YOU_DON_T_HAVE_PERMISSION_TO_PERFORM_THIS_OPERATION,
488 ThingsboardErrorCode.PERMISSION_DENIED); 490 ThingsboardErrorCode.PERMISSION_DENIED);
489 491
490 } else if (tenantId.getId().equals(ModelConstants.NULL_UUID)) { 492 } else if (tenantId.getId().equals(ModelConstants.NULL_UUID)) {
@@ -508,11 +510,11 @@ public abstract class BaseController { @@ -508,11 +510,11 @@ public abstract class BaseController {
508 checkNotNull(rule); 510 checkNotNull(rule);
509 SecurityUser authUser = getCurrentUser(); 511 SecurityUser authUser = getCurrentUser();
510 TenantId tenantId = rule.getTenantId(); 512 TenantId tenantId = rule.getTenantId();
511 - validateId(tenantId, "Incorrect tenantId " + tenantId); 513 + validateId(tenantId, INCORRECT_TENANT_ID + tenantId);
512 if (authUser.getAuthority() != Authority.SYS_ADMIN) { 514 if (authUser.getAuthority() != Authority.SYS_ADMIN) {
513 if (authUser.getTenantId() == null || 515 if (authUser.getTenantId() == null ||
514 !tenantId.getId().equals(ModelConstants.NULL_UUID) && !authUser.getTenantId().equals(tenantId)) { 516 !tenantId.getId().equals(ModelConstants.NULL_UUID) && !authUser.getTenantId().equals(tenantId)) {
515 - throw new ThingsboardException("You don't have permission to perform this operation!", 517 + throw new ThingsboardException(YOU_DON_T_HAVE_PERMISSION_TO_PERFORM_THIS_OPERATION,
516 ThingsboardErrorCode.PERMISSION_DENIED); 518 ThingsboardErrorCode.PERMISSION_DENIED);
517 519
518 } 520 }
@@ -32,11 +32,14 @@ import org.thingsboard.server.exception.ThingsboardException; @@ -32,11 +32,14 @@ import org.thingsboard.server.exception.ThingsboardException;
32 @RequestMapping("/api") 32 @RequestMapping("/api")
33 public class CustomerController extends BaseController { 33 public class CustomerController extends BaseController {
34 34
  35 + public static final String CUSTOMER_ID = "customerId";
  36 + public static final String IS_PUBLIC = "isPublic";
  37 +
35 @PreAuthorize("hasAnyAuthority('TENANT_ADMIN', 'CUSTOMER_USER')") 38 @PreAuthorize("hasAnyAuthority('TENANT_ADMIN', 'CUSTOMER_USER')")
36 @RequestMapping(value = "/customer/{customerId}", method = RequestMethod.GET) 39 @RequestMapping(value = "/customer/{customerId}", method = RequestMethod.GET)
37 @ResponseBody 40 @ResponseBody
38 - public Customer getCustomerById(@PathVariable("customerId") String strCustomerId) throws ThingsboardException {  
39 - checkParameter("customerId", strCustomerId); 41 + public Customer getCustomerById(@PathVariable(CUSTOMER_ID) String strCustomerId) throws ThingsboardException {
  42 + checkParameter(CUSTOMER_ID, strCustomerId);
40 try { 43 try {
41 CustomerId customerId = new CustomerId(toUUID(strCustomerId)); 44 CustomerId customerId = new CustomerId(toUUID(strCustomerId));
42 return checkCustomerId(customerId); 45 return checkCustomerId(customerId);
@@ -48,15 +51,15 @@ public class CustomerController extends BaseController { @@ -48,15 +51,15 @@ public class CustomerController extends BaseController {
48 @PreAuthorize("hasAnyAuthority('TENANT_ADMIN', 'CUSTOMER_USER')") 51 @PreAuthorize("hasAnyAuthority('TENANT_ADMIN', 'CUSTOMER_USER')")
49 @RequestMapping(value = "/customer/{customerId}/shortInfo", method = RequestMethod.GET) 52 @RequestMapping(value = "/customer/{customerId}/shortInfo", method = RequestMethod.GET)
50 @ResponseBody 53 @ResponseBody
51 - public JsonNode getShortCustomerInfoById(@PathVariable("customerId") String strCustomerId) throws ThingsboardException {  
52 - checkParameter("customerId", strCustomerId); 54 + public JsonNode getShortCustomerInfoById(@PathVariable(CUSTOMER_ID) String strCustomerId) throws ThingsboardException {
  55 + checkParameter(CUSTOMER_ID, strCustomerId);
53 try { 56 try {
54 CustomerId customerId = new CustomerId(toUUID(strCustomerId)); 57 CustomerId customerId = new CustomerId(toUUID(strCustomerId));
55 Customer customer = checkCustomerId(customerId); 58 Customer customer = checkCustomerId(customerId);
56 ObjectMapper objectMapper = new ObjectMapper(); 59 ObjectMapper objectMapper = new ObjectMapper();
57 ObjectNode infoObject = objectMapper.createObjectNode(); 60 ObjectNode infoObject = objectMapper.createObjectNode();
58 infoObject.put("title", customer.getTitle()); 61 infoObject.put("title", customer.getTitle());
59 - infoObject.put("isPublic", customer.isPublic()); 62 + infoObject.put(IS_PUBLIC, customer.isPublic());
60 return infoObject; 63 return infoObject;
61 } catch (Exception e) { 64 } catch (Exception e) {
62 throw handleException(e); 65 throw handleException(e);
@@ -66,8 +69,8 @@ public class CustomerController extends BaseController { @@ -66,8 +69,8 @@ public class CustomerController extends BaseController {
66 @PreAuthorize("hasAnyAuthority('TENANT_ADMIN', 'CUSTOMER_USER')") 69 @PreAuthorize("hasAnyAuthority('TENANT_ADMIN', 'CUSTOMER_USER')")
67 @RequestMapping(value = "/customer/{customerId}/title", method = RequestMethod.GET, produces = "application/text") 70 @RequestMapping(value = "/customer/{customerId}/title", method = RequestMethod.GET, produces = "application/text")
68 @ResponseBody 71 @ResponseBody
69 - public String getCustomerTitleById(@PathVariable("customerId") String strCustomerId) throws ThingsboardException {  
70 - checkParameter("customerId", strCustomerId); 72 + public String getCustomerTitleById(@PathVariable(CUSTOMER_ID) String strCustomerId) throws ThingsboardException {
  73 + checkParameter(CUSTOMER_ID, strCustomerId);
71 try { 74 try {
72 CustomerId customerId = new CustomerId(toUUID(strCustomerId)); 75 CustomerId customerId = new CustomerId(toUUID(strCustomerId));
73 Customer customer = checkCustomerId(customerId); 76 Customer customer = checkCustomerId(customerId);
@@ -92,8 +95,8 @@ public class CustomerController extends BaseController { @@ -92,8 +95,8 @@ public class CustomerController extends BaseController {
92 @PreAuthorize("hasAuthority('TENANT_ADMIN')") 95 @PreAuthorize("hasAuthority('TENANT_ADMIN')")
93 @RequestMapping(value = "/customer/{customerId}", method = RequestMethod.DELETE) 96 @RequestMapping(value = "/customer/{customerId}", method = RequestMethod.DELETE)
94 @ResponseStatus(value = HttpStatus.OK) 97 @ResponseStatus(value = HttpStatus.OK)
95 - public void deleteCustomer(@PathVariable("customerId") String strCustomerId) throws ThingsboardException {  
96 - checkParameter("customerId", strCustomerId); 98 + public void deleteCustomer(@PathVariable(CUSTOMER_ID) String strCustomerId) throws ThingsboardException {
  99 + checkParameter(CUSTOMER_ID, strCustomerId);
97 try { 100 try {
98 CustomerId customerId = new CustomerId(toUUID(strCustomerId)); 101 CustomerId customerId = new CustomerId(toUUID(strCustomerId));
99 checkCustomerId(customerId); 102 checkCustomerId(customerId);
@@ -34,6 +34,8 @@ import org.thingsboard.server.exception.ThingsboardException; @@ -34,6 +34,8 @@ import org.thingsboard.server.exception.ThingsboardException;
34 @RequestMapping("/api") 34 @RequestMapping("/api")
35 public class DashboardController extends BaseController { 35 public class DashboardController extends BaseController {
36 36
  37 + public static final String DASHBOARD_ID = "dashboardId";
  38 +
37 @PreAuthorize("hasAnyAuthority('SYS_ADMIN', 'TENANT_ADMIN', 'CUSTOMER_USER')") 39 @PreAuthorize("hasAnyAuthority('SYS_ADMIN', 'TENANT_ADMIN', 'CUSTOMER_USER')")
38 @RequestMapping(value = "/dashboard/serverTime", method = RequestMethod.GET) 40 @RequestMapping(value = "/dashboard/serverTime", method = RequestMethod.GET)
39 @ResponseBody 41 @ResponseBody
@@ -44,8 +46,8 @@ public class DashboardController extends BaseController { @@ -44,8 +46,8 @@ public class DashboardController extends BaseController {
44 @PreAuthorize("hasAnyAuthority('SYS_ADMIN', 'TENANT_ADMIN', 'CUSTOMER_USER')") 46 @PreAuthorize("hasAnyAuthority('SYS_ADMIN', 'TENANT_ADMIN', 'CUSTOMER_USER')")
45 @RequestMapping(value = "/dashboard/info/{dashboardId}", method = RequestMethod.GET) 47 @RequestMapping(value = "/dashboard/info/{dashboardId}", method = RequestMethod.GET)
46 @ResponseBody 48 @ResponseBody
47 - public DashboardInfo getDashboardInfoById(@PathVariable("dashboardId") String strDashboardId) throws ThingsboardException {  
48 - checkParameter("dashboardId", strDashboardId); 49 + public DashboardInfo getDashboardInfoById(@PathVariable(DASHBOARD_ID) String strDashboardId) throws ThingsboardException {
  50 + checkParameter(DASHBOARD_ID, strDashboardId);
49 try { 51 try {
50 DashboardId dashboardId = new DashboardId(toUUID(strDashboardId)); 52 DashboardId dashboardId = new DashboardId(toUUID(strDashboardId));
51 return checkDashboardInfoId(dashboardId); 53 return checkDashboardInfoId(dashboardId);
@@ -57,8 +59,8 @@ public class DashboardController extends BaseController { @@ -57,8 +59,8 @@ public class DashboardController extends BaseController {
57 @PreAuthorize("hasAnyAuthority('TENANT_ADMIN', 'CUSTOMER_USER')") 59 @PreAuthorize("hasAnyAuthority('TENANT_ADMIN', 'CUSTOMER_USER')")
58 @RequestMapping(value = "/dashboard/{dashboardId}", method = RequestMethod.GET) 60 @RequestMapping(value = "/dashboard/{dashboardId}", method = RequestMethod.GET)
59 @ResponseBody 61 @ResponseBody
60 - public Dashboard getDashboardById(@PathVariable("dashboardId") String strDashboardId) throws ThingsboardException {  
61 - checkParameter("dashboardId", strDashboardId); 62 + public Dashboard getDashboardById(@PathVariable(DASHBOARD_ID) String strDashboardId) throws ThingsboardException {
  63 + checkParameter(DASHBOARD_ID, strDashboardId);
62 try { 64 try {
63 DashboardId dashboardId = new DashboardId(toUUID(strDashboardId)); 65 DashboardId dashboardId = new DashboardId(toUUID(strDashboardId));
64 return checkDashboardId(dashboardId); 66 return checkDashboardId(dashboardId);
@@ -82,8 +84,8 @@ public class DashboardController extends BaseController { @@ -82,8 +84,8 @@ public class DashboardController extends BaseController {
82 @PreAuthorize("hasAuthority('TENANT_ADMIN')") 84 @PreAuthorize("hasAuthority('TENANT_ADMIN')")
83 @RequestMapping(value = "/dashboard/{dashboardId}", method = RequestMethod.DELETE) 85 @RequestMapping(value = "/dashboard/{dashboardId}", method = RequestMethod.DELETE)
84 @ResponseStatus(value = HttpStatus.OK) 86 @ResponseStatus(value = HttpStatus.OK)
85 - public void deleteDashboard(@PathVariable("dashboardId") String strDashboardId) throws ThingsboardException {  
86 - checkParameter("dashboardId", strDashboardId); 87 + public void deleteDashboard(@PathVariable(DASHBOARD_ID) String strDashboardId) throws ThingsboardException {
  88 + checkParameter(DASHBOARD_ID, strDashboardId);
87 try { 89 try {
88 DashboardId dashboardId = new DashboardId(toUUID(strDashboardId)); 90 DashboardId dashboardId = new DashboardId(toUUID(strDashboardId));
89 checkDashboardId(dashboardId); 91 checkDashboardId(dashboardId);
@@ -97,9 +99,9 @@ public class DashboardController extends BaseController { @@ -97,9 +99,9 @@ public class DashboardController extends BaseController {
97 @RequestMapping(value = "/customer/{customerId}/dashboard/{dashboardId}", method = RequestMethod.POST) 99 @RequestMapping(value = "/customer/{customerId}/dashboard/{dashboardId}", method = RequestMethod.POST)
98 @ResponseBody 100 @ResponseBody
99 public Dashboard assignDashboardToCustomer(@PathVariable("customerId") String strCustomerId, 101 public Dashboard assignDashboardToCustomer(@PathVariable("customerId") String strCustomerId,
100 - @PathVariable("dashboardId") String strDashboardId) throws ThingsboardException { 102 + @PathVariable(DASHBOARD_ID) String strDashboardId) throws ThingsboardException {
101 checkParameter("customerId", strCustomerId); 103 checkParameter("customerId", strCustomerId);
102 - checkParameter("dashboardId", strDashboardId); 104 + checkParameter(DASHBOARD_ID, strDashboardId);
103 try { 105 try {
104 CustomerId customerId = new CustomerId(toUUID(strCustomerId)); 106 CustomerId customerId = new CustomerId(toUUID(strCustomerId));
105 checkCustomerId(customerId); 107 checkCustomerId(customerId);
@@ -116,8 +118,8 @@ public class DashboardController extends BaseController { @@ -116,8 +118,8 @@ public class DashboardController extends BaseController {
116 @PreAuthorize("hasAuthority('TENANT_ADMIN')") 118 @PreAuthorize("hasAuthority('TENANT_ADMIN')")
117 @RequestMapping(value = "/customer/dashboard/{dashboardId}", method = RequestMethod.DELETE) 119 @RequestMapping(value = "/customer/dashboard/{dashboardId}", method = RequestMethod.DELETE)
118 @ResponseBody 120 @ResponseBody
119 - public Dashboard unassignDashboardFromCustomer(@PathVariable("dashboardId") String strDashboardId) throws ThingsboardException {  
120 - checkParameter("dashboardId", strDashboardId); 121 + public Dashboard unassignDashboardFromCustomer(@PathVariable(DASHBOARD_ID) String strDashboardId) throws ThingsboardException {
  122 + checkParameter(DASHBOARD_ID, strDashboardId);
121 try { 123 try {
122 DashboardId dashboardId = new DashboardId(toUUID(strDashboardId)); 124 DashboardId dashboardId = new DashboardId(toUUID(strDashboardId));
123 Dashboard dashboard = checkDashboardId(dashboardId); 125 Dashboard dashboard = checkDashboardId(dashboardId);
@@ -133,8 +135,8 @@ public class DashboardController extends BaseController { @@ -133,8 +135,8 @@ public class DashboardController extends BaseController {
133 @PreAuthorize("hasAuthority('TENANT_ADMIN')") 135 @PreAuthorize("hasAuthority('TENANT_ADMIN')")
134 @RequestMapping(value = "/customer/public/dashboard/{dashboardId}", method = RequestMethod.POST) 136 @RequestMapping(value = "/customer/public/dashboard/{dashboardId}", method = RequestMethod.POST)
135 @ResponseBody 137 @ResponseBody
136 - public Dashboard assignDashboardToPublicCustomer(@PathVariable("dashboardId") String strDashboardId) throws ThingsboardException {  
137 - checkParameter("dashboardId", strDashboardId); 138 + public Dashboard assignDashboardToPublicCustomer(@PathVariable(DASHBOARD_ID) String strDashboardId) throws ThingsboardException {
  139 + checkParameter(DASHBOARD_ID, strDashboardId);
138 try { 140 try {
139 DashboardId dashboardId = new DashboardId(toUUID(strDashboardId)); 141 DashboardId dashboardId = new DashboardId(toUUID(strDashboardId));
140 Dashboard dashboard = checkDashboardId(dashboardId); 142 Dashboard dashboard = checkDashboardId(dashboardId);
@@ -44,11 +44,13 @@ import java.util.stream.Collectors; @@ -44,11 +44,13 @@ import java.util.stream.Collectors;
44 @RequestMapping("/api") 44 @RequestMapping("/api")
45 public class DeviceController extends BaseController { 45 public class DeviceController extends BaseController {
46 46
  47 + public static final String DEVICE_ID = "deviceId";
  48 +
47 @PreAuthorize("hasAnyAuthority('TENANT_ADMIN', 'CUSTOMER_USER')") 49 @PreAuthorize("hasAnyAuthority('TENANT_ADMIN', 'CUSTOMER_USER')")
48 @RequestMapping(value = "/device/{deviceId}", method = RequestMethod.GET) 50 @RequestMapping(value = "/device/{deviceId}", method = RequestMethod.GET)
49 @ResponseBody 51 @ResponseBody
50 - public Device getDeviceById(@PathVariable("deviceId") String strDeviceId) throws ThingsboardException {  
51 - checkParameter("deviceId", strDeviceId); 52 + public Device getDeviceById(@PathVariable(DEVICE_ID) String strDeviceId) throws ThingsboardException {
  53 + checkParameter(DEVICE_ID, strDeviceId);
52 try { 54 try {
53 DeviceId deviceId = new DeviceId(toUUID(strDeviceId)); 55 DeviceId deviceId = new DeviceId(toUUID(strDeviceId));
54 return checkDeviceId(deviceId); 56 return checkDeviceId(deviceId);
@@ -88,8 +90,8 @@ public class DeviceController extends BaseController { @@ -88,8 +90,8 @@ public class DeviceController extends BaseController {
88 @PreAuthorize("hasAuthority('TENANT_ADMIN')") 90 @PreAuthorize("hasAuthority('TENANT_ADMIN')")
89 @RequestMapping(value = "/device/{deviceId}", method = RequestMethod.DELETE) 91 @RequestMapping(value = "/device/{deviceId}", method = RequestMethod.DELETE)
90 @ResponseStatus(value = HttpStatus.OK) 92 @ResponseStatus(value = HttpStatus.OK)
91 - public void deleteDevice(@PathVariable("deviceId") String strDeviceId) throws ThingsboardException {  
92 - checkParameter("deviceId", strDeviceId); 93 + public void deleteDevice(@PathVariable(DEVICE_ID) String strDeviceId) throws ThingsboardException {
  94 + checkParameter(DEVICE_ID, strDeviceId);
93 try { 95 try {
94 DeviceId deviceId = new DeviceId(toUUID(strDeviceId)); 96 DeviceId deviceId = new DeviceId(toUUID(strDeviceId));
95 checkDeviceId(deviceId); 97 checkDeviceId(deviceId);
@@ -103,9 +105,9 @@ public class DeviceController extends BaseController { @@ -103,9 +105,9 @@ public class DeviceController extends BaseController {
103 @RequestMapping(value = "/customer/{customerId}/device/{deviceId}", method = RequestMethod.POST) 105 @RequestMapping(value = "/customer/{customerId}/device/{deviceId}", method = RequestMethod.POST)
104 @ResponseBody 106 @ResponseBody
105 public Device assignDeviceToCustomer(@PathVariable("customerId") String strCustomerId, 107 public Device assignDeviceToCustomer(@PathVariable("customerId") String strCustomerId,
106 - @PathVariable("deviceId") String strDeviceId) throws ThingsboardException { 108 + @PathVariable(DEVICE_ID) String strDeviceId) throws ThingsboardException {
107 checkParameter("customerId", strCustomerId); 109 checkParameter("customerId", strCustomerId);
108 - checkParameter("deviceId", strDeviceId); 110 + checkParameter(DEVICE_ID, strDeviceId);
109 try { 111 try {
110 CustomerId customerId = new CustomerId(toUUID(strCustomerId)); 112 CustomerId customerId = new CustomerId(toUUID(strCustomerId));
111 checkCustomerId(customerId); 113 checkCustomerId(customerId);
@@ -122,8 +124,8 @@ public class DeviceController extends BaseController { @@ -122,8 +124,8 @@ public class DeviceController extends BaseController {
122 @PreAuthorize("hasAuthority('TENANT_ADMIN')") 124 @PreAuthorize("hasAuthority('TENANT_ADMIN')")
123 @RequestMapping(value = "/customer/device/{deviceId}", method = RequestMethod.DELETE) 125 @RequestMapping(value = "/customer/device/{deviceId}", method = RequestMethod.DELETE)
124 @ResponseBody 126 @ResponseBody
125 - public Device unassignDeviceFromCustomer(@PathVariable("deviceId") String strDeviceId) throws ThingsboardException {  
126 - checkParameter("deviceId", strDeviceId); 127 + public Device unassignDeviceFromCustomer(@PathVariable(DEVICE_ID) String strDeviceId) throws ThingsboardException {
  128 + checkParameter(DEVICE_ID, strDeviceId);
127 try { 129 try {
128 DeviceId deviceId = new DeviceId(toUUID(strDeviceId)); 130 DeviceId deviceId = new DeviceId(toUUID(strDeviceId));
129 Device device = checkDeviceId(deviceId); 131 Device device = checkDeviceId(deviceId);
@@ -139,8 +141,8 @@ public class DeviceController extends BaseController { @@ -139,8 +141,8 @@ public class DeviceController extends BaseController {
139 @PreAuthorize("hasAuthority('TENANT_ADMIN')") 141 @PreAuthorize("hasAuthority('TENANT_ADMIN')")
140 @RequestMapping(value = "/customer/public/device/{deviceId}", method = RequestMethod.POST) 142 @RequestMapping(value = "/customer/public/device/{deviceId}", method = RequestMethod.POST)
141 @ResponseBody 143 @ResponseBody
142 - public Device assignDeviceToPublicCustomer(@PathVariable("deviceId") String strDeviceId) throws ThingsboardException {  
143 - checkParameter("deviceId", strDeviceId); 144 + public Device assignDeviceToPublicCustomer(@PathVariable(DEVICE_ID) String strDeviceId) throws ThingsboardException {
  145 + checkParameter(DEVICE_ID, strDeviceId);
144 try { 146 try {
145 DeviceId deviceId = new DeviceId(toUUID(strDeviceId)); 147 DeviceId deviceId = new DeviceId(toUUID(strDeviceId));
146 Device device = checkDeviceId(deviceId); 148 Device device = checkDeviceId(deviceId);
@@ -154,8 +156,8 @@ public class DeviceController extends BaseController { @@ -154,8 +156,8 @@ public class DeviceController extends BaseController {
154 @PreAuthorize("hasAnyAuthority('TENANT_ADMIN', 'CUSTOMER_USER')") 156 @PreAuthorize("hasAnyAuthority('TENANT_ADMIN', 'CUSTOMER_USER')")
155 @RequestMapping(value = "/device/{deviceId}/credentials", method = RequestMethod.GET) 157 @RequestMapping(value = "/device/{deviceId}/credentials", method = RequestMethod.GET)
156 @ResponseBody 158 @ResponseBody
157 - public DeviceCredentials getDeviceCredentialsByDeviceId(@PathVariable("deviceId") String strDeviceId) throws ThingsboardException {  
158 - checkParameter("deviceId", strDeviceId); 159 + public DeviceCredentials getDeviceCredentialsByDeviceId(@PathVariable(DEVICE_ID) String strDeviceId) throws ThingsboardException {
  160 + checkParameter(DEVICE_ID, strDeviceId);
159 try { 161 try {
160 DeviceId deviceId = new DeviceId(toUUID(strDeviceId)); 162 DeviceId deviceId = new DeviceId(toUUID(strDeviceId));
161 checkDeviceId(deviceId); 163 checkDeviceId(deviceId);
@@ -34,6 +34,12 @@ import java.util.List; @@ -34,6 +34,12 @@ import java.util.List;
34 @RequestMapping("/api") 34 @RequestMapping("/api")
35 public class EntityRelationController extends BaseController { 35 public class EntityRelationController extends BaseController {
36 36
  37 + public static final String TO_TYPE = "toType";
  38 + public static final String FROM_ID = "fromId";
  39 + public static final String FROM_TYPE = "fromType";
  40 + public static final String RELATION_TYPE = "relationType";
  41 + public static final String TO_ID = "toId";
  42 +
37 @PreAuthorize("hasAnyAuthority('SYS_ADMIN', 'TENANT_ADMIN', 'CUSTOMER_USER')") 43 @PreAuthorize("hasAnyAuthority('SYS_ADMIN', 'TENANT_ADMIN', 'CUSTOMER_USER')")
38 @RequestMapping(value = "/relation", method = RequestMethod.POST) 44 @RequestMapping(value = "/relation", method = RequestMethod.POST)
39 @ResponseStatus(value = HttpStatus.OK) 45 @ResponseStatus(value = HttpStatus.OK)
@@ -45,32 +51,32 @@ public class EntityRelationController extends BaseController { @@ -45,32 +51,32 @@ public class EntityRelationController extends BaseController {
45 if (relation.getTypeGroup() == null) { 51 if (relation.getTypeGroup() == null) {
46 relation.setTypeGroup(RelationTypeGroup.COMMON); 52 relation.setTypeGroup(RelationTypeGroup.COMMON);
47 } 53 }
48 - relationService.saveRelation(relation).get(); 54 + relationService.saveRelation(relation);
49 } catch (Exception e) { 55 } catch (Exception e) {
50 throw handleException(e); 56 throw handleException(e);
51 } 57 }
52 } 58 }
53 59
54 @PreAuthorize("hasAnyAuthority('SYS_ADMIN', 'TENANT_ADMIN', 'CUSTOMER_USER')") 60 @PreAuthorize("hasAnyAuthority('SYS_ADMIN', 'TENANT_ADMIN', 'CUSTOMER_USER')")
55 - @RequestMapping(value = "/relation", method = RequestMethod.DELETE, params = {"fromId", "fromType", "relationType", "toId", "toType"}) 61 + @RequestMapping(value = "/relation", method = RequestMethod.DELETE, params = {FROM_ID, FROM_TYPE, RELATION_TYPE, TO_ID, TO_TYPE})
56 @ResponseStatus(value = HttpStatus.OK) 62 @ResponseStatus(value = HttpStatus.OK)
57 - public void deleteRelation(@RequestParam("fromId") String strFromId,  
58 - @RequestParam("fromType") String strFromType,  
59 - @RequestParam("relationType") String strRelationType, 63 + public void deleteRelation(@RequestParam(FROM_ID) String strFromId,
  64 + @RequestParam(FROM_TYPE) String strFromType,
  65 + @RequestParam(RELATION_TYPE) String strRelationType,
60 @RequestParam(value = "relationTypeGroup", required = false) String strRelationTypeGroup, 66 @RequestParam(value = "relationTypeGroup", required = false) String strRelationTypeGroup,
61 - @RequestParam("toId") String strToId, @RequestParam("toType") String strToType) throws ThingsboardException {  
62 - checkParameter("fromId", strFromId);  
63 - checkParameter("fromType", strFromType);  
64 - checkParameter("relationType", strRelationType);  
65 - checkParameter("toId", strToId);  
66 - checkParameter("toType", strToType); 67 + @RequestParam(TO_ID) String strToId, @RequestParam(TO_TYPE) String strToType) throws ThingsboardException {
  68 + checkParameter(FROM_ID, strFromId);
  69 + checkParameter(FROM_TYPE, strFromType);
  70 + checkParameter(RELATION_TYPE, strRelationType);
  71 + checkParameter(TO_ID, strToId);
  72 + checkParameter(TO_TYPE, strToType);
67 EntityId fromId = EntityIdFactory.getByTypeAndId(strFromType, strFromId); 73 EntityId fromId = EntityIdFactory.getByTypeAndId(strFromType, strFromId);
68 EntityId toId = EntityIdFactory.getByTypeAndId(strToType, strToId); 74 EntityId toId = EntityIdFactory.getByTypeAndId(strToType, strToId);
69 checkEntityId(fromId); 75 checkEntityId(fromId);
70 checkEntityId(toId); 76 checkEntityId(toId);
71 RelationTypeGroup relationTypeGroup = parseRelationTypeGroup(strRelationTypeGroup, RelationTypeGroup.COMMON); 77 RelationTypeGroup relationTypeGroup = parseRelationTypeGroup(strRelationTypeGroup, RelationTypeGroup.COMMON);
72 try { 78 try {
73 - Boolean found = relationService.deleteRelation(fromId, toId, strRelationType, relationTypeGroup).get(); 79 + Boolean found = relationService.deleteRelation(fromId, toId, strRelationType, relationTypeGroup);
74 if (!found) { 80 if (!found) {
75 throw new ThingsboardException("Requested item wasn't found!", ThingsboardErrorCode.ITEM_NOT_FOUND); 81 throw new ThingsboardException("Requested item wasn't found!", ThingsboardErrorCode.ITEM_NOT_FOUND);
76 } 82 }
@@ -89,26 +95,26 @@ public class EntityRelationController extends BaseController { @@ -89,26 +95,26 @@ public class EntityRelationController extends BaseController {
89 EntityId entityId = EntityIdFactory.getByTypeAndId(strType, strId); 95 EntityId entityId = EntityIdFactory.getByTypeAndId(strType, strId);
90 checkEntityId(entityId); 96 checkEntityId(entityId);
91 try { 97 try {
92 - relationService.deleteEntityRelations(entityId).get(); 98 + relationService.deleteEntityRelations(entityId);
93 } catch (Exception e) { 99 } catch (Exception e) {
94 throw handleException(e); 100 throw handleException(e);
95 } 101 }
96 } 102 }
97 103
98 @PreAuthorize("hasAnyAuthority('SYS_ADMIN', 'TENANT_ADMIN', 'CUSTOMER_USER')") 104 @PreAuthorize("hasAnyAuthority('SYS_ADMIN', 'TENANT_ADMIN', 'CUSTOMER_USER')")
99 - @RequestMapping(value = "/relation", method = RequestMethod.GET, params = {"fromId", "fromType", "relationType", "toId", "toType"}) 105 + @RequestMapping(value = "/relation", method = RequestMethod.GET, params = {FROM_ID, FROM_TYPE, RELATION_TYPE, TO_ID, TO_TYPE})
100 @ResponseBody 106 @ResponseBody
101 - public EntityRelation getRelation(@RequestParam("fromId") String strFromId,  
102 - @RequestParam("fromType") String strFromType,  
103 - @RequestParam("relationType") String strRelationType,  
104 - @RequestParam(value = "relationTypeGroup", required = false) String strRelationTypeGroup,  
105 - @RequestParam("toId") String strToId, @RequestParam("toType") String strToType) throws ThingsboardException { 107 + public EntityRelation getRelation(@RequestParam(FROM_ID) String strFromId,
  108 + @RequestParam(FROM_TYPE) String strFromType,
  109 + @RequestParam(RELATION_TYPE) String strRelationType,
  110 + @RequestParam(value = "relationTypeGroup", required = false) String strRelationTypeGroup,
  111 + @RequestParam(TO_ID) String strToId, @RequestParam(TO_TYPE) String strToType) throws ThingsboardException {
106 try { 112 try {
107 - checkParameter("fromId", strFromId);  
108 - checkParameter("fromType", strFromType);  
109 - checkParameter("relationType", strRelationType);  
110 - checkParameter("toId", strToId);  
111 - checkParameter("toType", strToType); 113 + checkParameter(FROM_ID, strFromId);
  114 + checkParameter(FROM_TYPE, strFromType);
  115 + checkParameter(RELATION_TYPE, strRelationType);
  116 + checkParameter(TO_ID, strToId);
  117 + checkParameter(TO_TYPE, strToType);
112 EntityId fromId = EntityIdFactory.getByTypeAndId(strFromType, strFromId); 118 EntityId fromId = EntityIdFactory.getByTypeAndId(strFromType, strFromId);
113 EntityId toId = EntityIdFactory.getByTypeAndId(strToType, strToId); 119 EntityId toId = EntityIdFactory.getByTypeAndId(strToType, strToId);
114 checkEntityId(fromId); 120 checkEntityId(fromId);
@@ -121,13 +127,13 @@ public class EntityRelationController extends BaseController { @@ -121,13 +127,13 @@ public class EntityRelationController extends BaseController {
121 } 127 }
122 128
123 @PreAuthorize("hasAnyAuthority('SYS_ADMIN', 'TENANT_ADMIN', 'CUSTOMER_USER')") 129 @PreAuthorize("hasAnyAuthority('SYS_ADMIN', 'TENANT_ADMIN', 'CUSTOMER_USER')")
124 - @RequestMapping(value = "/relations", method = RequestMethod.GET, params = {"fromId", "fromType"}) 130 + @RequestMapping(value = "/relations", method = RequestMethod.GET, params = {FROM_ID, FROM_TYPE})
125 @ResponseBody 131 @ResponseBody
126 - public List<EntityRelation> findByFrom(@RequestParam("fromId") String strFromId,  
127 - @RequestParam("fromType") String strFromType, 132 + public List<EntityRelation> findByFrom(@RequestParam(FROM_ID) String strFromId,
  133 + @RequestParam(FROM_TYPE) String strFromType,
128 @RequestParam(value = "relationTypeGroup", required = false) String strRelationTypeGroup) throws ThingsboardException { 134 @RequestParam(value = "relationTypeGroup", required = false) String strRelationTypeGroup) throws ThingsboardException {
129 - checkParameter("fromId", strFromId);  
130 - checkParameter("fromType", strFromType); 135 + checkParameter(FROM_ID, strFromId);
  136 + checkParameter(FROM_TYPE, strFromType);
131 EntityId entityId = EntityIdFactory.getByTypeAndId(strFromType, strFromId); 137 EntityId entityId = EntityIdFactory.getByTypeAndId(strFromType, strFromId);
132 checkEntityId(entityId); 138 checkEntityId(entityId);
133 RelationTypeGroup typeGroup = parseRelationTypeGroup(strRelationTypeGroup, RelationTypeGroup.COMMON); 139 RelationTypeGroup typeGroup = parseRelationTypeGroup(strRelationTypeGroup, RelationTypeGroup.COMMON);
@@ -139,13 +145,13 @@ public class EntityRelationController extends BaseController { @@ -139,13 +145,13 @@ public class EntityRelationController extends BaseController {
139 } 145 }
140 146
141 @PreAuthorize("hasAnyAuthority('SYS_ADMIN', 'TENANT_ADMIN', 'CUSTOMER_USER')") 147 @PreAuthorize("hasAnyAuthority('SYS_ADMIN', 'TENANT_ADMIN', 'CUSTOMER_USER')")
142 - @RequestMapping(value = "/relations/info", method = RequestMethod.GET, params = {"fromId", "fromType"}) 148 + @RequestMapping(value = "/relations/info", method = RequestMethod.GET, params = {FROM_ID, FROM_TYPE})
143 @ResponseBody 149 @ResponseBody
144 - public List<EntityRelationInfo> findInfoByFrom(@RequestParam("fromId") String strFromId,  
145 - @RequestParam("fromType") String strFromType, 150 + public List<EntityRelationInfo> findInfoByFrom(@RequestParam(FROM_ID) String strFromId,
  151 + @RequestParam(FROM_TYPE) String strFromType,
146 @RequestParam(value = "relationTypeGroup", required = false) String strRelationTypeGroup) throws ThingsboardException { 152 @RequestParam(value = "relationTypeGroup", required = false) String strRelationTypeGroup) throws ThingsboardException {
147 - checkParameter("fromId", strFromId);  
148 - checkParameter("fromType", strFromType); 153 + checkParameter(FROM_ID, strFromId);
  154 + checkParameter(FROM_TYPE, strFromType);
149 EntityId entityId = EntityIdFactory.getByTypeAndId(strFromType, strFromId); 155 EntityId entityId = EntityIdFactory.getByTypeAndId(strFromType, strFromId);
150 checkEntityId(entityId); 156 checkEntityId(entityId);
151 RelationTypeGroup typeGroup = parseRelationTypeGroup(strRelationTypeGroup, RelationTypeGroup.COMMON); 157 RelationTypeGroup typeGroup = parseRelationTypeGroup(strRelationTypeGroup, RelationTypeGroup.COMMON);
@@ -157,15 +163,15 @@ public class EntityRelationController extends BaseController { @@ -157,15 +163,15 @@ public class EntityRelationController extends BaseController {
157 } 163 }
158 164
159 @PreAuthorize("hasAnyAuthority('SYS_ADMIN', 'TENANT_ADMIN', 'CUSTOMER_USER')") 165 @PreAuthorize("hasAnyAuthority('SYS_ADMIN', 'TENANT_ADMIN', 'CUSTOMER_USER')")
160 - @RequestMapping(value = "/relations", method = RequestMethod.GET, params = {"fromId", "fromType", "relationType"}) 166 + @RequestMapping(value = "/relations", method = RequestMethod.GET, params = {FROM_ID, FROM_TYPE, RELATION_TYPE})
161 @ResponseBody 167 @ResponseBody
162 - public List<EntityRelation> findByFrom(@RequestParam("fromId") String strFromId,  
163 - @RequestParam("fromType") String strFromType,  
164 - @RequestParam("relationType") String strRelationType, 168 + public List<EntityRelation> findByFrom(@RequestParam(FROM_ID) String strFromId,
  169 + @RequestParam(FROM_TYPE) String strFromType,
  170 + @RequestParam(RELATION_TYPE) String strRelationType,
165 @RequestParam(value = "relationTypeGroup", required = false) String strRelationTypeGroup) throws ThingsboardException { 171 @RequestParam(value = "relationTypeGroup", required = false) String strRelationTypeGroup) throws ThingsboardException {
166 - checkParameter("fromId", strFromId);  
167 - checkParameter("fromType", strFromType);  
168 - checkParameter("relationType", strRelationType); 172 + checkParameter(FROM_ID, strFromId);
  173 + checkParameter(FROM_TYPE, strFromType);
  174 + checkParameter(RELATION_TYPE, strRelationType);
169 EntityId entityId = EntityIdFactory.getByTypeAndId(strFromType, strFromId); 175 EntityId entityId = EntityIdFactory.getByTypeAndId(strFromType, strFromId);
170 checkEntityId(entityId); 176 checkEntityId(entityId);
171 RelationTypeGroup typeGroup = parseRelationTypeGroup(strRelationTypeGroup, RelationTypeGroup.COMMON); 177 RelationTypeGroup typeGroup = parseRelationTypeGroup(strRelationTypeGroup, RelationTypeGroup.COMMON);
@@ -177,13 +183,13 @@ public class EntityRelationController extends BaseController { @@ -177,13 +183,13 @@ public class EntityRelationController extends BaseController {
177 } 183 }
178 184
179 @PreAuthorize("hasAnyAuthority('SYS_ADMIN', 'TENANT_ADMIN', 'CUSTOMER_USER')") 185 @PreAuthorize("hasAnyAuthority('SYS_ADMIN', 'TENANT_ADMIN', 'CUSTOMER_USER')")
180 - @RequestMapping(value = "/relations", method = RequestMethod.GET, params = {"toId", "toType"}) 186 + @RequestMapping(value = "/relations", method = RequestMethod.GET, params = {TO_ID, TO_TYPE})
181 @ResponseBody 187 @ResponseBody
182 - public List<EntityRelation> findByTo(@RequestParam("toId") String strToId,  
183 - @RequestParam("toType") String strToType, 188 + public List<EntityRelation> findByTo(@RequestParam(TO_ID) String strToId,
  189 + @RequestParam(TO_TYPE) String strToType,
184 @RequestParam(value = "relationTypeGroup", required = false) String strRelationTypeGroup) throws ThingsboardException { 190 @RequestParam(value = "relationTypeGroup", required = false) String strRelationTypeGroup) throws ThingsboardException {
185 - checkParameter("toId", strToId);  
186 - checkParameter("toType", strToType); 191 + checkParameter(TO_ID, strToId);
  192 + checkParameter(TO_TYPE, strToType);
187 EntityId entityId = EntityIdFactory.getByTypeAndId(strToType, strToId); 193 EntityId entityId = EntityIdFactory.getByTypeAndId(strToType, strToId);
188 checkEntityId(entityId); 194 checkEntityId(entityId);
189 RelationTypeGroup typeGroup = parseRelationTypeGroup(strRelationTypeGroup, RelationTypeGroup.COMMON); 195 RelationTypeGroup typeGroup = parseRelationTypeGroup(strRelationTypeGroup, RelationTypeGroup.COMMON);
@@ -195,13 +201,13 @@ public class EntityRelationController extends BaseController { @@ -195,13 +201,13 @@ public class EntityRelationController extends BaseController {
195 } 201 }
196 202
197 @PreAuthorize("hasAnyAuthority('SYS_ADMIN', 'TENANT_ADMIN', 'CUSTOMER_USER')") 203 @PreAuthorize("hasAnyAuthority('SYS_ADMIN', 'TENANT_ADMIN', 'CUSTOMER_USER')")
198 - @RequestMapping(value = "/relations/info", method = RequestMethod.GET, params = {"toId", "toType"}) 204 + @RequestMapping(value = "/relations/info", method = RequestMethod.GET, params = {TO_ID, TO_TYPE})
199 @ResponseBody 205 @ResponseBody
200 - public List<EntityRelationInfo> findInfoByTo(@RequestParam("toId") String strToId,  
201 - @RequestParam("toType") String strToType, 206 + public List<EntityRelationInfo> findInfoByTo(@RequestParam(TO_ID) String strToId,
  207 + @RequestParam(TO_TYPE) String strToType,
202 @RequestParam(value = "relationTypeGroup", required = false) String strRelationTypeGroup) throws ThingsboardException { 208 @RequestParam(value = "relationTypeGroup", required = false) String strRelationTypeGroup) throws ThingsboardException {
203 - checkParameter("toId", strToId);  
204 - checkParameter("toType", strToType); 209 + checkParameter(TO_ID, strToId);
  210 + checkParameter(TO_TYPE, strToType);
205 EntityId entityId = EntityIdFactory.getByTypeAndId(strToType, strToId); 211 EntityId entityId = EntityIdFactory.getByTypeAndId(strToType, strToId);
206 checkEntityId(entityId); 212 checkEntityId(entityId);
207 RelationTypeGroup typeGroup = parseRelationTypeGroup(strRelationTypeGroup, RelationTypeGroup.COMMON); 213 RelationTypeGroup typeGroup = parseRelationTypeGroup(strRelationTypeGroup, RelationTypeGroup.COMMON);
@@ -213,15 +219,15 @@ public class EntityRelationController extends BaseController { @@ -213,15 +219,15 @@ public class EntityRelationController extends BaseController {
213 } 219 }
214 220
215 @PreAuthorize("hasAnyAuthority('SYS_ADMIN', 'TENANT_ADMIN', 'CUSTOMER_USER')") 221 @PreAuthorize("hasAnyAuthority('SYS_ADMIN', 'TENANT_ADMIN', 'CUSTOMER_USER')")
216 - @RequestMapping(value = "/relations", method = RequestMethod.GET, params = {"toId", "toType", "relationType"}) 222 + @RequestMapping(value = "/relations", method = RequestMethod.GET, params = {TO_ID, TO_TYPE, RELATION_TYPE})
217 @ResponseBody 223 @ResponseBody
218 - public List<EntityRelation> findByTo(@RequestParam("toId") String strToId,  
219 - @RequestParam("toType") String strToType,  
220 - @RequestParam("relationType") String strRelationType, 224 + public List<EntityRelation> findByTo(@RequestParam(TO_ID) String strToId,
  225 + @RequestParam(TO_TYPE) String strToType,
  226 + @RequestParam(RELATION_TYPE) String strRelationType,
221 @RequestParam(value = "relationTypeGroup", required = false) String strRelationTypeGroup) throws ThingsboardException { 227 @RequestParam(value = "relationTypeGroup", required = false) String strRelationTypeGroup) throws ThingsboardException {
222 - checkParameter("toId", strToId);  
223 - checkParameter("toType", strToType);  
224 - checkParameter("relationType", strRelationType); 228 + checkParameter(TO_ID, strToId);
  229 + checkParameter(TO_TYPE, strToType);
  230 + checkParameter(RELATION_TYPE, strRelationType);
225 EntityId entityId = EntityIdFactory.getByTypeAndId(strToType, strToId); 231 EntityId entityId = EntityIdFactory.getByTypeAndId(strToType, strToId);
226 checkEntityId(entityId); 232 checkEntityId(entityId);
227 RelationTypeGroup typeGroup = parseRelationTypeGroup(strRelationTypeGroup, RelationTypeGroup.COMMON); 233 RelationTypeGroup typeGroup = parseRelationTypeGroup(strRelationTypeGroup, RelationTypeGroup.COMMON);
@@ -267,9 +273,7 @@ public class EntityRelationController extends BaseController { @@ -267,9 +273,7 @@ public class EntityRelationController extends BaseController {
267 if (strRelationTypeGroup != null && strRelationTypeGroup.trim().length()>0) { 273 if (strRelationTypeGroup != null && strRelationTypeGroup.trim().length()>0) {
268 try { 274 try {
269 result = RelationTypeGroup.valueOf(strRelationTypeGroup); 275 result = RelationTypeGroup.valueOf(strRelationTypeGroup);
270 - } catch (IllegalArgumentException e) {  
271 - result = defaultValue;  
272 - } 276 + } catch (IllegalArgumentException e) { }
273 } 277 }
274 return result; 278 return result;
275 } 279 }
@@ -34,11 +34,13 @@ import java.util.List; @@ -34,11 +34,13 @@ import java.util.List;
34 @RequestMapping("/api") 34 @RequestMapping("/api")
35 public class PluginController extends BaseController { 35 public class PluginController extends BaseController {
36 36
  37 + public static final String PLUGIN_ID = "pluginId";
  38 +
37 @PreAuthorize("hasAnyAuthority('SYS_ADMIN', 'TENANT_ADMIN')") 39 @PreAuthorize("hasAnyAuthority('SYS_ADMIN', 'TENANT_ADMIN')")
38 @RequestMapping(value = "/plugin/{pluginId}", method = RequestMethod.GET) 40 @RequestMapping(value = "/plugin/{pluginId}", method = RequestMethod.GET)
39 @ResponseBody 41 @ResponseBody
40 - public PluginMetaData getPluginById(@PathVariable("pluginId") String strPluginId) throws ThingsboardException {  
41 - checkParameter("pluginId", strPluginId); 42 + public PluginMetaData getPluginById(@PathVariable(PLUGIN_ID) String strPluginId) throws ThingsboardException {
  43 + checkParameter(PLUGIN_ID, strPluginId);
42 try { 44 try {
43 PluginId pluginId = new PluginId(toUUID(strPluginId)); 45 PluginId pluginId = new PluginId(toUUID(strPluginId));
44 return checkPlugin(pluginService.findPluginById(pluginId)); 46 return checkPlugin(pluginService.findPluginById(pluginId));
@@ -78,8 +80,8 @@ public class PluginController extends BaseController { @@ -78,8 +80,8 @@ public class PluginController extends BaseController {
78 @PreAuthorize("hasAnyAuthority('SYS_ADMIN', 'TENANT_ADMIN')") 80 @PreAuthorize("hasAnyAuthority('SYS_ADMIN', 'TENANT_ADMIN')")
79 @RequestMapping(value = "/plugin/{pluginId}/activate", method = RequestMethod.POST) 81 @RequestMapping(value = "/plugin/{pluginId}/activate", method = RequestMethod.POST)
80 @ResponseStatus(value = HttpStatus.OK) 82 @ResponseStatus(value = HttpStatus.OK)
81 - public void activatePluginById(@PathVariable("pluginId") String strPluginId) throws ThingsboardException {  
82 - checkParameter("pluginId", strPluginId); 83 + public void activatePluginById(@PathVariable(PLUGIN_ID) String strPluginId) throws ThingsboardException {
  84 + checkParameter(PLUGIN_ID, strPluginId);
83 try { 85 try {
84 PluginId pluginId = new PluginId(toUUID(strPluginId)); 86 PluginId pluginId = new PluginId(toUUID(strPluginId));
85 PluginMetaData plugin = checkPlugin(pluginService.findPluginById(pluginId)); 87 PluginMetaData plugin = checkPlugin(pluginService.findPluginById(pluginId));
@@ -93,8 +95,8 @@ public class PluginController extends BaseController { @@ -93,8 +95,8 @@ public class PluginController extends BaseController {
93 @PreAuthorize("hasAnyAuthority('SYS_ADMIN', 'TENANT_ADMIN')") 95 @PreAuthorize("hasAnyAuthority('SYS_ADMIN', 'TENANT_ADMIN')")
94 @RequestMapping(value = "/plugin/{pluginId}/suspend", method = RequestMethod.POST) 96 @RequestMapping(value = "/plugin/{pluginId}/suspend", method = RequestMethod.POST)
95 @ResponseStatus(value = HttpStatus.OK) 97 @ResponseStatus(value = HttpStatus.OK)
96 - public void suspendPluginById(@PathVariable("pluginId") String strPluginId) throws ThingsboardException {  
97 - checkParameter("pluginId", strPluginId); 98 + public void suspendPluginById(@PathVariable(PLUGIN_ID) String strPluginId) throws ThingsboardException {
  99 + checkParameter(PLUGIN_ID, strPluginId);
98 try { 100 try {
99 PluginId pluginId = new PluginId(toUUID(strPluginId)); 101 PluginId pluginId = new PluginId(toUUID(strPluginId));
100 PluginMetaData plugin = checkPlugin(pluginService.findPluginById(pluginId)); 102 PluginMetaData plugin = checkPlugin(pluginService.findPluginById(pluginId));
@@ -180,8 +182,8 @@ public class PluginController extends BaseController { @@ -180,8 +182,8 @@ public class PluginController extends BaseController {
180 @PreAuthorize("hasAnyAuthority('SYS_ADMIN', 'TENANT_ADMIN')") 182 @PreAuthorize("hasAnyAuthority('SYS_ADMIN', 'TENANT_ADMIN')")
181 @RequestMapping(value = "/plugin/{pluginId}", method = RequestMethod.DELETE) 183 @RequestMapping(value = "/plugin/{pluginId}", method = RequestMethod.DELETE)
182 @ResponseStatus(value = HttpStatus.OK) 184 @ResponseStatus(value = HttpStatus.OK)
183 - public void deletePlugin(@PathVariable("pluginId") String strPluginId) throws ThingsboardException {  
184 - checkParameter("pluginId", strPluginId); 185 + public void deletePlugin(@PathVariable(PLUGIN_ID) String strPluginId) throws ThingsboardException {
  186 + checkParameter(PLUGIN_ID, strPluginId);
185 try { 187 try {
186 PluginId pluginId = new PluginId(toUUID(strPluginId)); 188 PluginId pluginId = new PluginId(toUUID(strPluginId));
187 PluginMetaData plugin = checkPlugin(pluginService.findPluginById(pluginId)); 189 PluginMetaData plugin = checkPlugin(pluginService.findPluginById(pluginId));
@@ -34,11 +34,13 @@ import java.util.List; @@ -34,11 +34,13 @@ import java.util.List;
34 @RequestMapping("/api") 34 @RequestMapping("/api")
35 public class RuleController extends BaseController { 35 public class RuleController extends BaseController {
36 36
  37 + public static final String RULE_ID = "ruleId";
  38 +
37 @PreAuthorize("hasAnyAuthority('SYS_ADMIN', 'TENANT_ADMIN')") 39 @PreAuthorize("hasAnyAuthority('SYS_ADMIN', 'TENANT_ADMIN')")
38 @RequestMapping(value = "/rule/{ruleId}", method = RequestMethod.GET) 40 @RequestMapping(value = "/rule/{ruleId}", method = RequestMethod.GET)
39 @ResponseBody 41 @ResponseBody
40 - public RuleMetaData getRuleById(@PathVariable("ruleId") String strRuleId) throws ThingsboardException {  
41 - checkParameter("ruleId", strRuleId); 42 + public RuleMetaData getRuleById(@PathVariable(RULE_ID) String strRuleId) throws ThingsboardException {
  43 + checkParameter(RULE_ID, strRuleId);
42 try { 44 try {
43 RuleId ruleId = new RuleId(toUUID(strRuleId)); 45 RuleId ruleId = new RuleId(toUUID(strRuleId));
44 return checkRule(ruleService.findRuleById(ruleId)); 46 return checkRule(ruleService.findRuleById(ruleId));
@@ -80,8 +82,8 @@ public class RuleController extends BaseController { @@ -80,8 +82,8 @@ public class RuleController extends BaseController {
80 @PreAuthorize("hasAnyAuthority('SYS_ADMIN', 'TENANT_ADMIN')") 82 @PreAuthorize("hasAnyAuthority('SYS_ADMIN', 'TENANT_ADMIN')")
81 @RequestMapping(value = "/rule/{ruleId}/activate", method = RequestMethod.POST) 83 @RequestMapping(value = "/rule/{ruleId}/activate", method = RequestMethod.POST)
82 @ResponseStatus(value = HttpStatus.OK) 84 @ResponseStatus(value = HttpStatus.OK)
83 - public void activateRuleById(@PathVariable("ruleId") String strRuleId) throws ThingsboardException {  
84 - checkParameter("ruleId", strRuleId); 85 + public void activateRuleById(@PathVariable(RULE_ID) String strRuleId) throws ThingsboardException {
  86 + checkParameter(RULE_ID, strRuleId);
85 try { 87 try {
86 RuleId ruleId = new RuleId(toUUID(strRuleId)); 88 RuleId ruleId = new RuleId(toUUID(strRuleId));
87 RuleMetaData rule = checkRule(ruleService.findRuleById(ruleId)); 89 RuleMetaData rule = checkRule(ruleService.findRuleById(ruleId));
@@ -95,8 +97,8 @@ public class RuleController extends BaseController { @@ -95,8 +97,8 @@ public class RuleController extends BaseController {
95 @PreAuthorize("hasAnyAuthority('SYS_ADMIN', 'TENANT_ADMIN')") 97 @PreAuthorize("hasAnyAuthority('SYS_ADMIN', 'TENANT_ADMIN')")
96 @RequestMapping(value = "/rule/{ruleId}/suspend", method = RequestMethod.POST) 98 @RequestMapping(value = "/rule/{ruleId}/suspend", method = RequestMethod.POST)
97 @ResponseStatus(value = HttpStatus.OK) 99 @ResponseStatus(value = HttpStatus.OK)
98 - public void suspendRuleById(@PathVariable("ruleId") String strRuleId) throws ThingsboardException {  
99 - checkParameter("ruleId", strRuleId); 100 + public void suspendRuleById(@PathVariable(RULE_ID) String strRuleId) throws ThingsboardException {
  101 + checkParameter(RULE_ID, strRuleId);
100 try { 102 try {
101 RuleId ruleId = new RuleId(toUUID(strRuleId)); 103 RuleId ruleId = new RuleId(toUUID(strRuleId));
102 RuleMetaData rule = checkRule(ruleService.findRuleById(ruleId)); 104 RuleMetaData rule = checkRule(ruleService.findRuleById(ruleId));
@@ -178,8 +180,8 @@ public class RuleController extends BaseController { @@ -178,8 +180,8 @@ public class RuleController extends BaseController {
178 @PreAuthorize("hasAnyAuthority('SYS_ADMIN', 'TENANT_ADMIN')") 180 @PreAuthorize("hasAnyAuthority('SYS_ADMIN', 'TENANT_ADMIN')")
179 @RequestMapping(value = "/rule/{ruleId}", method = RequestMethod.DELETE) 181 @RequestMapping(value = "/rule/{ruleId}", method = RequestMethod.DELETE)
180 @ResponseStatus(value = HttpStatus.OK) 182 @ResponseStatus(value = HttpStatus.OK)
181 - public void deleteRule(@PathVariable("ruleId") String strRuleId) throws ThingsboardException {  
182 - checkParameter("ruleId", strRuleId); 183 + public void deleteRule(@PathVariable(RULE_ID) String strRuleId) throws ThingsboardException {
  184 + checkParameter(RULE_ID, strRuleId);
183 try { 185 try {
184 RuleId ruleId = new RuleId(toUUID(strRuleId)); 186 RuleId ruleId = new RuleId(toUUID(strRuleId));
185 RuleMetaData rule = checkRule(ruleService.findRuleById(ruleId)); 187 RuleMetaData rule = checkRule(ruleService.findRuleById(ruleId));
@@ -38,19 +38,22 @@ import javax.servlet.http.HttpServletRequest; @@ -38,19 +38,22 @@ import javax.servlet.http.HttpServletRequest;
38 @RequestMapping("/api") 38 @RequestMapping("/api")
39 public class UserController extends BaseController { 39 public class UserController extends BaseController {
40 40
  41 + public static final String USER_ID = "userId";
  42 + public static final String YOU_DON_T_HAVE_PERMISSION_TO_PERFORM_THIS_OPERATION = "You don't have permission to perform this operation!";
  43 + public static final String ACTIVATE_URL_PATTERN = "%s/api/noauth/activate?activateToken=%s";
41 @Autowired 44 @Autowired
42 private MailService mailService; 45 private MailService mailService;
43 46
44 @PreAuthorize("hasAnyAuthority('SYS_ADMIN', 'TENANT_ADMIN', 'CUSTOMER_USER')") 47 @PreAuthorize("hasAnyAuthority('SYS_ADMIN', 'TENANT_ADMIN', 'CUSTOMER_USER')")
45 @RequestMapping(value = "/user/{userId}", method = RequestMethod.GET) 48 @RequestMapping(value = "/user/{userId}", method = RequestMethod.GET)
46 @ResponseBody 49 @ResponseBody
47 - public User getUserById(@PathVariable("userId") String strUserId) throws ThingsboardException {  
48 - checkParameter("userId", strUserId); 50 + public User getUserById(@PathVariable(USER_ID) String strUserId) throws ThingsboardException {
  51 + checkParameter(USER_ID, strUserId);
49 try { 52 try {
50 UserId userId = new UserId(toUUID(strUserId)); 53 UserId userId = new UserId(toUUID(strUserId));
51 SecurityUser authUser = getCurrentUser(); 54 SecurityUser authUser = getCurrentUser();
52 if (authUser.getAuthority() == Authority.CUSTOMER_USER && !authUser.getId().equals(userId)) { 55 if (authUser.getAuthority() == Authority.CUSTOMER_USER && !authUser.getId().equals(userId)) {
53 - throw new ThingsboardException("You don't have permission to perform this operation!", 56 + throw new ThingsboardException(YOU_DON_T_HAVE_PERMISSION_TO_PERFORM_THIS_OPERATION,
54 ThingsboardErrorCode.PERMISSION_DENIED); 57 ThingsboardErrorCode.PERMISSION_DENIED);
55 } 58 }
56 return checkUserId(userId); 59 return checkUserId(userId);
@@ -68,7 +71,7 @@ public class UserController extends BaseController { @@ -68,7 +71,7 @@ public class UserController extends BaseController {
68 try { 71 try {
69 SecurityUser authUser = getCurrentUser(); 72 SecurityUser authUser = getCurrentUser();
70 if (authUser.getAuthority() == Authority.CUSTOMER_USER && !authUser.getId().equals(user.getId())) { 73 if (authUser.getAuthority() == Authority.CUSTOMER_USER && !authUser.getId().equals(user.getId())) {
71 - throw new ThingsboardException("You don't have permission to perform this operation!", 74 + throw new ThingsboardException(YOU_DON_T_HAVE_PERMISSION_TO_PERFORM_THIS_OPERATION,
72 ThingsboardErrorCode.PERMISSION_DENIED); 75 ThingsboardErrorCode.PERMISSION_DENIED);
73 } 76 }
74 boolean sendEmail = user.getId() == null && sendActivationMail; 77 boolean sendEmail = user.getId() == null && sendActivationMail;
@@ -79,7 +82,7 @@ public class UserController extends BaseController { @@ -79,7 +82,7 @@ public class UserController extends BaseController {
79 if (sendEmail) { 82 if (sendEmail) {
80 UserCredentials userCredentials = userService.findUserCredentialsByUserId(savedUser.getId()); 83 UserCredentials userCredentials = userService.findUserCredentialsByUserId(savedUser.getId());
81 String baseUrl = constructBaseUrl(request); 84 String baseUrl = constructBaseUrl(request);
82 - String activateUrl = String.format("%s/api/noauth/activate?activateToken=%s", baseUrl, 85 + String activateUrl = String.format(ACTIVATE_URL_PATTERN, baseUrl,
83 userCredentials.getActivateToken()); 86 userCredentials.getActivateToken());
84 String email = savedUser.getEmail(); 87 String email = savedUser.getEmail();
85 try { 88 try {
@@ -106,7 +109,7 @@ public class UserController extends BaseController { @@ -106,7 +109,7 @@ public class UserController extends BaseController {
106 UserCredentials userCredentials = userService.findUserCredentialsByUserId(user.getId()); 109 UserCredentials userCredentials = userService.findUserCredentialsByUserId(user.getId());
107 if (!userCredentials.isEnabled()) { 110 if (!userCredentials.isEnabled()) {
108 String baseUrl = constructBaseUrl(request); 111 String baseUrl = constructBaseUrl(request);
109 - String activateUrl = String.format("%s/api/noauth/activate?activateToken=%s", baseUrl, 112 + String activateUrl = String.format(ACTIVATE_URL_PATTERN, baseUrl,
110 userCredentials.getActivateToken()); 113 userCredentials.getActivateToken());
111 mailService.sendActivationEmail(activateUrl, email); 114 mailService.sendActivationEmail(activateUrl, email);
112 } else { 115 } else {
@@ -121,21 +124,21 @@ public class UserController extends BaseController { @@ -121,21 +124,21 @@ public class UserController extends BaseController {
121 @RequestMapping(value = "/user/{userId}/activationLink", method = RequestMethod.GET, produces = "text/plain") 124 @RequestMapping(value = "/user/{userId}/activationLink", method = RequestMethod.GET, produces = "text/plain")
122 @ResponseBody 125 @ResponseBody
123 public String getActivationLink( 126 public String getActivationLink(
124 - @PathVariable("userId") String strUserId, 127 + @PathVariable(USER_ID) String strUserId,
125 HttpServletRequest request) throws ThingsboardException { 128 HttpServletRequest request) throws ThingsboardException {
126 - checkParameter("userId", strUserId); 129 + checkParameter(USER_ID, strUserId);
127 try { 130 try {
128 UserId userId = new UserId(toUUID(strUserId)); 131 UserId userId = new UserId(toUUID(strUserId));
129 SecurityUser authUser = getCurrentUser(); 132 SecurityUser authUser = getCurrentUser();
130 if (authUser.getAuthority() == Authority.CUSTOMER_USER && !authUser.getId().equals(userId)) { 133 if (authUser.getAuthority() == Authority.CUSTOMER_USER && !authUser.getId().equals(userId)) {
131 - throw new ThingsboardException("You don't have permission to perform this operation!", 134 + throw new ThingsboardException(YOU_DON_T_HAVE_PERMISSION_TO_PERFORM_THIS_OPERATION,
132 ThingsboardErrorCode.PERMISSION_DENIED); 135 ThingsboardErrorCode.PERMISSION_DENIED);
133 } 136 }
134 User user = checkUserId(userId); 137 User user = checkUserId(userId);
135 UserCredentials userCredentials = userService.findUserCredentialsByUserId(user.getId()); 138 UserCredentials userCredentials = userService.findUserCredentialsByUserId(user.getId());
136 if (!userCredentials.isEnabled()) { 139 if (!userCredentials.isEnabled()) {
137 String baseUrl = constructBaseUrl(request); 140 String baseUrl = constructBaseUrl(request);
138 - String activateUrl = String.format("%s/api/noauth/activate?activateToken=%s", baseUrl, 141 + String activateUrl = String.format(ACTIVATE_URL_PATTERN, baseUrl,
139 userCredentials.getActivateToken()); 142 userCredentials.getActivateToken());
140 return activateUrl; 143 return activateUrl;
141 } else { 144 } else {
@@ -149,8 +152,8 @@ public class UserController extends BaseController { @@ -149,8 +152,8 @@ public class UserController extends BaseController {
149 @PreAuthorize("hasAnyAuthority('SYS_ADMIN', 'TENANT_ADMIN')") 152 @PreAuthorize("hasAnyAuthority('SYS_ADMIN', 'TENANT_ADMIN')")
150 @RequestMapping(value = "/user/{userId}", method = RequestMethod.DELETE) 153 @RequestMapping(value = "/user/{userId}", method = RequestMethod.DELETE)
151 @ResponseStatus(value = HttpStatus.OK) 154 @ResponseStatus(value = HttpStatus.OK)
152 - public void deleteUser(@PathVariable("userId") String strUserId) throws ThingsboardException {  
153 - checkParameter("userId", strUserId); 155 + public void deleteUser(@PathVariable(USER_ID) String strUserId) throws ThingsboardException {
  156 + checkParameter(USER_ID, strUserId);
154 try { 157 try {
155 UserId userId = new UserId(toUUID(strUserId)); 158 UserId userId = new UserId(toUUID(strUserId));
156 checkUserId(userId); 159 checkUserId(userId);
@@ -47,12 +47,6 @@ import javax.servlet.http.HttpServletRequest; @@ -47,12 +47,6 @@ import javax.servlet.http.HttpServletRequest;
47 @Slf4j 47 @Slf4j
48 public class PluginApiController extends BaseController { 48 public class PluginApiController extends BaseController {
49 49
50 - @Autowired  
51 - private ActorService actorService;  
52 -  
53 - @Autowired  
54 - private PluginService pluginService;  
55 -  
56 @SuppressWarnings("rawtypes") 50 @SuppressWarnings("rawtypes")
57 @PreAuthorize("hasAnyAuthority('SYS_ADMIN', 'TENANT_ADMIN', 'CUSTOMER_USER')") 51 @PreAuthorize("hasAnyAuthority('SYS_ADMIN', 'TENANT_ADMIN', 'CUSTOMER_USER')")
58 @RequestMapping(value = "/{pluginToken}/**") 52 @RequestMapping(value = "/{pluginToken}/**")
@@ -71,7 +65,7 @@ public class PluginApiController extends BaseController { @@ -71,7 +65,7 @@ public class PluginApiController extends BaseController {
71 TenantId tenantId = getCurrentUser().getTenantId(); 65 TenantId tenantId = getCurrentUser().getTenantId();
72 CustomerId customerId = getCurrentUser().getCustomerId(); 66 CustomerId customerId = getCurrentUser().getCustomerId();
73 if (validatePluginAccess(pluginMd, tenantId, customerId)) { 67 if (validatePluginAccess(pluginMd, tenantId, customerId)) {
74 - if(ModelConstants.NULL_UUID.equals(tenantId.getId())){ 68 + if(tenantId != null && ModelConstants.NULL_UUID.equals(tenantId.getId())){
75 tenantId = null; 69 tenantId = null;
76 } 70 }
77 PluginApiCallSecurityContext securityCtx = new PluginApiCallSecurityContext(pluginMd.getTenantId(), pluginMd.getId(), tenantId, customerId); 71 PluginApiCallSecurityContext securityCtx = new PluginApiCallSecurityContext(pluginMd.getTenantId(), pluginMd.getId(), tenantId, customerId);
@@ -97,7 +91,7 @@ public class PluginApiController extends BaseController { @@ -97,7 +91,7 @@ public class PluginApiController extends BaseController {
97 validUser = true; 91 validUser = true;
98 } 92 }
99 } else { 93 } else {
100 - if ((pluginMd.isPublicAccess() || tenantAdministrator) && tenantId.equals(pluginMd.getTenantId())) { 94 + if ((pluginMd.isPublicAccess() || tenantAdministrator) && tenantId != null && tenantId.equals(pluginMd.getTenantId())) {
101 // All tenant users can access public tenant plugins. Only tenant 95 // All tenant users can access public tenant plugins. Only tenant
102 // administrator can access private tenant plugins 96 // administrator can access private tenant plugins
103 validUser = true; 97 validUser = true;
@@ -28,7 +28,6 @@ import org.thingsboard.server.service.install.DatabaseSchemaService; @@ -28,7 +28,6 @@ import org.thingsboard.server.service.install.DatabaseSchemaService;
28 import org.thingsboard.server.service.install.DatabaseUpgradeService; 28 import org.thingsboard.server.service.install.DatabaseUpgradeService;
29 import org.thingsboard.server.service.install.SystemDataLoaderService; 29 import org.thingsboard.server.service.install.SystemDataLoaderService;
30 30
31 -import java.nio.file.Files;  
32 import java.nio.file.Paths; 31 import java.nio.file.Paths;
33 32
34 @Service 33 @Service
@@ -69,7 +68,7 @@ public class ThingsboardInstallService { @@ -69,7 +68,7 @@ public class ThingsboardInstallService {
69 log.info("Starting ThingsBoard Upgrade from version {} ...", upgradeFromVersion); 68 log.info("Starting ThingsBoard Upgrade from version {} ...", upgradeFromVersion);
70 69
71 switch (upgradeFromVersion) { 70 switch (upgradeFromVersion) {
72 - case "1.2.3": 71 + case "1.2.3": //NOSONAR, Need to execute gradual upgrade starting from upgradeFromVersion
73 log.info("Upgrading ThingsBoard from version 1.2.3 to 1.3.0 ..."); 72 log.info("Upgrading ThingsBoard from version 1.2.3 to 1.3.0 ...");
74 73
75 databaseUpgradeService.upgradeDatabase(upgradeFromVersion); 74 databaseUpgradeService.upgradeDatabase(upgradeFromVersion);
@@ -115,7 +114,7 @@ public class ThingsboardInstallService { @@ -115,7 +114,7 @@ public class ThingsboardInstallService {
115 if (this.dataDir == null) { 114 if (this.dataDir == null) {
116 throw new RuntimeException("'install.data_dir' property should specified!"); 115 throw new RuntimeException("'install.data_dir' property should specified!");
117 } 116 }
118 - if (!Files.isDirectory(Paths.get(this.dataDir))) { 117 + if (!Paths.get(this.dataDir).toFile().isDirectory()) {
119 throw new RuntimeException("'install.data_dir' property value is not a valid directory!"); 118 throw new RuntimeException("'install.data_dir' property value is not a valid directory!");
120 } 119 }
121 120
@@ -45,12 +45,12 @@ public class DummyDiscoveryService implements DiscoveryService { @@ -45,12 +45,12 @@ public class DummyDiscoveryService implements DiscoveryService {
45 45
46 @Override 46 @Override
47 public void publishCurrentServer() { 47 public void publishCurrentServer() {
48 - 48 + //Do nothing
49 } 49 }
50 50
51 @Override 51 @Override
52 public void unpublishCurrentServer() { 52 public void unpublishCurrentServer() {
53 - 53 + //Do nothing
54 } 54 }
55 55
56 @Override 56 @Override
@@ -202,6 +202,8 @@ public class ZkDiscoveryService implements DiscoveryService, PathChildrenCacheLi @@ -202,6 +202,8 @@ public class ZkDiscoveryService implements DiscoveryService, PathChildrenCacheLi
202 case CHILD_REMOVED: 202 case CHILD_REMOVED:
203 listeners.forEach(listener -> listener.onServerRemoved(instance)); 203 listeners.forEach(listener -> listener.onServerRemoved(instance));
204 break; 204 break;
  205 + default:
  206 + break;
205 } 207 }
206 } 208 }
207 } 209 }
@@ -95,6 +95,7 @@ public class ClusterGrpcService extends ClusterRpcServiceGrpc.ClusterRpcServiceI @@ -95,6 +95,7 @@ public class ClusterGrpcService extends ClusterRpcServiceGrpc.ClusterRpcServiceI
95 future.onMsg(msg); 95 future.onMsg(msg);
96 } catch (InterruptedException e) { 96 } catch (InterruptedException e) {
97 log.warn("Failed to report created session!"); 97 log.warn("Failed to report created session!");
  98 + Thread.currentThread().interrupt();
98 } 99 }
99 } else { 100 } else {
100 log.warn("Failed to lookup pending session!"); 101 log.warn("Failed to lookup pending session!");
@@ -117,6 +118,7 @@ public class ClusterGrpcService extends ClusterRpcServiceGrpc.ClusterRpcServiceI @@ -117,6 +118,7 @@ public class ClusterGrpcService extends ClusterRpcServiceGrpc.ClusterRpcServiceI
117 log.info("RPC server stopped!"); 118 log.info("RPC server stopped!");
118 } catch (InterruptedException e) { 119 } catch (InterruptedException e) {
119 log.warn("Failed to onStop RPC server!"); 120 log.warn("Failed to onStop RPC server!");
  121 + Thread.currentThread().interrupt();
120 } 122 }
121 } 123 }
122 } 124 }
@@ -29,7 +29,7 @@ import java.util.UUID; @@ -29,7 +29,7 @@ import java.util.UUID;
29 */ 29 */
30 @Data 30 @Data
31 @Slf4j 31 @Slf4j
32 -final public class GrpcSession implements Closeable { 32 +public final class GrpcSession implements Closeable {
33 private final UUID sessionId; 33 private final UUID sessionId;
34 private final boolean client; 34 private final boolean client;
35 private final GrpcSessionListener listener; 35 private final GrpcSessionListener listener;
@@ -59,36 +59,14 @@ final public class GrpcSession implements Closeable { @@ -59,36 +59,14 @@ final public class GrpcSession implements Closeable {
59 this.inputStream = new StreamObserver<ClusterAPIProtos.ToRpcServerMessage>() { 59 this.inputStream = new StreamObserver<ClusterAPIProtos.ToRpcServerMessage>() {
60 @Override 60 @Override
61 public void onNext(ClusterAPIProtos.ToRpcServerMessage msg) { 61 public void onNext(ClusterAPIProtos.ToRpcServerMessage msg) {
62 - if (!connected) {  
63 - if (msg.hasConnectMsg()) {  
64 - connected = true;  
65 - ClusterAPIProtos.ServerAddress rpcAddress = msg.getConnectMsg().getServerAddress();  
66 - remoteServer = new ServerAddress(rpcAddress.getHost(), rpcAddress.getPort());  
67 - listener.onConnected(GrpcSession.this);  
68 - } 62 + if (!connected && msg.hasConnectMsg()) {
  63 + connected = true;
  64 + ClusterAPIProtos.ServerAddress rpcAddress = msg.getConnectMsg().getServerAddress();
  65 + remoteServer = new ServerAddress(rpcAddress.getHost(), rpcAddress.getPort());
  66 + listener.onConnected(GrpcSession.this);
69 } 67 }
70 if (connected) { 68 if (connected) {
71 - if (msg.hasToPluginRpcMsg()) {  
72 - listener.onToPluginRpcMsg(GrpcSession.this, msg.getToPluginRpcMsg());  
73 - }  
74 - if (msg.hasToDeviceActorRpcMsg()) {  
75 - listener.onToDeviceActorRpcMsg(GrpcSession.this, msg.getToDeviceActorRpcMsg());  
76 - }  
77 - if (msg.hasToDeviceSessionActorRpcMsg()) {  
78 - listener.onToDeviceSessionActorRpcMsg(GrpcSession.this, msg.getToDeviceSessionActorRpcMsg());  
79 - }  
80 - if (msg.hasToDeviceActorNotificationRpcMsg()) {  
81 - listener.onToDeviceActorNotificationRpcMsg(GrpcSession.this, msg.getToDeviceActorNotificationRpcMsg());  
82 - }  
83 - if (msg.hasToDeviceRpcRequestRpcMsg()) {  
84 - listener.onToDeviceRpcRequestRpcMsg(GrpcSession.this, msg.getToDeviceRpcRequestRpcMsg());  
85 - }  
86 - if (msg.hasToPluginRpcResponseRpcMsg()) {  
87 - listener.onFromDeviceRpcResponseRpcMsg(GrpcSession.this, msg.getToPluginRpcResponseRpcMsg());  
88 - }  
89 - if (msg.hasToAllNodesRpcMsg()) {  
90 - listener.onToAllNodesRpcMessage(GrpcSession.this, msg.getToAllNodesRpcMsg());  
91 - } 69 + handleToRpcServerMessage(msg);
92 } 70 }
93 } 71 }
94 72
@@ -105,6 +83,30 @@ final public class GrpcSession implements Closeable { @@ -105,6 +83,30 @@ final public class GrpcSession implements Closeable {
105 }; 83 };
106 } 84 }
107 85
  86 + private void handleToRpcServerMessage(ClusterAPIProtos.ToRpcServerMessage msg) {
  87 + if (msg.hasToPluginRpcMsg()) {
  88 + listener.onToPluginRpcMsg(GrpcSession.this, msg.getToPluginRpcMsg());
  89 + }
  90 + if (msg.hasToDeviceActorRpcMsg()) {
  91 + listener.onToDeviceActorRpcMsg(GrpcSession.this, msg.getToDeviceActorRpcMsg());
  92 + }
  93 + if (msg.hasToDeviceSessionActorRpcMsg()) {
  94 + listener.onToDeviceSessionActorRpcMsg(GrpcSession.this, msg.getToDeviceSessionActorRpcMsg());
  95 + }
  96 + if (msg.hasToDeviceActorNotificationRpcMsg()) {
  97 + listener.onToDeviceActorNotificationRpcMsg(GrpcSession.this, msg.getToDeviceActorNotificationRpcMsg());
  98 + }
  99 + if (msg.hasToDeviceRpcRequestRpcMsg()) {
  100 + listener.onToDeviceRpcRequestRpcMsg(GrpcSession.this, msg.getToDeviceRpcRequestRpcMsg());
  101 + }
  102 + if (msg.hasToPluginRpcResponseRpcMsg()) {
  103 + listener.onFromDeviceRpcResponseRpcMsg(GrpcSession.this, msg.getToPluginRpcResponseRpcMsg());
  104 + }
  105 + if (msg.hasToAllNodesRpcMsg()) {
  106 + listener.onToAllNodesRpcMessage(GrpcSession.this, msg.getToAllNodesRpcMsg());
  107 + }
  108 + }
  109 +
108 public void initOutputStream() { 110 public void initOutputStream() {
109 if (client) { 111 if (client) {
110 listener.onConnected(GrpcSession.this); 112 listener.onConnected(GrpcSession.this);
@@ -79,78 +79,83 @@ public class AnnotationComponentDiscoveryService implements ComponentDiscoverySe @@ -79,78 +79,83 @@ public class AnnotationComponentDiscoveryService implements ComponentDiscoverySe
79 private List<ComponentDescriptor> persist(Set<BeanDefinition> filterDefs, ComponentType type) { 79 private List<ComponentDescriptor> persist(Set<BeanDefinition> filterDefs, ComponentType type) {
80 List<ComponentDescriptor> result = new ArrayList<>(); 80 List<ComponentDescriptor> result = new ArrayList<>();
81 for (BeanDefinition def : filterDefs) { 81 for (BeanDefinition def : filterDefs) {
82 - ComponentDescriptor scannedComponent = new ComponentDescriptor();  
83 - String clazzName = def.getBeanClassName();  
84 - try {  
85 - scannedComponent.setType(type);  
86 - Class<?> clazz = Class.forName(clazzName);  
87 - String descriptorResourceName;  
88 - switch (type) {  
89 - case FILTER:  
90 - Filter filterAnnotation = clazz.getAnnotation(Filter.class);  
91 - scannedComponent.setName(filterAnnotation.name());  
92 - scannedComponent.setScope(filterAnnotation.scope());  
93 - descriptorResourceName = filterAnnotation.descriptor();  
94 - break;  
95 - case PROCESSOR:  
96 - Processor processorAnnotation = clazz.getAnnotation(Processor.class);  
97 - scannedComponent.setName(processorAnnotation.name());  
98 - scannedComponent.setScope(processorAnnotation.scope());  
99 - descriptorResourceName = processorAnnotation.descriptor();  
100 - break;  
101 - case ACTION:  
102 - Action actionAnnotation = clazz.getAnnotation(Action.class);  
103 - scannedComponent.setName(actionAnnotation.name());  
104 - scannedComponent.setScope(actionAnnotation.scope());  
105 - descriptorResourceName = actionAnnotation.descriptor();  
106 - break;  
107 - case PLUGIN:  
108 - Plugin pluginAnnotation = clazz.getAnnotation(Plugin.class);  
109 - scannedComponent.setName(pluginAnnotation.name());  
110 - scannedComponent.setScope(pluginAnnotation.scope());  
111 - descriptorResourceName = pluginAnnotation.descriptor();  
112 - for (Class<?> actionClazz : pluginAnnotation.actions()) {  
113 - ComponentDescriptor actionComponent = getComponent(actionClazz.getName())  
114 - .orElseThrow(() -> {  
115 - log.error("Can't initialize plugin {}, due to missing action {}!", def.getBeanClassName(), actionClazz.getName());  
116 - return new ClassNotFoundException("Action: " + actionClazz.getName() + "is missing!");  
117 - });  
118 - if (actionComponent.getType() != ComponentType.ACTION) {  
119 - log.error("Plugin {} action {} has wrong component type!", def.getBeanClassName(), actionClazz.getName(), actionComponent.getType());  
120 - throw new RuntimeException("Plugin " + def.getBeanClassName() + "action " + actionClazz.getName() + " has wrong component type!");  
121 - }  
122 - }  
123 - scannedComponent.setActions(Arrays.stream(pluginAnnotation.actions()).map(action -> action.getName()).collect(Collectors.joining(",")));  
124 - break;  
125 - default:  
126 - throw new RuntimeException(type + " is not supported yet!");  
127 - }  
128 - scannedComponent.setConfigurationDescriptor(mapper.readTree(  
129 - Resources.toString(Resources.getResource(descriptorResourceName), Charsets.UTF_8)));  
130 - scannedComponent.setClazz(clazzName);  
131 - log.info("Processing scanned component: {}", scannedComponent);  
132 - } catch (Exception e) {  
133 - log.error("Can't initialize component {}, due to {}", def.getBeanClassName(), e.getMessage(), e);  
134 - throw new RuntimeException(e);  
135 - }  
136 - ComponentDescriptor persistedComponent = componentDescriptorService.findByClazz(clazzName);  
137 - if (persistedComponent == null) {  
138 - log.info("Persisting new component: {}", scannedComponent);  
139 - scannedComponent = componentDescriptorService.saveComponent(scannedComponent);  
140 - } else if (scannedComponent.equals(persistedComponent)) {  
141 - log.info("Component is already persisted: {}", persistedComponent);  
142 - scannedComponent = persistedComponent;  
143 - } else {  
144 - log.info("Component {} will be updated to {}", persistedComponent, scannedComponent);  
145 - componentDescriptorService.deleteByClazz(persistedComponent.getClazz());  
146 - scannedComponent.setId(persistedComponent.getId());  
147 - scannedComponent = componentDescriptorService.saveComponent(scannedComponent);  
148 - } 82 + ComponentDescriptor scannedComponent = scanAndPersistComponent(def, type);
149 result.add(scannedComponent); 83 result.add(scannedComponent);
150 } 84 }
151 return result; 85 return result;
152 } 86 }
153 87
  88 + private ComponentDescriptor scanAndPersistComponent(BeanDefinition def, ComponentType type) {
  89 + ComponentDescriptor scannedComponent = new ComponentDescriptor();
  90 + String clazzName = def.getBeanClassName();
  91 + try {
  92 + scannedComponent.setType(type);
  93 + Class<?> clazz = Class.forName(clazzName);
  94 + String descriptorResourceName;
  95 + switch (type) {
  96 + case FILTER:
  97 + Filter filterAnnotation = clazz.getAnnotation(Filter.class);
  98 + scannedComponent.setName(filterAnnotation.name());
  99 + scannedComponent.setScope(filterAnnotation.scope());
  100 + descriptorResourceName = filterAnnotation.descriptor();
  101 + break;
  102 + case PROCESSOR:
  103 + Processor processorAnnotation = clazz.getAnnotation(Processor.class);
  104 + scannedComponent.setName(processorAnnotation.name());
  105 + scannedComponent.setScope(processorAnnotation.scope());
  106 + descriptorResourceName = processorAnnotation.descriptor();
  107 + break;
  108 + case ACTION:
  109 + Action actionAnnotation = clazz.getAnnotation(Action.class);
  110 + scannedComponent.setName(actionAnnotation.name());
  111 + scannedComponent.setScope(actionAnnotation.scope());
  112 + descriptorResourceName = actionAnnotation.descriptor();
  113 + break;
  114 + case PLUGIN:
  115 + Plugin pluginAnnotation = clazz.getAnnotation(Plugin.class);
  116 + scannedComponent.setName(pluginAnnotation.name());
  117 + scannedComponent.setScope(pluginAnnotation.scope());
  118 + descriptorResourceName = pluginAnnotation.descriptor();
  119 + for (Class<?> actionClazz : pluginAnnotation.actions()) {
  120 + ComponentDescriptor actionComponent = getComponent(actionClazz.getName())
  121 + .orElseThrow(() -> {
  122 + log.error("Can't initialize plugin {}, due to missing action {}!", def.getBeanClassName(), actionClazz.getName());
  123 + return new ClassNotFoundException("Action: " + actionClazz.getName() + "is missing!");
  124 + });
  125 + if (actionComponent.getType() != ComponentType.ACTION) {
  126 + log.error("Plugin {} action {} has wrong component type!", def.getBeanClassName(), actionClazz.getName(), actionComponent.getType());
  127 + throw new RuntimeException("Plugin " + def.getBeanClassName() + "action " + actionClazz.getName() + " has wrong component type!");
  128 + }
  129 + }
  130 + scannedComponent.setActions(Arrays.stream(pluginAnnotation.actions()).map(action -> action.getName()).collect(Collectors.joining(",")));
  131 + break;
  132 + default:
  133 + throw new RuntimeException(type + " is not supported yet!");
  134 + }
  135 + scannedComponent.setConfigurationDescriptor(mapper.readTree(
  136 + Resources.toString(Resources.getResource(descriptorResourceName), Charsets.UTF_8)));
  137 + scannedComponent.setClazz(clazzName);
  138 + log.info("Processing scanned component: {}", scannedComponent);
  139 + } catch (Exception e) {
  140 + log.error("Can't initialize component {}, due to {}", def.getBeanClassName(), e.getMessage(), e);
  141 + throw new RuntimeException(e);
  142 + }
  143 + ComponentDescriptor persistedComponent = componentDescriptorService.findByClazz(clazzName);
  144 + if (persistedComponent == null) {
  145 + log.info("Persisting new component: {}", scannedComponent);
  146 + scannedComponent = componentDescriptorService.saveComponent(scannedComponent);
  147 + } else if (scannedComponent.equals(persistedComponent)) {
  148 + log.info("Component is already persisted: {}", persistedComponent);
  149 + scannedComponent = persistedComponent;
  150 + } else {
  151 + log.info("Component {} will be updated to {}", persistedComponent, scannedComponent);
  152 + componentDescriptorService.deleteByClazz(persistedComponent.getClazz());
  153 + scannedComponent.setId(persistedComponent.getId());
  154 + scannedComponent = componentDescriptorService.saveComponent(scannedComponent);
  155 + }
  156 + return scannedComponent;
  157 + }
  158 +
154 private Set<BeanDefinition> getBeanDefinitions(Class<? extends Annotation> componentType) { 159 private Set<BeanDefinition> getBeanDefinitions(Class<? extends Annotation> componentType) {
155 ClassPathScanningCandidateComponentProvider scanner = new ClassPathScanningCandidateComponentProvider(false); 160 ClassPathScanningCandidateComponentProvider scanner = new ClassPathScanningCandidateComponentProvider(false);
156 scanner.addIncludeFilter(new AnnotationTypeFilter(componentType)); 161 scanner.addIncludeFilter(new AnnotationTypeFilter(componentType));
@@ -40,6 +40,12 @@ import java.util.List; @@ -40,6 +40,12 @@ import java.util.List;
40 public class CassandraDatabaseUpgradeService implements DatabaseUpgradeService { 40 public class CassandraDatabaseUpgradeService implements DatabaseUpgradeService {
41 41
42 private static final String SCHEMA_UPDATE_CQL = "schema_update.cql"; 42 private static final String SCHEMA_UPDATE_CQL = "schema_update.cql";
  43 + public static final String DEVICE = "device";
  44 + public static final String TENANT_ID = "tenant_id";
  45 + public static final String CUSTOMER_ID = "customer_id";
  46 + public static final String SEARCH_TEXT = "search_text";
  47 + public static final String ADDITIONAL_INFO = "additional_info";
  48 + public static final String ASSET = "asset";
43 49
44 @Value("${install.data_dir}") 50 @Value("${install.data_dir}")
45 private String dataDir; 51 private String dataDir;
@@ -63,22 +69,22 @@ public class CassandraDatabaseUpgradeService implements DatabaseUpgradeService { @@ -63,22 +69,22 @@ public class CassandraDatabaseUpgradeService implements DatabaseUpgradeService {
63 KeyspaceMetadata ks = cluster.getCluster().getMetadata().getKeyspace(cluster.getKeyspaceName()); 69 KeyspaceMetadata ks = cluster.getCluster().getMetadata().getKeyspace(cluster.getKeyspaceName());
64 70
65 log.info("Dumping devices ..."); 71 log.info("Dumping devices ...");
66 - Path devicesDump = CassandraDbHelper.dumpCfIfExists(ks, cluster.getSession(), "device",  
67 - new String[]{"id", "tenant_id", "customer_id", "name", "search_text", "additional_info", "type"}, 72 + Path devicesDump = CassandraDbHelper.dumpCfIfExists(ks, cluster.getSession(), DEVICE,
  73 + new String[]{"id", TENANT_ID, CUSTOMER_ID, "name", SEARCH_TEXT, ADDITIONAL_INFO, "type"},
68 new String[]{"", "", "", "", "", "", "default"}, 74 new String[]{"", "", "", "", "", "", "default"},
69 "tb-devices"); 75 "tb-devices");
70 log.info("Devices dumped."); 76 log.info("Devices dumped.");
71 77
72 log.info("Dumping assets ..."); 78 log.info("Dumping assets ...");
73 - Path assetsDump = CassandraDbHelper.dumpCfIfExists(ks, cluster.getSession(), "asset",  
74 - new String[]{"id", "tenant_id", "customer_id", "name", "search_text", "additional_info", "type"}, 79 + Path assetsDump = CassandraDbHelper.dumpCfIfExists(ks, cluster.getSession(), ASSET,
  80 + new String[]{"id", TENANT_ID, CUSTOMER_ID, "name", SEARCH_TEXT, ADDITIONAL_INFO, "type"},
75 new String[]{"", "", "", "", "", "", "default"}, 81 new String[]{"", "", "", "", "", "", "default"},
76 "tb-assets"); 82 "tb-assets");
77 log.info("Assets dumped."); 83 log.info("Assets dumped.");
78 84
79 log.info("Dumping relations ..."); 85 log.info("Dumping relations ...");
80 Path relationsDump = CassandraDbHelper.dumpCfIfExists(ks, cluster.getSession(), "relation", 86 Path relationsDump = CassandraDbHelper.dumpCfIfExists(ks, cluster.getSession(), "relation",
81 - new String[]{"from_id", "from_type", "to_id", "to_type", "relation_type", "additional_info", "relation_type_group"}, 87 + new String[]{"from_id", "from_type", "to_id", "to_type", "relation_type", ADDITIONAL_INFO, "relation_type_group"},
82 new String[]{"", "", "", "", "", "", "COMMON"}, 88 new String[]{"", "", "", "", "", "", "COMMON"},
83 "tb-relations"); 89 "tb-relations");
84 log.info("Relations dumped."); 90 log.info("Relations dumped.");
@@ -92,15 +98,15 @@ public class CassandraDatabaseUpgradeService implements DatabaseUpgradeService { @@ -92,15 +98,15 @@ public class CassandraDatabaseUpgradeService implements DatabaseUpgradeService {
92 98
93 log.info("Restoring devices ..."); 99 log.info("Restoring devices ...");
94 if (devicesDump != null) { 100 if (devicesDump != null) {
95 - CassandraDbHelper.loadCf(ks, cluster.getSession(), "device",  
96 - new String[]{"id", "tenant_id", "customer_id", "name", "search_text", "additional_info", "type"}, devicesDump); 101 + CassandraDbHelper.loadCf(ks, cluster.getSession(), DEVICE,
  102 + new String[]{"id", TENANT_ID, CUSTOMER_ID, "name", SEARCH_TEXT, ADDITIONAL_INFO, "type"}, devicesDump);
97 Files.deleteIfExists(devicesDump); 103 Files.deleteIfExists(devicesDump);
98 } 104 }
99 log.info("Devices restored."); 105 log.info("Devices restored.");
100 106
101 log.info("Dumping device types ..."); 107 log.info("Dumping device types ...");
102 - Path deviceTypesDump = CassandraDbHelper.dumpCfIfExists(ks, cluster.getSession(), "device",  
103 - new String[]{"tenant_id", "type"}, 108 + Path deviceTypesDump = CassandraDbHelper.dumpCfIfExists(ks, cluster.getSession(), DEVICE,
  109 + new String[]{TENANT_ID, "type"},
104 new String[]{"", ""}, 110 new String[]{"", ""},
105 "tb-device-types"); 111 "tb-device-types");
106 if (deviceTypesDump != null) { 112 if (deviceTypesDump != null) {
@@ -110,22 +116,22 @@ public class CassandraDatabaseUpgradeService implements DatabaseUpgradeService { @@ -110,22 +116,22 @@ public class CassandraDatabaseUpgradeService implements DatabaseUpgradeService {
110 log.info("Loading device types ..."); 116 log.info("Loading device types ...");
111 if (deviceTypesDump != null) { 117 if (deviceTypesDump != null) {
112 CassandraDbHelper.loadCf(ks, cluster.getSession(), "entity_subtype", 118 CassandraDbHelper.loadCf(ks, cluster.getSession(), "entity_subtype",
113 - new String[]{"tenant_id", "type", "entity_type"}, deviceTypesDump); 119 + new String[]{TENANT_ID, "type", "entity_type"}, deviceTypesDump);
114 Files.deleteIfExists(deviceTypesDump); 120 Files.deleteIfExists(deviceTypesDump);
115 } 121 }
116 log.info("Device types loaded."); 122 log.info("Device types loaded.");
117 123
118 log.info("Restoring assets ..."); 124 log.info("Restoring assets ...");
119 if (assetsDump != null) { 125 if (assetsDump != null) {
120 - CassandraDbHelper.loadCf(ks, cluster.getSession(), "asset",  
121 - new String[]{"id", "tenant_id", "customer_id", "name", "search_text", "additional_info", "type"}, assetsDump); 126 + CassandraDbHelper.loadCf(ks, cluster.getSession(), ASSET,
  127 + new String[]{"id", TENANT_ID, CUSTOMER_ID, "name", SEARCH_TEXT, ADDITIONAL_INFO, "type"}, assetsDump);
122 Files.deleteIfExists(assetsDump); 128 Files.deleteIfExists(assetsDump);
123 } 129 }
124 log.info("Assets restored."); 130 log.info("Assets restored.");
125 131
126 log.info("Dumping asset types ..."); 132 log.info("Dumping asset types ...");
127 - Path assetTypesDump = CassandraDbHelper.dumpCfIfExists(ks, cluster.getSession(), "asset",  
128 - new String[]{"tenant_id", "type"}, 133 + Path assetTypesDump = CassandraDbHelper.dumpCfIfExists(ks, cluster.getSession(), ASSET,
  134 + new String[]{TENANT_ID, "type"},
129 new String[]{"", ""}, 135 new String[]{"", ""},
130 "tb-asset-types"); 136 "tb-asset-types");
131 if (assetTypesDump != null) { 137 if (assetTypesDump != null) {
@@ -135,7 +141,7 @@ public class CassandraDatabaseUpgradeService implements DatabaseUpgradeService { @@ -135,7 +141,7 @@ public class CassandraDatabaseUpgradeService implements DatabaseUpgradeService {
135 log.info("Loading asset types ..."); 141 log.info("Loading asset types ...");
136 if (assetTypesDump != null) { 142 if (assetTypesDump != null) {
137 CassandraDbHelper.loadCf(ks, cluster.getSession(), "entity_subtype", 143 CassandraDbHelper.loadCf(ks, cluster.getSession(), "entity_subtype",
138 - new String[]{"tenant_id", "type", "entity_type"}, assetTypesDump); 144 + new String[]{TENANT_ID, "type", "entity_type"}, assetTypesDump);
139 Files.deleteIfExists(assetTypesDump); 145 Files.deleteIfExists(assetTypesDump);
140 } 146 }
141 log.info("Asset types loaded."); 147 log.info("Asset types loaded.");
@@ -143,7 +149,7 @@ public class CassandraDatabaseUpgradeService implements DatabaseUpgradeService { @@ -143,7 +149,7 @@ public class CassandraDatabaseUpgradeService implements DatabaseUpgradeService {
143 log.info("Restoring relations ..."); 149 log.info("Restoring relations ...");
144 if (relationsDump != null) { 150 if (relationsDump != null) {
145 CassandraDbHelper.loadCf(ks, cluster.getSession(), "relation", 151 CassandraDbHelper.loadCf(ks, cluster.getSession(), "relation",
146 - new String[]{"from_id", "from_type", "to_id", "to_type", "relation_type", "additional_info", "relation_type_group"}, relationsDump); 152 + new String[]{"from_id", "from_type", "to_id", "to_type", "relation_type", ADDITIONAL_INFO, "relation_type_group"}, relationsDump);
147 Files.deleteIfExists(relationsDump); 153 Files.deleteIfExists(relationsDump);
148 } 154 }
149 log.info("Relations restored."); 155 log.info("Relations restored.");
@@ -51,6 +51,7 @@ import org.thingsboard.server.dao.widget.WidgetTypeService; @@ -51,6 +51,7 @@ import org.thingsboard.server.dao.widget.WidgetTypeService;
51 import org.thingsboard.server.dao.widget.WidgetsBundleService; 51 import org.thingsboard.server.dao.widget.WidgetsBundleService;
52 52
53 import java.io.IOException; 53 import java.io.IOException;
  54 +import java.nio.file.DirectoryStream;
54 import java.nio.file.Files; 55 import java.nio.file.Files;
55 import java.nio.file.Path; 56 import java.nio.file.Path;
56 import java.nio.file.Paths; 57 import java.nio.file.Paths;
@@ -69,6 +70,9 @@ public class DefaultSystemDataLoaderService implements SystemDataLoaderService { @@ -69,6 +70,9 @@ public class DefaultSystemDataLoaderService implements SystemDataLoaderService {
69 private static final String DASHBOARDS_DIR = "dashboards"; 70 private static final String DASHBOARDS_DIR = "dashboards";
70 71
71 private static final ObjectMapper objectMapper = new ObjectMapper(); 72 private static final ObjectMapper objectMapper = new ObjectMapper();
  73 + public static final String JSON_EXT = ".json";
  74 + public static final String CUSTOMER_CRED = "customer";
  75 + public static final String DEFAULT_DEVICE_TYPE = "default";
72 76
73 @Value("${install.data_dir}") 77 @Value("${install.data_dir}")
74 private String dataDir; 78 private String dataDir;
@@ -138,7 +142,7 @@ public class DefaultSystemDataLoaderService implements SystemDataLoaderService { @@ -138,7 +142,7 @@ public class DefaultSystemDataLoaderService implements SystemDataLoaderService {
138 node.put("timeout", "10000"); 142 node.put("timeout", "10000");
139 node.put("enableTls", "false"); 143 node.put("enableTls", "false");
140 node.put("username", ""); 144 node.put("username", "");
141 - node.put("password", ""); 145 + node.put("password", ""); //NOSONAR, key used to identify password field (not password value itself)
142 mailSettings.setJsonValue(node); 146 mailSettings.setJsonValue(node);
143 adminSettingsService.saveAdminSettings(mailSettings); 147 adminSettingsService.saveAdminSettings(mailSettings);
144 } 148 }
@@ -146,33 +150,34 @@ public class DefaultSystemDataLoaderService implements SystemDataLoaderService { @@ -146,33 +150,34 @@ public class DefaultSystemDataLoaderService implements SystemDataLoaderService {
146 @Override 150 @Override
147 public void loadSystemWidgets() throws Exception { 151 public void loadSystemWidgets() throws Exception {
148 Path widgetBundlesDir = Paths.get(dataDir, JSON_DIR, SYSTEM_DIR, WIDGET_BUNDLES_DIR); 152 Path widgetBundlesDir = Paths.get(dataDir, JSON_DIR, SYSTEM_DIR, WIDGET_BUNDLES_DIR);
149 - Files.newDirectoryStream(widgetBundlesDir, path -> path.toString().endsWith(".json"))  
150 - .forEach(  
151 - path -> {  
152 - try {  
153 - JsonNode widgetsBundleDescriptorJson = objectMapper.readTree(path.toFile());  
154 - JsonNode widgetsBundleJson = widgetsBundleDescriptorJson.get("widgetsBundle");  
155 - WidgetsBundle widgetsBundle = objectMapper.treeToValue(widgetsBundleJson, WidgetsBundle.class);  
156 - WidgetsBundle savedWidgetsBundle = widgetsBundleService.saveWidgetsBundle(widgetsBundle);  
157 - JsonNode widgetTypesArrayJson = widgetsBundleDescriptorJson.get("widgetTypes");  
158 - widgetTypesArrayJson.forEach(  
159 - widgetTypeJson -> {  
160 - try {  
161 - WidgetType widgetType = objectMapper.treeToValue(widgetTypeJson, WidgetType.class);  
162 - widgetType.setBundleAlias(savedWidgetsBundle.getAlias());  
163 - widgetTypeService.saveWidgetType(widgetType);  
164 - } catch (Exception e) {  
165 - log.error("Unable to load widget type from json: [{}]", path.toString());  
166 - throw new RuntimeException("Unable to load widget type from json", e);  
167 - } 153 + try (DirectoryStream<Path> dirStream = Files.newDirectoryStream(widgetBundlesDir, path -> path.toString().endsWith(JSON_EXT))) {
  154 + dirStream.forEach(
  155 + path -> {
  156 + try {
  157 + JsonNode widgetsBundleDescriptorJson = objectMapper.readTree(path.toFile());
  158 + JsonNode widgetsBundleJson = widgetsBundleDescriptorJson.get("widgetsBundle");
  159 + WidgetsBundle widgetsBundle = objectMapper.treeToValue(widgetsBundleJson, WidgetsBundle.class);
  160 + WidgetsBundle savedWidgetsBundle = widgetsBundleService.saveWidgetsBundle(widgetsBundle);
  161 + JsonNode widgetTypesArrayJson = widgetsBundleDescriptorJson.get("widgetTypes");
  162 + widgetTypesArrayJson.forEach(
  163 + widgetTypeJson -> {
  164 + try {
  165 + WidgetType widgetType = objectMapper.treeToValue(widgetTypeJson, WidgetType.class);
  166 + widgetType.setBundleAlias(savedWidgetsBundle.getAlias());
  167 + widgetTypeService.saveWidgetType(widgetType);
  168 + } catch (Exception e) {
  169 + log.error("Unable to load widget type from json: [{}]", path.toString());
  170 + throw new RuntimeException("Unable to load widget type from json", e);
168 } 171 }
169 - );  
170 - } catch (Exception e) {  
171 - log.error("Unable to load widgets bundle from json: [{}]", path.toString());  
172 - throw new RuntimeException("Unable to load widgets bundle from json", e);  
173 - } 172 + }
  173 + );
  174 + } catch (Exception e) {
  175 + log.error("Unable to load widgets bundle from json: [{}]", path.toString());
  176 + throw new RuntimeException("Unable to load widgets bundle from json", e);
174 } 177 }
175 - ); 178 + }
  179 + );
  180 + }
176 } 181 }
177 182
178 @Override 183 @Override
@@ -206,21 +211,21 @@ public class DefaultSystemDataLoaderService implements SystemDataLoaderService { @@ -206,21 +211,21 @@ public class DefaultSystemDataLoaderService implements SystemDataLoaderService {
206 customerC.setTenantId(demoTenant.getId()); 211 customerC.setTenantId(demoTenant.getId());
207 customerC.setTitle("Customer C"); 212 customerC.setTitle("Customer C");
208 customerC = customerService.saveCustomer(customerC); 213 customerC = customerService.saveCustomer(customerC);
209 - createUser(Authority.CUSTOMER_USER, demoTenant.getId(), customerA.getId(), "customer@thingsboard.org", "customer");  
210 - createUser(Authority.CUSTOMER_USER, demoTenant.getId(), customerA.getId(), "customerA@thingsboard.org", "customer");  
211 - createUser(Authority.CUSTOMER_USER, demoTenant.getId(), customerB.getId(), "customerB@thingsboard.org", "customer");  
212 - createUser(Authority.CUSTOMER_USER, demoTenant.getId(), customerC.getId(), "customerC@thingsboard.org", "customer");  
213 -  
214 - createDevice(demoTenant.getId(), customerA.getId(), "default", "Test Device A1", "A1_TEST_TOKEN", null);  
215 - createDevice(demoTenant.getId(), customerA.getId(), "default", "Test Device A2", "A2_TEST_TOKEN", null);  
216 - createDevice(demoTenant.getId(), customerA.getId(), "default", "Test Device A3", "A3_TEST_TOKEN", null);  
217 - createDevice(demoTenant.getId(), customerB.getId(), "default", "Test Device B1", "B1_TEST_TOKEN", null);  
218 - createDevice(demoTenant.getId(), customerC.getId(), "default", "Test Device C1", "C1_TEST_TOKEN", null);  
219 -  
220 - createDevice(demoTenant.getId(), null, "default", "DHT11 Demo Device", "DHT11_DEMO_TOKEN", "Demo device that is used in sample " + 214 + createUser(Authority.CUSTOMER_USER, demoTenant.getId(), customerA.getId(), "customer@thingsboard.org", CUSTOMER_CRED);
  215 + createUser(Authority.CUSTOMER_USER, demoTenant.getId(), customerA.getId(), "customerA@thingsboard.org", CUSTOMER_CRED);
  216 + createUser(Authority.CUSTOMER_USER, demoTenant.getId(), customerB.getId(), "customerB@thingsboard.org", CUSTOMER_CRED);
  217 + createUser(Authority.CUSTOMER_USER, demoTenant.getId(), customerC.getId(), "customerC@thingsboard.org", CUSTOMER_CRED);
  218 +
  219 + createDevice(demoTenant.getId(), customerA.getId(), DEFAULT_DEVICE_TYPE, "Test Device A1", "A1_TEST_TOKEN", null);
  220 + createDevice(demoTenant.getId(), customerA.getId(), DEFAULT_DEVICE_TYPE, "Test Device A2", "A2_TEST_TOKEN", null);
  221 + createDevice(demoTenant.getId(), customerA.getId(), DEFAULT_DEVICE_TYPE, "Test Device A3", "A3_TEST_TOKEN", null);
  222 + createDevice(demoTenant.getId(), customerB.getId(), DEFAULT_DEVICE_TYPE, "Test Device B1", "B1_TEST_TOKEN", null);
  223 + createDevice(demoTenant.getId(), customerC.getId(), DEFAULT_DEVICE_TYPE, "Test Device C1", "C1_TEST_TOKEN", null);
  224 +
  225 + createDevice(demoTenant.getId(), null, DEFAULT_DEVICE_TYPE, "DHT11 Demo Device", "DHT11_DEMO_TOKEN", "Demo device that is used in sample " +
221 "applications that upload data from DHT11 temperature and humidity sensor"); 226 "applications that upload data from DHT11 temperature and humidity sensor");
222 227
223 - createDevice(demoTenant.getId(), null, "default", "Raspberry Pi Demo Device", "RASPBERRY_PI_DEMO_TOKEN", "Demo device that is used in " + 228 + createDevice(demoTenant.getId(), null, DEFAULT_DEVICE_TYPE, "Raspberry Pi Demo Device", "RASPBERRY_PI_DEMO_TOKEN", "Demo device that is used in " +
224 "Raspberry Pi GPIO control sample application"); 229 "Raspberry Pi GPIO control sample application");
225 230
226 loadPlugins(Paths.get(dataDir, JSON_DIR, DEMO_DIR, PLUGINS_DIR), demoTenant.getId()); 231 loadPlugins(Paths.get(dataDir, JSON_DIR, DEMO_DIR, PLUGINS_DIR), demoTenant.getId());
@@ -279,67 +284,69 @@ public class DefaultSystemDataLoaderService implements SystemDataLoaderService { @@ -279,67 +284,69 @@ public class DefaultSystemDataLoaderService implements SystemDataLoaderService {
279 } 284 }
280 285
281 private void loadPlugins(Path pluginsDir, TenantId tenantId) throws Exception{ 286 private void loadPlugins(Path pluginsDir, TenantId tenantId) throws Exception{
282 - Files.newDirectoryStream(pluginsDir, path -> path.toString().endsWith(".json"))  
283 - .forEach(  
284 - path -> {  
285 - try {  
286 - JsonNode pluginJson = objectMapper.readTree(path.toFile());  
287 - PluginMetaData plugin = objectMapper.treeToValue(pluginJson, PluginMetaData.class);  
288 - plugin.setTenantId(tenantId);  
289 - if (plugin.getState() == ComponentLifecycleState.ACTIVE) {  
290 - plugin.setState(ComponentLifecycleState.SUSPENDED);  
291 - PluginMetaData savedPlugin = pluginService.savePlugin(plugin);  
292 - pluginService.activatePluginById(savedPlugin.getId());  
293 - } else {  
294 - pluginService.savePlugin(plugin);  
295 - }  
296 - } catch (Exception e) {  
297 - log.error("Unable to load plugin from json: [{}]", path.toString());  
298 - throw new RuntimeException("Unable to load plugin from json", e); 287 + try (DirectoryStream<Path> dirStream = Files.newDirectoryStream(pluginsDir, path -> path.toString().endsWith(JSON_EXT))) {
  288 + dirStream.forEach(
  289 + path -> {
  290 + try {
  291 + JsonNode pluginJson = objectMapper.readTree(path.toFile());
  292 + PluginMetaData plugin = objectMapper.treeToValue(pluginJson, PluginMetaData.class);
  293 + plugin.setTenantId(tenantId);
  294 + if (plugin.getState() == ComponentLifecycleState.ACTIVE) {
  295 + plugin.setState(ComponentLifecycleState.SUSPENDED);
  296 + PluginMetaData savedPlugin = pluginService.savePlugin(plugin);
  297 + pluginService.activatePluginById(savedPlugin.getId());
  298 + } else {
  299 + pluginService.savePlugin(plugin);
299 } 300 }
  301 + } catch (Exception e) {
  302 + log.error("Unable to load plugin from json: [{}]", path.toString());
  303 + throw new RuntimeException("Unable to load plugin from json", e);
300 } 304 }
301 - );  
302 - 305 + }
  306 + );
  307 + }
303 } 308 }
304 309
305 private void loadRules(Path rulesDir, TenantId tenantId) throws Exception { 310 private void loadRules(Path rulesDir, TenantId tenantId) throws Exception {
306 - Files.newDirectoryStream(rulesDir, path -> path.toString().endsWith(".json"))  
307 - .forEach(  
308 - path -> {  
309 - try {  
310 - JsonNode ruleJson = objectMapper.readTree(path.toFile());  
311 - RuleMetaData rule = objectMapper.treeToValue(ruleJson, RuleMetaData.class);  
312 - rule.setTenantId(tenantId);  
313 - if (rule.getState() == ComponentLifecycleState.ACTIVE) {  
314 - rule.setState(ComponentLifecycleState.SUSPENDED);  
315 - RuleMetaData savedRule = ruleService.saveRule(rule);  
316 - ruleService.activateRuleById(savedRule.getId());  
317 - } else {  
318 - ruleService.saveRule(rule);  
319 - }  
320 - } catch (Exception e) {  
321 - log.error("Unable to load rule from json: [{}]", path.toString());  
322 - throw new RuntimeException("Unable to load rule from json", e); 311 + try (DirectoryStream<Path> dirStream = Files.newDirectoryStream(rulesDir, path -> path.toString().endsWith(JSON_EXT))) {
  312 + dirStream.forEach(
  313 + path -> {
  314 + try {
  315 + JsonNode ruleJson = objectMapper.readTree(path.toFile());
  316 + RuleMetaData rule = objectMapper.treeToValue(ruleJson, RuleMetaData.class);
  317 + rule.setTenantId(tenantId);
  318 + if (rule.getState() == ComponentLifecycleState.ACTIVE) {
  319 + rule.setState(ComponentLifecycleState.SUSPENDED);
  320 + RuleMetaData savedRule = ruleService.saveRule(rule);
  321 + ruleService.activateRuleById(savedRule.getId());
  322 + } else {
  323 + ruleService.saveRule(rule);
323 } 324 }
  325 + } catch (Exception e) {
  326 + log.error("Unable to load rule from json: [{}]", path.toString());
  327 + throw new RuntimeException("Unable to load rule from json", e);
324 } 328 }
325 - ); 329 + }
  330 + );
  331 + }
326 } 332 }
327 333
328 private void loadDashboards(Path dashboardsDir, TenantId tenantId, CustomerId customerId) throws Exception { 334 private void loadDashboards(Path dashboardsDir, TenantId tenantId, CustomerId customerId) throws Exception {
329 - Files.newDirectoryStream(dashboardsDir, path -> path.toString().endsWith(".json"))  
330 - .forEach(  
331 - path -> {  
332 - try {  
333 - JsonNode dashboardJson = objectMapper.readTree(path.toFile());  
334 - Dashboard dashboard = objectMapper.treeToValue(dashboardJson, Dashboard.class);  
335 - dashboard.setTenantId(tenantId);  
336 - dashboard.setCustomerId(customerId);  
337 - dashboardService.saveDashboard(dashboard);  
338 - } catch (Exception e) {  
339 - log.error("Unable to load dashboard from json: [{}]", path.toString());  
340 - throw new RuntimeException("Unable to load dashboard from json", e);  
341 - } 335 + try (DirectoryStream<Path> dirStream = Files.newDirectoryStream(dashboardsDir, path -> path.toString().endsWith(JSON_EXT))) {
  336 + dirStream.forEach(
  337 + path -> {
  338 + try {
  339 + JsonNode dashboardJson = objectMapper.readTree(path.toFile());
  340 + Dashboard dashboard = objectMapper.treeToValue(dashboardJson, Dashboard.class);
  341 + dashboard.setTenantId(tenantId);
  342 + dashboard.setCustomerId(customerId);
  343 + dashboardService.saveDashboard(dashboard);
  344 + } catch (Exception e) {
  345 + log.error("Unable to load dashboard from json: [{}]", path.toString());
  346 + throw new RuntimeException("Unable to load dashboard from json", e);
342 } 347 }
343 - ); 348 + }
  349 + );
  350 + }
344 } 351 }
345 } 352 }
@@ -28,6 +28,7 @@ import java.nio.file.Path; @@ -28,6 +28,7 @@ import java.nio.file.Path;
28 import java.nio.file.Paths; 28 import java.nio.file.Paths;
29 import java.sql.Connection; 29 import java.sql.Connection;
30 import java.sql.DriverManager; 30 import java.sql.DriverManager;
  31 +import java.sql.PreparedStatement;
31 32
32 @Service 33 @Service
33 @Profile("install") 34 @Profile("install")
@@ -58,7 +59,7 @@ public class SqlDatabaseSchemaService implements DatabaseSchemaService { @@ -58,7 +59,7 @@ public class SqlDatabaseSchemaService implements DatabaseSchemaService {
58 Path schemaFile = Paths.get(this.dataDir, SQL_DIR, SCHEMA_SQL); 59 Path schemaFile = Paths.get(this.dataDir, SQL_DIR, SCHEMA_SQL);
59 try (Connection conn = DriverManager.getConnection(dbUrl, dbUserName, dbPassword)) { 60 try (Connection conn = DriverManager.getConnection(dbUrl, dbUserName, dbPassword)) {
60 String sql = new String(Files.readAllBytes(schemaFile), Charset.forName("UTF-8")); 61 String sql = new String(Files.readAllBytes(schemaFile), Charset.forName("UTF-8"));
61 - conn.createStatement().execute(sql); 62 + conn.prepareStatement(sql).execute(); //NOSONAR, ignoring because method used to load initial thingsboard database schema
62 } 63 }
63 64
64 } 65 }
@@ -44,7 +44,7 @@ public class CQLStatementsParser { @@ -44,7 +44,7 @@ public class CQLStatementsParser {
44 public CQLStatementsParser(Path cql) throws IOException { 44 public CQLStatementsParser(Path cql) throws IOException {
45 try { 45 try {
46 List<String> lines = Files.readAllLines(cql); 46 List<String> lines = Files.readAllLines(cql);
47 - StringBuffer t = new StringBuffer(); 47 + StringBuilder t = new StringBuilder();
48 for (String l : lines) { 48 for (String l : lines) {
49 t.append(l.trim()); 49 t.append(l.trim());
50 t.append('\n'); 50 t.append('\n');
@@ -68,36 +68,14 @@ public class CQLStatementsParser { @@ -68,36 +68,14 @@ public class CQLStatementsParser {
68 68
69 private void parseStatements() { 69 private void parseStatements() {
70 this.statements = new ArrayList<>(); 70 this.statements = new ArrayList<>();
71 - StringBuffer statementUnderConstruction = new StringBuffer(); 71 + StringBuilder statementUnderConstruction = new StringBuilder();
72 72
73 char c; 73 char c;
74 while ((c = getChar()) != 0) { 74 while ((c = getChar()) != 0) {
75 switch (state) { 75 switch (state) {
76 case DEFAULT: 76 case DEFAULT:
77 - if (c == '/' && peekAhead() == '/') {  
78 - state = State.INSINGLELINECOMMENT;  
79 - advance();  
80 - } else if (c == '-' && peekAhead() == '-') {  
81 - state = State.INSINGLELINECOMMENT;  
82 - advance();  
83 - } else if (c == '/' && peekAhead() == '*') {  
84 - state = State.INMULTILINECOMMENT;  
85 - advance();  
86 - } else if (c == '\n') {  
87 - statementUnderConstruction.append(' ');  
88 - } else {  
89 - statementUnderConstruction.append(c);  
90 - if (c == '\"') {  
91 - state = State.INQUOTESTRING;  
92 - } else if (c == '\'') {  
93 - state = State.INSQUOTESTRING;  
94 - } else if (c == ';') {  
95 - statements.add(statementUnderConstruction.toString().trim());  
96 - statementUnderConstruction.setLength(0);  
97 - }  
98 - } 77 + processDefaultState(c, statementUnderConstruction);
99 break; 78 break;
100 -  
101 case INSINGLELINECOMMENT: 79 case INSINGLELINECOMMENT:
102 if (c == '\n') { 80 if (c == '\n') {
103 state = State.DEFAULT; 81 state = State.DEFAULT;
@@ -112,25 +90,10 @@ public class CQLStatementsParser { @@ -112,25 +90,10 @@ public class CQLStatementsParser {
112 break; 90 break;
113 91
114 case INQUOTESTRING: 92 case INQUOTESTRING:
115 - statementUnderConstruction.append(c);  
116 - if (c == '"') {  
117 - if (peekAhead() == '"') {  
118 - statementUnderConstruction.append(getChar());  
119 - } else {  
120 - state = State.DEFAULT;  
121 - }  
122 - } 93 + processInQuoteStringState(c, statementUnderConstruction);
123 break; 94 break;
124 -  
125 case INSQUOTESTRING: 95 case INSQUOTESTRING:
126 - statementUnderConstruction.append(c);  
127 - if (c == '\'') {  
128 - if (peekAhead() == '\'') {  
129 - statementUnderConstruction.append(getChar());  
130 - } else {  
131 - state = State.DEFAULT;  
132 - }  
133 - } 96 + processInSQuoteStringState(c, statementUnderConstruction);
134 break; 97 break;
135 } 98 }
136 99
@@ -141,6 +104,50 @@ public class CQLStatementsParser { @@ -141,6 +104,50 @@ public class CQLStatementsParser {
141 } 104 }
142 } 105 }
143 106
  107 + private void processDefaultState(char c, StringBuilder statementUnderConstruction) {
  108 + if ((c == '/' && peekAhead() == '/') || (c == '-' && peekAhead() == '-')) {
  109 + state = State.INSINGLELINECOMMENT;
  110 + advance();
  111 + } else if (c == '/' && peekAhead() == '*') {
  112 + state = State.INMULTILINECOMMENT;
  113 + advance();
  114 + } else if (c == '\n') {
  115 + statementUnderConstruction.append(' ');
  116 + } else {
  117 + statementUnderConstruction.append(c);
  118 + if (c == '\"') {
  119 + state = State.INQUOTESTRING;
  120 + } else if (c == '\'') {
  121 + state = State.INSQUOTESTRING;
  122 + } else if (c == ';') {
  123 + statements.add(statementUnderConstruction.toString().trim());
  124 + statementUnderConstruction.setLength(0);
  125 + }
  126 + }
  127 + }
  128 +
  129 + private void processInQuoteStringState(char c, StringBuilder statementUnderConstruction) {
  130 + statementUnderConstruction.append(c);
  131 + if (c == '"') {
  132 + if (peekAhead() == '"') {
  133 + statementUnderConstruction.append(getChar());
  134 + } else {
  135 + state = State.DEFAULT;
  136 + }
  137 + }
  138 + }
  139 +
  140 + private void processInSQuoteStringState(char c, StringBuilder statementUnderConstruction) {
  141 + statementUnderConstruction.append(c);
  142 + if (c == '\'') {
  143 + if (peekAhead() == '\'') {
  144 + statementUnderConstruction.append(getChar());
  145 + } else {
  146 + state = State.DEFAULT;
  147 + }
  148 + }
  149 + }
  150 +
144 private char getChar() { 151 private char getChar() {
145 if (pos < text.length()) 152 if (pos < text.length())
146 return text.charAt(pos++); 153 return text.charAt(pos++);
@@ -44,6 +44,9 @@ import java.util.Properties; @@ -44,6 +44,9 @@ import java.util.Properties;
44 @Slf4j 44 @Slf4j
45 public class DefaultMailService implements MailService { 45 public class DefaultMailService implements MailService {
46 46
  47 + public static final String MAIL_PROP = "mail.";
  48 + public static final String TARGET_EMAIL = "targetEmail";
  49 + public static final String UTF_8 = "UTF-8";
47 @Autowired 50 @Autowired
48 private MessageSource messages; 51 private MessageSource messages;
49 52
@@ -89,11 +92,11 @@ public class DefaultMailService implements MailService { @@ -89,11 +92,11 @@ public class DefaultMailService implements MailService {
89 Properties javaMailProperties = new Properties(); 92 Properties javaMailProperties = new Properties();
90 String protocol = jsonConfig.get("smtpProtocol").asText(); 93 String protocol = jsonConfig.get("smtpProtocol").asText();
91 javaMailProperties.put("mail.transport.protocol", protocol); 94 javaMailProperties.put("mail.transport.protocol", protocol);
92 - javaMailProperties.put("mail." + protocol + ".host", jsonConfig.get("smtpHost").asText());  
93 - javaMailProperties.put("mail." + protocol + ".port", jsonConfig.get("smtpPort").asText());  
94 - javaMailProperties.put("mail." + protocol + ".timeout", jsonConfig.get("timeout").asText());  
95 - javaMailProperties.put("mail." + protocol + ".auth", String.valueOf(StringUtils.isNotEmpty(jsonConfig.get("username").asText())));  
96 - javaMailProperties.put("mail." + protocol + ".starttls.enable", jsonConfig.get("enableTls")); 95 + javaMailProperties.put(MAIL_PROP + protocol + ".host", jsonConfig.get("smtpHost").asText());
  96 + javaMailProperties.put(MAIL_PROP + protocol + ".port", jsonConfig.get("smtpPort").asText());
  97 + javaMailProperties.put(MAIL_PROP + protocol + ".timeout", jsonConfig.get("timeout").asText());
  98 + javaMailProperties.put(MAIL_PROP + protocol + ".auth", String.valueOf(StringUtils.isNotEmpty(jsonConfig.get("username").asText())));
  99 + javaMailProperties.put(MAIL_PROP + protocol + ".starttls.enable", jsonConfig.get("enableTls"));
97 return javaMailProperties; 100 return javaMailProperties;
98 } 101 }
99 102
@@ -117,10 +120,10 @@ public class DefaultMailService implements MailService { @@ -117,10 +120,10 @@ public class DefaultMailService implements MailService {
117 String subject = messages.getMessage("test.message.subject", null, Locale.US); 120 String subject = messages.getMessage("test.message.subject", null, Locale.US);
118 121
119 Map<String, Object> model = new HashMap<String, Object>(); 122 Map<String, Object> model = new HashMap<String, Object>();
120 - model.put("targetEmail", email); 123 + model.put(TARGET_EMAIL, email);
121 124
122 String message = VelocityEngineUtils.mergeTemplateIntoString(this.engine, 125 String message = VelocityEngineUtils.mergeTemplateIntoString(this.engine,
123 - "test.vm", "UTF-8", model); 126 + "test.vm", UTF_8, model);
124 127
125 sendMail(testMailSender, mailFrom, email, subject, message); 128 sendMail(testMailSender, mailFrom, email, subject, message);
126 } 129 }
@@ -132,10 +135,10 @@ public class DefaultMailService implements MailService { @@ -132,10 +135,10 @@ public class DefaultMailService implements MailService {
132 135
133 Map<String, Object> model = new HashMap<String, Object>(); 136 Map<String, Object> model = new HashMap<String, Object>();
134 model.put("activationLink", activationLink); 137 model.put("activationLink", activationLink);
135 - model.put("targetEmail", email); 138 + model.put(TARGET_EMAIL, email);
136 139
137 String message = VelocityEngineUtils.mergeTemplateIntoString(this.engine, 140 String message = VelocityEngineUtils.mergeTemplateIntoString(this.engine,
138 - "activation.vm", "UTF-8", model); 141 + "activation.vm", UTF_8, model);
139 142
140 sendMail(mailSender, mailFrom, email, subject, message); 143 sendMail(mailSender, mailFrom, email, subject, message);
141 } 144 }
@@ -147,10 +150,10 @@ public class DefaultMailService implements MailService { @@ -147,10 +150,10 @@ public class DefaultMailService implements MailService {
147 150
148 Map<String, Object> model = new HashMap<String, Object>(); 151 Map<String, Object> model = new HashMap<String, Object>();
149 model.put("loginLink", loginLink); 152 model.put("loginLink", loginLink);
150 - model.put("targetEmail", email); 153 + model.put(TARGET_EMAIL, email);
151 154
152 String message = VelocityEngineUtils.mergeTemplateIntoString(this.engine, 155 String message = VelocityEngineUtils.mergeTemplateIntoString(this.engine,
153 - "account.activated.vm", "UTF-8", model); 156 + "account.activated.vm", UTF_8, model);
154 157
155 sendMail(mailSender, mailFrom, email, subject, message); 158 sendMail(mailSender, mailFrom, email, subject, message);
156 } 159 }
@@ -162,10 +165,10 @@ public class DefaultMailService implements MailService { @@ -162,10 +165,10 @@ public class DefaultMailService implements MailService {
162 165
163 Map<String, Object> model = new HashMap<String, Object>(); 166 Map<String, Object> model = new HashMap<String, Object>();
164 model.put("passwordResetLink", passwordResetLink); 167 model.put("passwordResetLink", passwordResetLink);
165 - model.put("targetEmail", email); 168 + model.put(TARGET_EMAIL, email);
166 169
167 String message = VelocityEngineUtils.mergeTemplateIntoString(this.engine, 170 String message = VelocityEngineUtils.mergeTemplateIntoString(this.engine,
168 - "reset.password.vm", "UTF-8", model); 171 + "reset.password.vm", UTF_8, model);
169 172
170 sendMail(mailSender, mailFrom, email, subject, message); 173 sendMail(mailSender, mailFrom, email, subject, message);
171 } 174 }
@@ -177,10 +180,10 @@ public class DefaultMailService implements MailService { @@ -177,10 +180,10 @@ public class DefaultMailService implements MailService {
177 180
178 Map<String, Object> model = new HashMap<String, Object>(); 181 Map<String, Object> model = new HashMap<String, Object>();
179 model.put("loginLink", loginLink); 182 model.put("loginLink", loginLink);
180 - model.put("targetEmail", email); 183 + model.put(TARGET_EMAIL, email);
181 184
182 String message = VelocityEngineUtils.mergeTemplateIntoString(this.engine, 185 String message = VelocityEngineUtils.mergeTemplateIntoString(this.engine,
183 - "password.was.reset.vm", "UTF-8", model); 186 + "password.was.reset.vm", UTF_8, model);
184 187
185 sendMail(mailSender, mailFrom, email, subject, message); 188 sendMail(mailSender, mailFrom, email, subject, message);
186 } 189 }
@@ -191,7 +194,7 @@ public class DefaultMailService implements MailService { @@ -191,7 +194,7 @@ public class DefaultMailService implements MailService {
191 String subject, String message) throws ThingsboardException { 194 String subject, String message) throws ThingsboardException {
192 try { 195 try {
193 MimeMessage mimeMsg = mailSender.createMimeMessage(); 196 MimeMessage mimeMsg = mailSender.createMimeMessage();
194 - MimeMessageHelper helper = new MimeMessageHelper(mimeMsg, "UTF-8"); 197 + MimeMessageHelper helper = new MimeMessageHelper(mimeMsg, UTF_8);
195 helper.setFrom(mailFrom); 198 helper.setFrom(mailFrom);
196 helper.setTo(email); 199 helper.setTo(email);
197 helper.setSubject(subject); 200 helper.setSubject(subject);
@@ -16,6 +16,7 @@ @@ -16,6 +16,7 @@
16 package org.thingsboard.server.service.security.auth.jwt; 16 package org.thingsboard.server.service.security.auth.jwt;
17 17
18 import com.fasterxml.jackson.databind.ObjectMapper; 18 import com.fasterxml.jackson.databind.ObjectMapper;
  19 +import lombok.extern.slf4j.Slf4j;
19 import org.apache.commons.lang3.StringUtils; 20 import org.apache.commons.lang3.StringUtils;
20 import org.slf4j.Logger; 21 import org.slf4j.Logger;
21 import org.slf4j.LoggerFactory; 22 import org.slf4j.LoggerFactory;
@@ -37,8 +38,8 @@ import javax.servlet.http.HttpServletRequest; @@ -37,8 +38,8 @@ import javax.servlet.http.HttpServletRequest;
37 import javax.servlet.http.HttpServletResponse; 38 import javax.servlet.http.HttpServletResponse;
38 import java.io.IOException; 39 import java.io.IOException;
39 40
  41 +@Slf4j
40 public class RefreshTokenProcessingFilter extends AbstractAuthenticationProcessingFilter { 42 public class RefreshTokenProcessingFilter extends AbstractAuthenticationProcessingFilter {
41 - private static Logger logger = LoggerFactory.getLogger(RefreshTokenProcessingFilter.class);  
42 43
43 private final AuthenticationSuccessHandler successHandler; 44 private final AuthenticationSuccessHandler successHandler;
44 private final AuthenticationFailureHandler failureHandler; 45 private final AuthenticationFailureHandler failureHandler;
@@ -57,8 +58,8 @@ public class RefreshTokenProcessingFilter extends AbstractAuthenticationProcessi @@ -57,8 +58,8 @@ public class RefreshTokenProcessingFilter extends AbstractAuthenticationProcessi
57 public Authentication attemptAuthentication(HttpServletRequest request, HttpServletResponse response) 58 public Authentication attemptAuthentication(HttpServletRequest request, HttpServletResponse response)
58 throws AuthenticationException, IOException, ServletException { 59 throws AuthenticationException, IOException, ServletException {
59 if (!HttpMethod.POST.name().equals(request.getMethod())) { 60 if (!HttpMethod.POST.name().equals(request.getMethod())) {
60 - if(logger.isDebugEnabled()) {  
61 - logger.debug("Authentication method not supported. Request method: " + request.getMethod()); 61 + if(log.isDebugEnabled()) {
  62 + log.debug("Authentication method not supported. Request method: " + request.getMethod());
62 } 63 }
63 throw new AuthMethodNotSupportedException("Authentication method not supported"); 64 throw new AuthMethodNotSupportedException("Authentication method not supported");
64 } 65 }
@@ -24,7 +24,7 @@ import javax.servlet.http.HttpServletRequest; @@ -24,7 +24,7 @@ import javax.servlet.http.HttpServletRequest;
24 24
25 @Component(value="jwtHeaderTokenExtractor") 25 @Component(value="jwtHeaderTokenExtractor")
26 public class JwtHeaderTokenExtractor implements TokenExtractor { 26 public class JwtHeaderTokenExtractor implements TokenExtractor {
27 - public static String HEADER_PREFIX = "Bearer "; 27 + public static final String HEADER_PREFIX = "Bearer ";
28 28
29 @Override 29 @Override
30 public String extract(HttpServletRequest request) { 30 public String extract(HttpServletRequest request) {
@@ -16,6 +16,7 @@ @@ -16,6 +16,7 @@
16 package org.thingsboard.server.service.security.auth.rest; 16 package org.thingsboard.server.service.security.auth.rest;
17 17
18 import com.fasterxml.jackson.databind.ObjectMapper; 18 import com.fasterxml.jackson.databind.ObjectMapper;
  19 +import lombok.extern.slf4j.Slf4j;
19 import org.apache.commons.lang3.StringUtils; 20 import org.apache.commons.lang3.StringUtils;
20 import org.slf4j.Logger; 21 import org.slf4j.Logger;
21 import org.slf4j.LoggerFactory; 22 import org.slf4j.LoggerFactory;
@@ -37,8 +38,8 @@ import javax.servlet.http.HttpServletRequest; @@ -37,8 +38,8 @@ import javax.servlet.http.HttpServletRequest;
37 import javax.servlet.http.HttpServletResponse; 38 import javax.servlet.http.HttpServletResponse;
38 import java.io.IOException; 39 import java.io.IOException;
39 40
  41 +@Slf4j
40 public class RestLoginProcessingFilter extends AbstractAuthenticationProcessingFilter { 42 public class RestLoginProcessingFilter extends AbstractAuthenticationProcessingFilter {
41 - private static Logger logger = LoggerFactory.getLogger(RestLoginProcessingFilter.class);  
42 43
43 private final AuthenticationSuccessHandler successHandler; 44 private final AuthenticationSuccessHandler successHandler;
44 private final AuthenticationFailureHandler failureHandler; 45 private final AuthenticationFailureHandler failureHandler;
@@ -57,8 +58,8 @@ public class RestLoginProcessingFilter extends AbstractAuthenticationProcessingF @@ -57,8 +58,8 @@ public class RestLoginProcessingFilter extends AbstractAuthenticationProcessingF
57 public Authentication attemptAuthentication(HttpServletRequest request, HttpServletResponse response) 58 public Authentication attemptAuthentication(HttpServletRequest request, HttpServletResponse response)
58 throws AuthenticationException, IOException, ServletException { 59 throws AuthenticationException, IOException, ServletException {
59 if (!HttpMethod.POST.name().equals(request.getMethod())) { 60 if (!HttpMethod.POST.name().equals(request.getMethod())) {
60 - if(logger.isDebugEnabled()) {  
61 - logger.debug("Authentication method not supported. Request method: " + request.getMethod()); 61 + if(log.isDebugEnabled()) {
  62 + log.debug("Authentication method not supported. Request method: " + request.getMethod());
62 } 63 }
63 throw new AuthMethodNotSupportedException("Authentication method not supported"); 64 throw new AuthMethodNotSupportedException("Authentication method not supported");
64 } 65 }
@@ -16,6 +16,7 @@ @@ -16,6 +16,7 @@
16 package org.thingsboard.server.service.security.auth.rest; 16 package org.thingsboard.server.service.security.auth.rest;
17 17
18 import com.fasterxml.jackson.databind.ObjectMapper; 18 import com.fasterxml.jackson.databind.ObjectMapper;
  19 +import lombok.extern.slf4j.Slf4j;
19 import org.apache.commons.lang3.StringUtils; 20 import org.apache.commons.lang3.StringUtils;
20 import org.slf4j.Logger; 21 import org.slf4j.Logger;
21 import org.slf4j.LoggerFactory; 22 import org.slf4j.LoggerFactory;
@@ -37,8 +38,8 @@ import javax.servlet.http.HttpServletRequest; @@ -37,8 +38,8 @@ import javax.servlet.http.HttpServletRequest;
37 import javax.servlet.http.HttpServletResponse; 38 import javax.servlet.http.HttpServletResponse;
38 import java.io.IOException; 39 import java.io.IOException;
39 40
  41 +@Slf4j
40 public class RestPublicLoginProcessingFilter extends AbstractAuthenticationProcessingFilter { 42 public class RestPublicLoginProcessingFilter extends AbstractAuthenticationProcessingFilter {
41 - private static Logger logger = LoggerFactory.getLogger(RestPublicLoginProcessingFilter.class);  
42 43
43 private final AuthenticationSuccessHandler successHandler; 44 private final AuthenticationSuccessHandler successHandler;
44 private final AuthenticationFailureHandler failureHandler; 45 private final AuthenticationFailureHandler failureHandler;
@@ -57,8 +58,8 @@ public class RestPublicLoginProcessingFilter extends AbstractAuthenticationProce @@ -57,8 +58,8 @@ public class RestPublicLoginProcessingFilter extends AbstractAuthenticationProce
57 public Authentication attemptAuthentication(HttpServletRequest request, HttpServletResponse response) 58 public Authentication attemptAuthentication(HttpServletRequest request, HttpServletResponse response)
58 throws AuthenticationException, IOException, ServletException { 59 throws AuthenticationException, IOException, ServletException {
59 if (!HttpMethod.POST.name().equals(request.getMethod())) { 60 if (!HttpMethod.POST.name().equals(request.getMethod())) {
60 - if(logger.isDebugEnabled()) {  
61 - logger.debug("Authentication method not supported. Request method: " + request.getMethod()); 61 + if(log.isDebugEnabled()) {
  62 + log.debug("Authentication method not supported. Request method: " + request.getMethod());
62 } 63 }
63 throw new AuthMethodNotSupportedException("Authentication method not supported"); 64 throw new AuthMethodNotSupportedException("Authentication method not supported");
64 } 65 }
@@ -46,7 +46,7 @@ public class SecurityUser extends User { @@ -46,7 +46,7 @@ public class SecurityUser extends User {
46 this.userPrincipal = userPrincipal; 46 this.userPrincipal = userPrincipal;
47 } 47 }
48 48
49 - public Collection<? extends GrantedAuthority> getAuthorities() { 49 + public Collection<GrantedAuthority> getAuthorities() {
50 if (authorities == null) { 50 if (authorities == null) {
51 authorities = Stream.of(SecurityUser.this.getAuthority()) 51 authorities = Stream.of(SecurityUser.this.getAuthority())
52 .map(authority -> new SimpleGrantedAuthority(authority.name())) 52 .map(authority -> new SimpleGrantedAuthority(authority.name()))
@@ -16,7 +16,9 @@ @@ -16,7 +16,9 @@
16 16
17 package org.thingsboard.server.service.security.model; 17 package org.thingsboard.server.service.security.model;
18 18
19 -public class UserPrincipal { 19 +import java.io.Serializable;
  20 +
  21 +public class UserPrincipal implements Serializable {
20 22
21 private final Type type; 23 private final Type type;
22 private final String value; 24 private final String value;
@@ -21,7 +21,7 @@ import io.jsonwebtoken.Claims; @@ -21,7 +21,7 @@ import io.jsonwebtoken.Claims;
21 public final class AccessJwtToken implements JwtToken { 21 public final class AccessJwtToken implements JwtToken {
22 private final String rawToken; 22 private final String rawToken;
23 @JsonIgnore 23 @JsonIgnore
24 - private Claims claims; 24 + private transient Claims claims;
25 25
26 protected AccessJwtToken(final String token, Claims claims) { 26 protected AccessJwtToken(final String token, Claims claims) {
27 this.rawToken = token; 27 this.rawToken = token;
@@ -15,6 +15,8 @@ @@ -15,6 +15,8 @@
15 */ 15 */
16 package org.thingsboard.server.service.security.model.token; 16 package org.thingsboard.server.service.security.model.token;
17 17
18 -public interface JwtToken { 18 +import java.io.Serializable;
  19 +
  20 +public interface JwtToken extends Serializable {
19 String getToken(); 21 String getToken();
20 } 22 }
@@ -21,7 +21,12 @@ import org.slf4j.LoggerFactory; @@ -21,7 +21,12 @@ import org.slf4j.LoggerFactory;
21 import org.springframework.security.authentication.BadCredentialsException; 21 import org.springframework.security.authentication.BadCredentialsException;
22 import org.thingsboard.server.service.security.exception.JwtExpiredTokenException; 22 import org.thingsboard.server.service.security.exception.JwtExpiredTokenException;
23 23
24 -public class RawAccessJwtToken implements JwtToken { 24 +import java.io.Serializable;
  25 +
  26 +public class RawAccessJwtToken implements JwtToken, Serializable {
  27 +
  28 + private static final long serialVersionUID = -797397445703066079L;
  29 +
25 private static Logger logger = LoggerFactory.getLogger(RawAccessJwtToken.class); 30 private static Logger logger = LoggerFactory.getLogger(RawAccessJwtToken.class);
26 31
27 private String token; 32 private String token;
@@ -27,6 +27,7 @@ import org.thingsboard.server.service.update.model.UpdateMessage; @@ -27,6 +27,7 @@ import org.thingsboard.server.service.update.model.UpdateMessage;
27 27
28 import javax.annotation.PostConstruct; 28 import javax.annotation.PostConstruct;
29 import javax.annotation.PreDestroy; 29 import javax.annotation.PreDestroy;
  30 +import java.io.IOException;
30 import java.nio.file.Files; 31 import java.nio.file.Files;
31 import java.nio.file.Path; 32 import java.nio.file.Path;
32 import java.nio.file.Paths; 33 import java.nio.file.Paths;
@@ -71,25 +72,34 @@ public class DefaultUpdateService implements UpdateService { @@ -71,25 +72,34 @@ public class DefaultUpdateService implements UpdateService {
71 if (version == null) { 72 if (version == null) {
72 version = "unknown"; 73 version = "unknown";
73 } 74 }
74 - Path instanceIdPath = Paths.get(INSTANCE_ID_FILE);  
75 - if (Files.exists(instanceIdPath)) {  
76 - byte[] data = Files.readAllBytes(instanceIdPath);  
77 - if (data != null && data.length > 0) {  
78 - try {  
79 - instanceId = UUID.fromString(new String(data));  
80 - } catch (IllegalArgumentException e) {  
81 - }  
82 - }  
83 - }  
84 - if (instanceId == null) {  
85 - instanceId = UUID.randomUUID();  
86 - Files.write(instanceIdPath, instanceId.toString().getBytes());  
87 - } 75 + instanceId = parseInstanceId();
88 checkUpdatesFuture = scheduler.scheduleAtFixedRate(checkUpdatesRunnable, 0, 1, TimeUnit.HOURS); 76 checkUpdatesFuture = scheduler.scheduleAtFixedRate(checkUpdatesRunnable, 0, 1, TimeUnit.HOURS);
89 - } catch (Exception e) {} 77 + } catch (Exception e) {
  78 + //Do nothing
  79 + }
90 } 80 }
91 } 81 }
92 82
  83 + private UUID parseInstanceId() throws IOException {
  84 + UUID result = null;
  85 + Path instanceIdPath = Paths.get(INSTANCE_ID_FILE);
  86 + if (instanceIdPath.toFile().exists()) {
  87 + byte[] data = Files.readAllBytes(instanceIdPath);
  88 + if (data != null && data.length > 0) {
  89 + try {
  90 + result = UUID.fromString(new String(data));
  91 + } catch (IllegalArgumentException e) {
  92 + //Do nothing
  93 + }
  94 + }
  95 + }
  96 + if (result == null) {
  97 + result = UUID.randomUUID();
  98 + Files.write(instanceIdPath, result.toString().getBytes());
  99 + }
  100 + return result;
  101 + }
  102 +
93 @PreDestroy 103 @PreDestroy
94 private void destroy() { 104 private void destroy() {
95 try { 105 try {
@@ -97,26 +107,25 @@ public class DefaultUpdateService implements UpdateService { @@ -97,26 +107,25 @@ public class DefaultUpdateService implements UpdateService {
97 checkUpdatesFuture.cancel(true); 107 checkUpdatesFuture.cancel(true);
98 } 108 }
99 scheduler.shutdownNow(); 109 scheduler.shutdownNow();
100 - } catch (Exception e) {} 110 + } catch (Exception e) {
  111 + //Do nothing
  112 + }
101 } 113 }
102 114
103 - Runnable checkUpdatesRunnable = new Runnable() {  
104 - @Override  
105 - public void run() {  
106 - try {  
107 - log.trace("Executing check update method for instanceId [{}], platform [{}] and version [{}]", instanceId, platform, version);  
108 - ObjectNode request = new ObjectMapper().createObjectNode();  
109 - request.put(PLATFORM_PARAM, platform);  
110 - request.put(VERSION_PARAM, version);  
111 - request.put(INSTANCE_ID_PARAM, instanceId.toString());  
112 - JsonNode response = restClient.postForObject(UPDATE_SERVER_BASE_URL+"/api/thingsboard/updates", request, JsonNode.class);  
113 - updateMessage = new UpdateMessage(  
114 - response.get("message").asText(),  
115 - response.get("updateAvailable").asBoolean()  
116 - );  
117 - } catch (Exception e) {  
118 - log.trace(e.getMessage());  
119 - } 115 + Runnable checkUpdatesRunnable = () -> {
  116 + try {
  117 + log.trace("Executing check update method for instanceId [{}], platform [{}] and version [{}]", instanceId, platform, version);
  118 + ObjectNode request = new ObjectMapper().createObjectNode();
  119 + request.put(PLATFORM_PARAM, platform);
  120 + request.put(VERSION_PARAM, version);
  121 + request.put(INSTANCE_ID_PARAM, instanceId.toString());
  122 + JsonNode response = restClient.postForObject(UPDATE_SERVER_BASE_URL+"/api/thingsboard/updates", request, JsonNode.class);
  123 + updateMessage = new UpdateMessage(
  124 + response.get("message").asText(),
  125 + response.get("updateAvailable").asBoolean()
  126 + );
  127 + } catch (Exception e) {
  128 + log.trace(e.getMessage());
120 } 129 }
121 }; 130 };
122 131
@@ -24,7 +24,7 @@ public class AdminSettings extends BaseData<AdminSettingsId> { @@ -24,7 +24,7 @@ public class AdminSettings extends BaseData<AdminSettingsId> {
24 private static final long serialVersionUID = -7670322981725511892L; 24 private static final long serialVersionUID = -7670322981725511892L;
25 25
26 private String key; 26 private String key;
27 - private JsonNode jsonValue; 27 + private transient JsonNode jsonValue;
28 28
29 public AdminSettings() { 29 public AdminSettings() {
30 super(); 30 super();
@@ -15,8 +15,10 @@ @@ -15,8 +15,10 @@
15 */ 15 */
16 package org.thingsboard.server.common.data; 16 package org.thingsboard.server.common.data;
17 17
  18 +import lombok.EqualsAndHashCode;
18 import org.thingsboard.server.common.data.id.UUIDBased; 19 import org.thingsboard.server.common.data.id.UUIDBased;
19 20
  21 +@EqualsAndHashCode(callSuper = true)
20 public abstract class ContactBased<I extends UUIDBased> extends SearchTextBased<I> { 22 public abstract class ContactBased<I extends UUIDBased> extends SearchTextBased<I> {
21 23
22 private static final long serialVersionUID = 5047448057830660988L; 24 private static final long serialVersionUID = 5047448057830660988L;
@@ -114,72 +116,4 @@ public abstract class ContactBased<I extends UUIDBased> extends SearchTextBased< @@ -114,72 +116,4 @@ public abstract class ContactBased<I extends UUIDBased> extends SearchTextBased<
114 this.email = email; 116 this.email = email;
115 } 117 }
116 118
117 - @Override  
118 - public int hashCode() {  
119 - final int prime = 31;  
120 - int result = super.hashCode();  
121 - result = prime * result + ((address == null) ? 0 : address.hashCode());  
122 - result = prime * result + ((address2 == null) ? 0 : address2.hashCode());  
123 - result = prime * result + ((city == null) ? 0 : city.hashCode());  
124 - result = prime * result + ((country == null) ? 0 : country.hashCode());  
125 - result = prime * result + ((email == null) ? 0 : email.hashCode());  
126 - result = prime * result + ((phone == null) ? 0 : phone.hashCode());  
127 - result = prime * result + ((state == null) ? 0 : state.hashCode());  
128 - result = prime * result + ((zip == null) ? 0 : zip.hashCode());  
129 - return result;  
130 - }  
131 -  
132 - @SuppressWarnings("rawtypes")  
133 - @Override  
134 - public boolean equals(Object obj) {  
135 - if (this == obj)  
136 - return true;  
137 - if (!super.equals(obj))  
138 - return false;  
139 - if (getClass() != obj.getClass())  
140 - return false;  
141 - ContactBased other = (ContactBased) obj;  
142 - if (address == null) {  
143 - if (other.address != null)  
144 - return false;  
145 - } else if (!address.equals(other.address))  
146 - return false;  
147 - if (address2 == null) {  
148 - if (other.address2 != null)  
149 - return false;  
150 - } else if (!address2.equals(other.address2))  
151 - return false;  
152 - if (city == null) {  
153 - if (other.city != null)  
154 - return false;  
155 - } else if (!city.equals(other.city))  
156 - return false;  
157 - if (country == null) {  
158 - if (other.country != null)  
159 - return false;  
160 - } else if (!country.equals(other.country))  
161 - return false;  
162 - if (email == null) {  
163 - if (other.email != null)  
164 - return false;  
165 - } else if (!email.equals(other.email))  
166 - return false;  
167 - if (phone == null) {  
168 - if (other.phone != null)  
169 - return false;  
170 - } else if (!phone.equals(other.phone))  
171 - return false;  
172 - if (state == null) {  
173 - if (other.state != null)  
174 - return false;  
175 - } else if (!state.equals(other.state))  
176 - return false;  
177 - if (zip == null) {  
178 - if (other.zip != null)  
179 - return false;  
180 - } else if (!zip.equals(other.zip))  
181 - return false;  
182 - return true;  
183 - }  
184 -  
185 } 119 }
@@ -29,7 +29,7 @@ public class Customer extends ContactBased<CustomerId> implements HasName { @@ -29,7 +29,7 @@ public class Customer extends ContactBased<CustomerId> implements HasName {
29 29
30 private String title; 30 private String title;
31 private TenantId tenantId; 31 private TenantId tenantId;
32 - private JsonNode additionalInfo; 32 + private transient JsonNode additionalInfo;
33 33
34 public Customer() { 34 public Customer() {
35 super(); 35 super();
@@ -87,7 +87,7 @@ public class Customer extends ContactBased<CustomerId> implements HasName { @@ -87,7 +87,7 @@ public class Customer extends ContactBased<CustomerId> implements HasName {
87 87
88 @Override 88 @Override
89 public String getSearchText() { 89 public String getSearchText() {
90 - return title; 90 + return getTitle();
91 } 91 }
92 92
93 @Override 93 @Override
@@ -22,7 +22,7 @@ public class Dashboard extends DashboardInfo { @@ -22,7 +22,7 @@ public class Dashboard extends DashboardInfo {
22 22
23 private static final long serialVersionUID = 872682138346187503L; 23 private static final long serialVersionUID = 872682138346187503L;
24 24
25 - private JsonNode configuration; 25 + private transient JsonNode configuration;
26 26
27 public Dashboard() { 27 public Dashboard() {
28 super(); 28 super();
@@ -73,7 +73,7 @@ public class DashboardInfo extends SearchTextBased<DashboardId> implements HasNa @@ -73,7 +73,7 @@ public class DashboardInfo extends SearchTextBased<DashboardId> implements HasNa
73 73
74 @Override 74 @Override
75 public String getSearchText() { 75 public String getSearchText() {
76 - return title; 76 + return getTitle();
77 } 77 }
78 78
79 @Override 79 @Override
@@ -29,7 +29,9 @@ public class DataConstants { @@ -29,7 +29,9 @@ public class DataConstants {
29 public static final String SERVER_SCOPE = "SERVER_SCOPE"; 29 public static final String SERVER_SCOPE = "SERVER_SCOPE";
30 public static final String SHARED_SCOPE = "SHARED_SCOPE"; 30 public static final String SHARED_SCOPE = "SHARED_SCOPE";
31 31
32 - public static final String[] ALL_SCOPES = {CLIENT_SCOPE, SHARED_SCOPE, SERVER_SCOPE}; 32 + public static final String[] allScopes() {
  33 + return new String[]{CLIENT_SCOPE, SHARED_SCOPE, SERVER_SCOPE};
  34 + }
33 35
34 public static final String ALARM = "ALARM"; 36 public static final String ALARM = "ALARM";
35 public static final String ERROR = "ERROR"; 37 public static final String ERROR = "ERROR";
@@ -15,12 +15,14 @@ @@ -15,12 +15,14 @@
15 */ 15 */
16 package org.thingsboard.server.common.data; 16 package org.thingsboard.server.common.data;
17 17
  18 +import lombok.EqualsAndHashCode;
18 import org.thingsboard.server.common.data.id.CustomerId; 19 import org.thingsboard.server.common.data.id.CustomerId;
19 import org.thingsboard.server.common.data.id.DeviceId; 20 import org.thingsboard.server.common.data.id.DeviceId;
20 import org.thingsboard.server.common.data.id.TenantId; 21 import org.thingsboard.server.common.data.id.TenantId;
21 22
22 import com.fasterxml.jackson.databind.JsonNode; 23 import com.fasterxml.jackson.databind.JsonNode;
23 24
  25 +@EqualsAndHashCode(callSuper = true)
24 public class Device extends SearchTextBased<DeviceId> implements HasName { 26 public class Device extends SearchTextBased<DeviceId> implements HasName {
25 27
26 private static final long serialVersionUID = 2807343040519543363L; 28 private static final long serialVersionUID = 2807343040519543363L;
@@ -29,7 +31,7 @@ public class Device extends SearchTextBased<DeviceId> implements HasName { @@ -29,7 +31,7 @@ public class Device extends SearchTextBased<DeviceId> implements HasName {
29 private CustomerId customerId; 31 private CustomerId customerId;
30 private String name; 32 private String name;
31 private String type; 33 private String type;
32 - private JsonNode additionalInfo; 34 + private transient JsonNode additionalInfo;
33 35
34 public Device() { 36 public Device() {
35 super(); 37 super();
@@ -91,56 +93,7 @@ public class Device extends SearchTextBased<DeviceId> implements HasName { @@ -91,56 +93,7 @@ public class Device extends SearchTextBased<DeviceId> implements HasName {
91 93
92 @Override 94 @Override
93 public String getSearchText() { 95 public String getSearchText() {
94 - return name;  
95 - }  
96 -  
97 - @Override  
98 - public int hashCode() {  
99 - final int prime = 31;  
100 - int result = super.hashCode();  
101 - result = prime * result + ((additionalInfo == null) ? 0 : additionalInfo.hashCode());  
102 - result = prime * result + ((customerId == null) ? 0 : customerId.hashCode());  
103 - result = prime * result + ((name == null) ? 0 : name.hashCode());  
104 - result = prime * result + ((type == null) ? 0 : type.hashCode());  
105 - result = prime * result + ((tenantId == null) ? 0 : tenantId.hashCode());  
106 - return result;  
107 - }  
108 -  
109 - @Override  
110 - public boolean equals(Object obj) {  
111 - if (this == obj)  
112 - return true;  
113 - if (!super.equals(obj))  
114 - return false;  
115 - if (getClass() != obj.getClass())  
116 - return false;  
117 - Device other = (Device) obj;  
118 - if (additionalInfo == null) {  
119 - if (other.additionalInfo != null)  
120 - return false;  
121 - } else if (!additionalInfo.equals(other.additionalInfo))  
122 - return false;  
123 - if (customerId == null) {  
124 - if (other.customerId != null)  
125 - return false;  
126 - } else if (!customerId.equals(other.customerId))  
127 - return false;  
128 - if (name == null) {  
129 - if (other.name != null)  
130 - return false;  
131 - } else if (!name.equals(other.name))  
132 - return false;  
133 - if (type == null) {  
134 - if (other.type != null)  
135 - return false;  
136 - } else if (!type.equals(other.type))  
137 - return false;  
138 - if (tenantId == null) {  
139 - if (other.tenantId != null)  
140 - return false;  
141 - } else if (!tenantId.equals(other.tenantId))  
142 - return false;  
143 - return true; 96 + return getName();
144 } 97 }
145 98
146 @Override 99 @Override
@@ -31,7 +31,7 @@ public class Event extends BaseData<EventId> { @@ -31,7 +31,7 @@ public class Event extends BaseData<EventId> {
31 private String type; 31 private String type;
32 private String uid; 32 private String uid;
33 private EntityId entityId; 33 private EntityId entityId;
34 - private JsonNode body; 34 + private transient JsonNode body;
35 35
36 public Event() { 36 public Event() {
37 super(); 37 super();
@@ -16,17 +16,19 @@ @@ -16,17 +16,19 @@
16 package org.thingsboard.server.common.data; 16 package org.thingsboard.server.common.data;
17 17
18 import com.fasterxml.jackson.annotation.JsonProperty; 18 import com.fasterxml.jackson.annotation.JsonProperty;
  19 +import lombok.EqualsAndHashCode;
19 import org.thingsboard.server.common.data.id.TenantId; 20 import org.thingsboard.server.common.data.id.TenantId;
20 21
21 import com.fasterxml.jackson.databind.JsonNode; 22 import com.fasterxml.jackson.databind.JsonNode;
22 23
  24 +@EqualsAndHashCode(callSuper = true)
23 public class Tenant extends ContactBased<TenantId> implements HasName { 25 public class Tenant extends ContactBased<TenantId> implements HasName {
24 26
25 private static final long serialVersionUID = 8057243243859922101L; 27 private static final long serialVersionUID = 8057243243859922101L;
26 28
27 private String title; 29 private String title;
28 private String region; 30 private String region;
29 - private JsonNode additionalInfo; 31 + private transient JsonNode additionalInfo;
30 32
31 public Tenant() { 33 public Tenant() {
32 super(); 34 super();
@@ -75,44 +77,7 @@ public class Tenant extends ContactBased<TenantId> implements HasName { @@ -75,44 +77,7 @@ public class Tenant extends ContactBased<TenantId> implements HasName {
75 77
76 @Override 78 @Override
77 public String getSearchText() { 79 public String getSearchText() {
78 - return title;  
79 - }  
80 -  
81 - @Override  
82 - public int hashCode() {  
83 - final int prime = 31;  
84 - int result = super.hashCode();  
85 - result = prime * result + ((additionalInfo == null) ? 0 : additionalInfo.hashCode());  
86 - result = prime * result + ((region == null) ? 0 : region.hashCode());  
87 - result = prime * result + ((title == null) ? 0 : title.hashCode());  
88 - return result;  
89 - }  
90 -  
91 - @Override  
92 - public boolean equals(Object obj) {  
93 - if (this == obj)  
94 - return true;  
95 - if (!super.equals(obj))  
96 - return false;  
97 - if (getClass() != obj.getClass())  
98 - return false;  
99 - Tenant other = (Tenant) obj;  
100 - if (additionalInfo == null) {  
101 - if (other.additionalInfo != null)  
102 - return false;  
103 - } else if (!additionalInfo.equals(other.additionalInfo))  
104 - return false;  
105 - if (region == null) {  
106 - if (other.region != null)  
107 - return false;  
108 - } else if (!region.equals(other.region))  
109 - return false;  
110 - if (title == null) {  
111 - if (other.title != null)  
112 - return false;  
113 - } else if (!title.equals(other.title))  
114 - return false;  
115 - return true; 80 + return getTitle();
116 } 81 }
117 82
118 @Override 83 @Override
@@ -16,6 +16,7 @@ @@ -16,6 +16,7 @@
16 package org.thingsboard.server.common.data; 16 package org.thingsboard.server.common.data;
17 17
18 import com.fasterxml.jackson.annotation.JsonProperty; 18 import com.fasterxml.jackson.annotation.JsonProperty;
  19 +import lombok.EqualsAndHashCode;
19 import org.thingsboard.server.common.data.id.CustomerId; 20 import org.thingsboard.server.common.data.id.CustomerId;
20 import org.thingsboard.server.common.data.id.TenantId; 21 import org.thingsboard.server.common.data.id.TenantId;
21 import org.thingsboard.server.common.data.id.UserId; 22 import org.thingsboard.server.common.data.id.UserId;
@@ -23,6 +24,7 @@ import org.thingsboard.server.common.data.security.Authority; @@ -23,6 +24,7 @@ import org.thingsboard.server.common.data.security.Authority;
23 24
24 import com.fasterxml.jackson.databind.JsonNode; 25 import com.fasterxml.jackson.databind.JsonNode;
25 26
  27 +@EqualsAndHashCode(callSuper = true)
26 public class User extends SearchTextBased<UserId> implements HasName { 28 public class User extends SearchTextBased<UserId> implements HasName {
27 29
28 private static final long serialVersionUID = 8250339805336035966L; 30 private static final long serialVersionUID = 8250339805336035966L;
@@ -33,7 +35,7 @@ public class User extends SearchTextBased<UserId> implements HasName { @@ -33,7 +35,7 @@ public class User extends SearchTextBased<UserId> implements HasName {
33 private Authority authority; 35 private Authority authority;
34 private String firstName; 36 private String firstName;
35 private String lastName; 37 private String lastName;
36 - private JsonNode additionalInfo; 38 + private transient JsonNode additionalInfo;
37 39
38 public User() { 40 public User() {
39 super(); 41 super();
@@ -118,65 +120,7 @@ public class User extends SearchTextBased<UserId> implements HasName { @@ -118,65 +120,7 @@ public class User extends SearchTextBased<UserId> implements HasName {
118 120
119 @Override 121 @Override
120 public String getSearchText() { 122 public String getSearchText() {
121 - return email;  
122 - }  
123 -  
124 - @Override  
125 - public int hashCode() {  
126 - final int prime = 31;  
127 - int result = super.hashCode();  
128 - result = prime * result + ((additionalInfo == null) ? 0 : additionalInfo.hashCode());  
129 - result = prime * result + ((authority == null) ? 0 : authority.hashCode());  
130 - result = prime * result + ((customerId == null) ? 0 : customerId.hashCode());  
131 - result = prime * result + ((email == null) ? 0 : email.hashCode());  
132 - result = prime * result + ((firstName == null) ? 0 : firstName.hashCode());  
133 - result = prime * result + ((lastName == null) ? 0 : lastName.hashCode());  
134 - result = prime * result + ((tenantId == null) ? 0 : tenantId.hashCode());  
135 - return result;  
136 - }  
137 -  
138 - @Override  
139 - public boolean equals(Object obj) {  
140 - if (this == obj)  
141 - return true;  
142 - if (!super.equals(obj))  
143 - return false;  
144 - if (getClass() != obj.getClass())  
145 - return false;  
146 - User other = (User) obj;  
147 - if (additionalInfo == null) {  
148 - if (other.additionalInfo != null)  
149 - return false;  
150 - } else if (!additionalInfo.equals(other.additionalInfo))  
151 - return false;  
152 - if (authority != other.authority)  
153 - return false;  
154 - if (customerId == null) {  
155 - if (other.customerId != null)  
156 - return false;  
157 - } else if (!customerId.equals(other.customerId))  
158 - return false;  
159 - if (email == null) {  
160 - if (other.email != null)  
161 - return false;  
162 - } else if (!email.equals(other.email))  
163 - return false;  
164 - if (firstName == null) {  
165 - if (other.firstName != null)  
166 - return false;  
167 - } else if (!firstName.equals(other.firstName))  
168 - return false;  
169 - if (lastName == null) {  
170 - if (other.lastName != null)  
171 - return false;  
172 - } else if (!lastName.equals(other.lastName))  
173 - return false;  
174 - if (tenantId == null) {  
175 - if (other.tenantId != null)  
176 - return false;  
177 - } else if (!tenantId.equals(other.tenantId))  
178 - return false;  
179 - return true; 123 + return getEmail();
180 } 124 }
181 125
182 @Override 126 @Override
@@ -42,7 +42,7 @@ public class Alarm extends BaseData<AlarmId> implements HasName { @@ -42,7 +42,7 @@ public class Alarm extends BaseData<AlarmId> implements HasName {
42 private long endTs; 42 private long endTs;
43 private long ackTs; 43 private long ackTs;
44 private long clearTs; 44 private long clearTs;
45 - private JsonNode details; 45 + private transient JsonNode details;
46 private boolean propagate; 46 private boolean propagate;
47 47
48 public Alarm() { 48 public Alarm() {
@@ -16,12 +16,14 @@ @@ -16,12 +16,14 @@
16 package org.thingsboard.server.common.data.asset; 16 package org.thingsboard.server.common.data.asset;
17 17
18 import com.fasterxml.jackson.databind.JsonNode; 18 import com.fasterxml.jackson.databind.JsonNode;
  19 +import lombok.EqualsAndHashCode;
19 import org.thingsboard.server.common.data.HasName; 20 import org.thingsboard.server.common.data.HasName;
20 import org.thingsboard.server.common.data.SearchTextBased; 21 import org.thingsboard.server.common.data.SearchTextBased;
21 import org.thingsboard.server.common.data.id.AssetId; 22 import org.thingsboard.server.common.data.id.AssetId;
22 import org.thingsboard.server.common.data.id.CustomerId; 23 import org.thingsboard.server.common.data.id.CustomerId;
23 import org.thingsboard.server.common.data.id.TenantId; 24 import org.thingsboard.server.common.data.id.TenantId;
24 25
  26 +@EqualsAndHashCode(callSuper = true)
25 public class Asset extends SearchTextBased<AssetId> implements HasName { 27 public class Asset extends SearchTextBased<AssetId> implements HasName {
26 28
27 private static final long serialVersionUID = 2807343040519543363L; 29 private static final long serialVersionUID = 2807343040519543363L;
@@ -30,7 +32,7 @@ public class Asset extends SearchTextBased<AssetId> implements HasName { @@ -30,7 +32,7 @@ public class Asset extends SearchTextBased<AssetId> implements HasName {
30 private CustomerId customerId; 32 private CustomerId customerId;
31 private String name; 33 private String name;
32 private String type; 34 private String type;
33 - private JsonNode additionalInfo; 35 + private transient JsonNode additionalInfo;
34 36
35 public Asset() { 37 public Asset() {
36 super(); 38 super();
@@ -92,56 +94,7 @@ public class Asset extends SearchTextBased<AssetId> implements HasName { @@ -92,56 +94,7 @@ public class Asset extends SearchTextBased<AssetId> implements HasName {
92 94
93 @Override 95 @Override
94 public String getSearchText() { 96 public String getSearchText() {
95 - return name;  
96 - }  
97 -  
98 - @Override  
99 - public int hashCode() {  
100 - final int prime = 31;  
101 - int result = super.hashCode();  
102 - result = prime * result + ((additionalInfo == null) ? 0 : additionalInfo.hashCode());  
103 - result = prime * result + ((customerId == null) ? 0 : customerId.hashCode());  
104 - result = prime * result + ((name == null) ? 0 : name.hashCode());  
105 - result = prime * result + ((type == null) ? 0 : type.hashCode());  
106 - result = prime * result + ((tenantId == null) ? 0 : tenantId.hashCode());  
107 - return result;  
108 - }  
109 -  
110 - @Override  
111 - public boolean equals(Object obj) {  
112 - if (this == obj)  
113 - return true;  
114 - if (!super.equals(obj))  
115 - return false;  
116 - if (getClass() != obj.getClass())  
117 - return false;  
118 - Asset other = (Asset) obj;  
119 - if (additionalInfo == null) {  
120 - if (other.additionalInfo != null)  
121 - return false;  
122 - } else if (!additionalInfo.equals(other.additionalInfo))  
123 - return false;  
124 - if (customerId == null) {  
125 - if (other.customerId != null)  
126 - return false;  
127 - } else if (!customerId.equals(other.customerId))  
128 - return false;  
129 - if (name == null) {  
130 - if (other.name != null)  
131 - return false;  
132 - } else if (!name.equals(other.name))  
133 - return false;  
134 - if (type == null) {  
135 - if (other.type != null)  
136 - return false;  
137 - } else if (!type.equals(other.type))  
138 - return false;  
139 - if (tenantId == null) {  
140 - if (other.tenantId != null)  
141 - return false;  
142 - } else if (!tenantId.equals(other.tenantId))  
143 - return false;  
144 - return true; 97 + return getName();
145 } 98 }
146 99
147 @Override 100 @Override
@@ -20,6 +20,7 @@ import com.fasterxml.jackson.databind.annotation.JsonDeserialize; @@ -20,6 +20,7 @@ import com.fasterxml.jackson.databind.annotation.JsonDeserialize;
20 import com.fasterxml.jackson.databind.annotation.JsonSerialize; 20 import com.fasterxml.jackson.databind.annotation.JsonSerialize;
21 import org.thingsboard.server.common.data.EntityType; 21 import org.thingsboard.server.common.data.EntityType;
22 22
  23 +import java.io.Serializable;
23 import java.util.UUID; 24 import java.util.UUID;
24 25
25 /** 26 /**
@@ -28,7 +29,7 @@ import java.util.UUID; @@ -28,7 +29,7 @@ import java.util.UUID;
28 29
29 @JsonDeserialize(using = EntityIdDeserializer.class) 30 @JsonDeserialize(using = EntityIdDeserializer.class)
30 @JsonSerialize(using = EntityIdSerializer.class) 31 @JsonSerialize(using = EntityIdSerializer.class)
31 -public interface EntityId { 32 +public interface EntityId extends Serializable { //NOSONAR, the constant is closely related to EntityId
32 33
33 UUID NULL_UUID = UUID.fromString("13814000-1dd2-11b2-8080-808080808080"); 34 UUID NULL_UUID = UUID.fromString("13814000-1dd2-11b2-8080-808080808080");
34 35
@@ -17,6 +17,7 @@ package org.thingsboard.server.common.data.page; @@ -17,6 +17,7 @@ package org.thingsboard.server.common.data.page;
17 17
18 import java.util.Iterator; 18 import java.util.Iterator;
19 import java.util.List; 19 import java.util.List;
  20 +import java.util.NoSuchElementException;
20 21
21 import org.thingsboard.server.common.data.SearchTextBased; 22 import org.thingsboard.server.common.data.SearchTextBased;
22 import org.thingsboard.server.common.data.id.UUIDBased; 23 import org.thingsboard.server.common.data.id.UUIDBased;
@@ -54,7 +55,7 @@ public class PageDataIterable<T extends SearchTextBased<? extends UUIDBased>> im @@ -54,7 +55,7 @@ public class PageDataIterable<T extends SearchTextBased<? extends UUIDBased>> im
54 fetch(nextPackLink); 55 fetch(nextPackLink);
55 } 56 }
56 } 57 }
57 - return currentIdx != currentItems.size(); 58 + return currentIdx < currentItems.size();
58 } 59 }
59 60
60 private void fetch(TextPageLink link) { 61 private void fetch(TextPageLink link) {
@@ -67,6 +68,9 @@ public class PageDataIterable<T extends SearchTextBased<? extends UUIDBased>> im @@ -67,6 +68,9 @@ public class PageDataIterable<T extends SearchTextBased<? extends UUIDBased>> im
67 68
68 @Override 69 @Override
69 public T next() { 70 public T next() {
  71 + if(!hasNext()){
  72 + throw new NoSuchElementException();
  73 + }
70 return currentItems.get(currentIdx++); 74 return currentItems.get(currentIdx++);
71 } 75 }
72 76
@@ -32,7 +32,7 @@ public class ComponentDescriptor extends SearchTextBased<ComponentDescriptorId> @@ -32,7 +32,7 @@ public class ComponentDescriptor extends SearchTextBased<ComponentDescriptorId>
32 @Getter @Setter private ComponentScope scope; 32 @Getter @Setter private ComponentScope scope;
33 @Getter @Setter private String name; 33 @Getter @Setter private String name;
34 @Getter @Setter private String clazz; 34 @Getter @Setter private String clazz;
35 - @Getter @Setter private JsonNode configurationDescriptor; 35 + @Getter @Setter private transient JsonNode configurationDescriptor;
36 @Getter @Setter private String actions; 36 @Getter @Setter private String actions;
37 37
38 public ComponentDescriptor() { 38 public ComponentDescriptor() {
@@ -15,6 +15,7 @@ @@ -15,6 +15,7 @@
15 */ 15 */
16 package org.thingsboard.server.common.data.plugin; 16 package org.thingsboard.server.common.data.plugin;
17 17
  18 +import lombok.EqualsAndHashCode;
18 import org.thingsboard.server.common.data.HasName; 19 import org.thingsboard.server.common.data.HasName;
19 import org.thingsboard.server.common.data.SearchTextBased; 20 import org.thingsboard.server.common.data.SearchTextBased;
20 import org.thingsboard.server.common.data.id.PluginId; 21 import org.thingsboard.server.common.data.id.PluginId;
@@ -22,6 +23,7 @@ import org.thingsboard.server.common.data.id.TenantId; @@ -22,6 +23,7 @@ import org.thingsboard.server.common.data.id.TenantId;
22 23
23 import com.fasterxml.jackson.databind.JsonNode; 24 import com.fasterxml.jackson.databind.JsonNode;
24 25
  26 +@EqualsAndHashCode(callSuper = true)
25 public class PluginMetaData extends SearchTextBased<PluginId> implements HasName { 27 public class PluginMetaData extends SearchTextBased<PluginId> implements HasName {
26 28
27 private static final long serialVersionUID = 1L; 29 private static final long serialVersionUID = 1L;
@@ -32,8 +34,8 @@ public class PluginMetaData extends SearchTextBased<PluginId> implements HasName @@ -32,8 +34,8 @@ public class PluginMetaData extends SearchTextBased<PluginId> implements HasName
32 private String clazz; 34 private String clazz;
33 private boolean publicAccess; 35 private boolean publicAccess;
34 private ComponentLifecycleState state; 36 private ComponentLifecycleState state;
35 - private JsonNode configuration;  
36 - private JsonNode additionalInfo; 37 + private transient JsonNode configuration;
  38 + private transient JsonNode additionalInfo;
37 39
38 public PluginMetaData() { 40 public PluginMetaData() {
39 super(); 41 super();
@@ -57,7 +59,7 @@ public class PluginMetaData extends SearchTextBased<PluginId> implements HasName @@ -57,7 +59,7 @@ public class PluginMetaData extends SearchTextBased<PluginId> implements HasName
57 59
58 @Override 60 @Override
59 public String getSearchText() { 61 public String getSearchText() {
60 - return name; 62 + return getName();
61 } 63 }
62 64
63 public String getApiToken() { 65 public String getApiToken() {
@@ -126,49 +128,6 @@ public class PluginMetaData extends SearchTextBased<PluginId> implements HasName @@ -126,49 +128,6 @@ public class PluginMetaData extends SearchTextBased<PluginId> implements HasName
126 } 128 }
127 129
128 @Override 130 @Override
129 - public int hashCode() {  
130 - final int prime = 31;  
131 - int result = super.hashCode();  
132 - result = prime * result + ((apiToken == null) ? 0 : apiToken.hashCode());  
133 - result = prime * result + ((clazz == null) ? 0 : clazz.hashCode());  
134 - result = prime * result + ((name == null) ? 0 : name.hashCode());  
135 - result = prime * result + ((tenantId == null) ? 0 : tenantId.hashCode());  
136 - return result;  
137 - }  
138 -  
139 - @Override  
140 - public boolean equals(Object obj) {  
141 - if (this == obj)  
142 - return true;  
143 - if (!super.equals(obj))  
144 - return false;  
145 - if (getClass() != obj.getClass())  
146 - return false;  
147 - PluginMetaData other = (PluginMetaData) obj;  
148 - if (apiToken == null) {  
149 - if (other.apiToken != null)  
150 - return false;  
151 - } else if (!apiToken.equals(other.apiToken))  
152 - return false;  
153 - if (clazz == null) {  
154 - if (other.clazz != null)  
155 - return false;  
156 - } else if (!clazz.equals(other.clazz))  
157 - return false;  
158 - if (name == null) {  
159 - if (other.name != null)  
160 - return false;  
161 - } else if (!name.equals(other.name))  
162 - return false;  
163 - if (tenantId == null) {  
164 - if (other.tenantId != null)  
165 - return false;  
166 - } else if (!tenantId.equals(other.tenantId))  
167 - return false;  
168 - return true;  
169 - }  
170 -  
171 - @Override  
172 public String toString() { 131 public String toString() {
173 return "PluginMetaData [apiToken=" + apiToken + ", tenantId=" + tenantId + ", name=" + name + ", clazz=" + clazz + ", publicAccess=" + publicAccess 132 return "PluginMetaData [apiToken=" + apiToken + ", tenantId=" + tenantId + ", name=" + name + ", clazz=" + clazz + ", publicAccess=" + publicAccess
174 + ", configuration=" + configuration + "]"; 133 + ", configuration=" + configuration + "]";
@@ -35,10 +35,10 @@ public class RuleMetaData extends SearchTextBased<RuleId> implements HasName { @@ -35,10 +35,10 @@ public class RuleMetaData extends SearchTextBased<RuleId> implements HasName {
35 private ComponentLifecycleState state; 35 private ComponentLifecycleState state;
36 private int weight; 36 private int weight;
37 private String pluginToken; 37 private String pluginToken;
38 - private JsonNode filters;  
39 - private JsonNode processor;  
40 - private JsonNode action;  
41 - private JsonNode additionalInfo; 38 + private transient JsonNode filters;
  39 + private transient JsonNode processor;
  40 + private transient JsonNode action;
  41 + private transient JsonNode additionalInfo;
42 42
43 public RuleMetaData() { 43 public RuleMetaData() {
44 super(); 44 super();
@@ -63,7 +63,7 @@ public class RuleMetaData extends SearchTextBased<RuleId> implements HasName { @@ -63,7 +63,7 @@ public class RuleMetaData extends SearchTextBased<RuleId> implements HasName {
63 63
64 @Override 64 @Override
65 public String getSearchText() { 65 public String getSearchText() {
66 - return name; 66 + return getName();
67 } 67 }
68 68
69 @Override 69 @Override
@@ -15,10 +15,12 @@ @@ -15,10 +15,12 @@
15 */ 15 */
16 package org.thingsboard.server.common.data.security; 16 package org.thingsboard.server.common.data.security;
17 17
  18 +import lombok.EqualsAndHashCode;
18 import org.thingsboard.server.common.data.BaseData; 19 import org.thingsboard.server.common.data.BaseData;
19 import org.thingsboard.server.common.data.id.DeviceCredentialsId; 20 import org.thingsboard.server.common.data.id.DeviceCredentialsId;
20 import org.thingsboard.server.common.data.id.DeviceId; 21 import org.thingsboard.server.common.data.id.DeviceId;
21 22
  23 +@EqualsAndHashCode(callSuper = true)
22 public class DeviceCredentials extends BaseData<DeviceCredentialsId> implements DeviceCredentialsFilter { 24 public class DeviceCredentials extends BaseData<DeviceCredentialsId> implements DeviceCredentialsFilter {
23 25
24 private static final long serialVersionUID = -7869261127032877765L; 26 private static final long serialVersionUID = -7869261127032877765L;
@@ -79,46 +81,6 @@ public class DeviceCredentials extends BaseData<DeviceCredentialsId> implements @@ -79,46 +81,6 @@ public class DeviceCredentials extends BaseData<DeviceCredentialsId> implements
79 } 81 }
80 82
81 @Override 83 @Override
82 - public int hashCode() {  
83 - final int prime = 31;  
84 - int result = super.hashCode();  
85 - result = prime * result + ((credentialsId == null) ? 0 : credentialsId.hashCode());  
86 - result = prime * result + ((credentialsType == null) ? 0 : credentialsType.hashCode());  
87 - result = prime * result + ((credentialsValue == null) ? 0 : credentialsValue.hashCode());  
88 - result = prime * result + ((deviceId == null) ? 0 : deviceId.hashCode());  
89 - return result;  
90 - }  
91 -  
92 - @Override  
93 - public boolean equals(Object obj) {  
94 - if (this == obj)  
95 - return true;  
96 - if (!super.equals(obj))  
97 - return false;  
98 - if (getClass() != obj.getClass())  
99 - return false;  
100 - DeviceCredentials other = (DeviceCredentials) obj;  
101 - if (credentialsId == null) {  
102 - if (other.credentialsId != null)  
103 - return false;  
104 - } else if (!credentialsId.equals(other.credentialsId))  
105 - return false;  
106 - if (credentialsType != other.credentialsType)  
107 - return false;  
108 - if (credentialsValue == null) {  
109 - if (other.credentialsValue != null)  
110 - return false;  
111 - } else if (!credentialsValue.equals(other.credentialsValue))  
112 - return false;  
113 - if (deviceId == null) {  
114 - if (other.deviceId != null)  
115 - return false;  
116 - } else if (!deviceId.equals(other.deviceId))  
117 - return false;  
118 - return true;  
119 - }  
120 -  
121 - @Override  
122 public String toString() { 84 public String toString() {
123 return "DeviceCredentials [deviceId=" + deviceId + ", credentialsType=" + credentialsType + ", credentialsId=" 85 return "DeviceCredentials [deviceId=" + deviceId + ", credentialsType=" + credentialsType + ", credentialsId="
124 + credentialsId + ", credentialsValue=" + credentialsValue + ", createdTime=" + createdTime + ", id=" 86 + credentialsId + ", credentialsValue=" + credentialsValue + ", createdTime=" + createdTime + ", id="
@@ -15,10 +15,12 @@ @@ -15,10 +15,12 @@
15 */ 15 */
16 package org.thingsboard.server.common.data.security; 16 package org.thingsboard.server.common.data.security;
17 17
  18 +import lombok.EqualsAndHashCode;
18 import org.thingsboard.server.common.data.BaseData; 19 import org.thingsboard.server.common.data.BaseData;
19 import org.thingsboard.server.common.data.id.UserCredentialsId; 20 import org.thingsboard.server.common.data.id.UserCredentialsId;
20 import org.thingsboard.server.common.data.id.UserId; 21 import org.thingsboard.server.common.data.id.UserId;
21 22
  23 +@EqualsAndHashCode(callSuper = true)
22 public class UserCredentials extends BaseData<UserCredentialsId> { 24 public class UserCredentials extends BaseData<UserCredentialsId> {
23 25
24 private static final long serialVersionUID = -2108436378880529163L; 26 private static final long serialVersionUID = -2108436378880529163L;
@@ -87,52 +89,6 @@ public class UserCredentials extends BaseData<UserCredentialsId> { @@ -87,52 +89,6 @@ public class UserCredentials extends BaseData<UserCredentialsId> {
87 } 89 }
88 90
89 @Override 91 @Override
90 - public int hashCode() {  
91 - final int prime = 31;  
92 - int result = super.hashCode();  
93 - result = prime * result + ((activateToken == null) ? 0 : activateToken.hashCode());  
94 - result = prime * result + (enabled ? 1231 : 1237);  
95 - result = prime * result + ((password == null) ? 0 : password.hashCode());  
96 - result = prime * result + ((resetToken == null) ? 0 : resetToken.hashCode());  
97 - result = prime * result + ((userId == null) ? 0 : userId.hashCode());  
98 - return result;  
99 - }  
100 -  
101 - @Override  
102 - public boolean equals(Object obj) {  
103 - if (this == obj)  
104 - return true;  
105 - if (!super.equals(obj))  
106 - return false;  
107 - if (getClass() != obj.getClass())  
108 - return false;  
109 - UserCredentials other = (UserCredentials) obj;  
110 - if (activateToken == null) {  
111 - if (other.activateToken != null)  
112 - return false;  
113 - } else if (!activateToken.equals(other.activateToken))  
114 - return false;  
115 - if (enabled != other.enabled)  
116 - return false;  
117 - if (password == null) {  
118 - if (other.password != null)  
119 - return false;  
120 - } else if (!password.equals(other.password))  
121 - return false;  
122 - if (resetToken == null) {  
123 - if (other.resetToken != null)  
124 - return false;  
125 - } else if (!resetToken.equals(other.resetToken))  
126 - return false;  
127 - if (userId == null) {  
128 - if (other.userId != null)  
129 - return false;  
130 - } else if (!userId.equals(other.userId))  
131 - return false;  
132 - return true;  
133 - }  
134 -  
135 - @Override  
136 public String toString() { 92 public String toString() {
137 StringBuilder builder = new StringBuilder(); 93 StringBuilder builder = new StringBuilder();
138 builder.append("UserCredentials [userId="); 94 builder.append("UserCredentials [userId=");
@@ -16,10 +16,12 @@ @@ -16,10 +16,12 @@
16 package org.thingsboard.server.common.data.widget; 16 package org.thingsboard.server.common.data.widget;
17 17
18 import com.fasterxml.jackson.databind.JsonNode; 18 import com.fasterxml.jackson.databind.JsonNode;
  19 +import lombok.EqualsAndHashCode;
19 import org.thingsboard.server.common.data.BaseData; 20 import org.thingsboard.server.common.data.BaseData;
20 import org.thingsboard.server.common.data.id.TenantId; 21 import org.thingsboard.server.common.data.id.TenantId;
21 import org.thingsboard.server.common.data.id.WidgetTypeId; 22 import org.thingsboard.server.common.data.id.WidgetTypeId;
22 23
  24 +@EqualsAndHashCode(callSuper = true)
23 public class WidgetType extends BaseData<WidgetTypeId> { 25 public class WidgetType extends BaseData<WidgetTypeId> {
24 26
25 private static final long serialVersionUID = 8388684344603660756L; 27 private static final long serialVersionUID = 8388684344603660756L;
@@ -28,7 +30,7 @@ public class WidgetType extends BaseData<WidgetTypeId> { @@ -28,7 +30,7 @@ public class WidgetType extends BaseData<WidgetTypeId> {
28 private String bundleAlias; 30 private String bundleAlias;
29 private String alias; 31 private String alias;
30 private String name; 32 private String name;
31 - private JsonNode descriptor; 33 + private transient JsonNode descriptor;
32 34
33 public WidgetType() { 35 public WidgetType() {
34 super(); 36 super();
@@ -88,33 +90,6 @@ public class WidgetType extends BaseData<WidgetTypeId> { @@ -88,33 +90,6 @@ public class WidgetType extends BaseData<WidgetTypeId> {
88 } 90 }
89 91
90 @Override 92 @Override
91 - public int hashCode() {  
92 - int result = super.hashCode();  
93 - result = 31 * result + (tenantId != null ? tenantId.hashCode() : 0);  
94 - result = 31 * result + (bundleAlias != null ? bundleAlias.hashCode() : 0);  
95 - result = 31 * result + (alias != null ? alias.hashCode() : 0);  
96 - result = 31 * result + (name != null ? name.hashCode() : 0);  
97 - result = 31 * result + (descriptor != null ? descriptor.hashCode() : 0);  
98 - return result;  
99 - }  
100 -  
101 - @Override  
102 - public boolean equals(Object o) {  
103 - if (this == o) return true;  
104 - if (o == null || getClass() != o.getClass()) return false;  
105 - if (!super.equals(o)) return false;  
106 -  
107 - WidgetType that = (WidgetType) o;  
108 -  
109 - if (tenantId != null ? !tenantId.equals(that.tenantId) : that.tenantId != null) return false;  
110 - if (bundleAlias != null ? !bundleAlias.equals(that.bundleAlias) : that.bundleAlias != null) return false;  
111 - if (alias != null ? !alias.equals(that.alias) : that.alias != null) return false;  
112 - if (name != null ? !name.equals(that.name) : that.name != null) return false;  
113 - return descriptor != null ? descriptor.equals(that.descriptor) : that.descriptor == null;  
114 -  
115 - }  
116 -  
117 - @Override  
118 public String toString() { 93 public String toString() {
119 final StringBuilder sb = new StringBuilder("WidgetType{"); 94 final StringBuilder sb = new StringBuilder("WidgetType{");
120 sb.append("tenantId=").append(tenantId); 95 sb.append("tenantId=").append(tenantId);
@@ -80,7 +80,7 @@ public class WidgetsBundle extends SearchTextBased<WidgetsBundleId> { @@ -80,7 +80,7 @@ public class WidgetsBundle extends SearchTextBased<WidgetsBundleId> {
80 80
81 @Override 81 @Override
82 public String getSearchText() { 82 public String getSearchText() {
83 - return title; 83 + return getTitle();
84 } 84 }
85 85
86 @Override 86 @Override
@@ -30,6 +30,7 @@ import org.thingsboard.server.common.msg.kv.AttributesKVMsg; @@ -30,6 +30,7 @@ import org.thingsboard.server.common.msg.kv.AttributesKVMsg;
30 public class JsonConverter { 30 public class JsonConverter {
31 31
32 private static final Gson GSON = new Gson(); 32 private static final Gson GSON = new Gson();
  33 + public static final String CAN_T_PARSE_VALUE = "Can't parse value: ";
33 34
34 public static TelemetryUploadRequest convertToTelemetry(JsonElement jsonObject) throws JsonSyntaxException { 35 public static TelemetryUploadRequest convertToTelemetry(JsonElement jsonObject) throws JsonSyntaxException {
35 return convertToTelemetry(jsonObject, BasicRequest.DEFAULT_REQUEST_ID); 36 return convertToTelemetry(jsonObject, BasicRequest.DEFAULT_REQUEST_ID);
@@ -45,11 +46,11 @@ public class JsonConverter { @@ -45,11 +46,11 @@ public class JsonConverter {
45 if (je.isJsonObject()) { 46 if (je.isJsonObject()) {
46 parseObject(request, systemTs, je.getAsJsonObject()); 47 parseObject(request, systemTs, je.getAsJsonObject());
47 } else { 48 } else {
48 - throw new JsonSyntaxException("Can't parse value: " + je); 49 + throw new JsonSyntaxException(CAN_T_PARSE_VALUE + je);
49 } 50 }
50 }); 51 });
51 } else { 52 } else {
52 - throw new JsonSyntaxException("Can't parse value: " + jsonObject); 53 + throw new JsonSyntaxException(CAN_T_PARSE_VALUE + jsonObject);
53 } 54 }
54 return request; 55 return request;
55 } 56 }
@@ -99,10 +100,10 @@ public class JsonConverter { @@ -99,10 +100,10 @@ public class JsonConverter {
99 result.add(new LongDataEntry(valueEntry.getKey(), value.getAsLong())); 100 result.add(new LongDataEntry(valueEntry.getKey(), value.getAsLong()));
100 } 101 }
101 } else { 102 } else {
102 - throw new JsonSyntaxException("Can't parse value: " + value); 103 + throw new JsonSyntaxException(CAN_T_PARSE_VALUE + value);
103 } 104 }
104 } else { 105 } else {
105 - throw new JsonSyntaxException("Can't parse value: " + element); 106 + throw new JsonSyntaxException(CAN_T_PARSE_VALUE + element);
106 } 107 }
107 } 108 }
108 return result; 109 return result;
@@ -119,7 +120,7 @@ public class JsonConverter { @@ -119,7 +120,7 @@ public class JsonConverter {
119 request.add(parseValues(element.getAsJsonObject()).stream().map(kv -> new BaseAttributeKvEntry(kv, ts)).collect(Collectors.toList())); 120 request.add(parseValues(element.getAsJsonObject()).stream().map(kv -> new BaseAttributeKvEntry(kv, ts)).collect(Collectors.toList()));
120 return request; 121 return request;
121 } else { 122 } else {
122 - throw new JsonSyntaxException("Can't parse value: " + element); 123 + throw new JsonSyntaxException(CAN_T_PARSE_VALUE + element);
123 } 124 }
124 } 125 }
125 126
@@ -37,7 +37,6 @@ import org.thingsboard.server.dao.entity.EntityService; @@ -37,7 +37,6 @@ import org.thingsboard.server.dao.entity.EntityService;
37 import org.thingsboard.server.dao.exception.DataValidationException; 37 import org.thingsboard.server.dao.exception.DataValidationException;
38 import org.thingsboard.server.common.data.relation.EntityRelationsQuery; 38 import org.thingsboard.server.common.data.relation.EntityRelationsQuery;
39 import org.thingsboard.server.common.data.relation.EntitySearchDirection; 39 import org.thingsboard.server.common.data.relation.EntitySearchDirection;
40 -import org.thingsboard.server.dao.relation.RelationService;  
41 import org.thingsboard.server.common.data.relation.RelationsSearchParameters; 40 import org.thingsboard.server.common.data.relation.RelationsSearchParameters;
42 import org.thingsboard.server.dao.service.DataValidator; 41 import org.thingsboard.server.dao.service.DataValidator;
43 import org.thingsboard.server.dao.tenant.TenantDao; 42 import org.thingsboard.server.dao.tenant.TenantDao;
@@ -68,9 +67,6 @@ public class BaseAlarmService extends AbstractEntityService implements AlarmServ @@ -68,9 +67,6 @@ public class BaseAlarmService extends AbstractEntityService implements AlarmServ
68 private TenantDao tenantDao; 67 private TenantDao tenantDao;
69 68
70 @Autowired 69 @Autowired
71 - private RelationService relationService;  
72 -  
73 - @Autowired  
74 private EntityService entityService; 70 private EntityService entityService;
75 71
76 protected ExecutorService readResultsProcessingExecutor; 72 protected ExecutorService readResultsProcessingExecutor;
@@ -272,7 +268,7 @@ public class BaseAlarmService extends AbstractEntityService implements AlarmServ @@ -272,7 +268,7 @@ public class BaseAlarmService extends AbstractEntityService implements AlarmServ
272 boolean hasNext = true; 268 boolean hasNext = true;
273 AlarmSeverity highestSeverity = null; 269 AlarmSeverity highestSeverity = null;
274 AlarmQuery query; 270 AlarmQuery query;
275 - while (hasNext) { 271 + while (hasNext && AlarmSeverity.CRITICAL != highestSeverity) {
276 query = new AlarmQuery(entityId, nextPageLink, alarmSearchStatus, alarmStatus, false); 272 query = new AlarmQuery(entityId, nextPageLink, alarmSearchStatus, alarmStatus, false);
277 List<AlarmInfo> alarms; 273 List<AlarmInfo> alarms;
278 try { 274 try {
@@ -286,33 +282,37 @@ public class BaseAlarmService extends AbstractEntityService implements AlarmServ @@ -286,33 +282,37 @@ public class BaseAlarmService extends AbstractEntityService implements AlarmServ
286 if (hasNext) { 282 if (hasNext) {
287 nextPageLink = new TimePageData<>(alarms, nextPageLink).getNextPageLink(); 283 nextPageLink = new TimePageData<>(alarms, nextPageLink).getNextPageLink();
288 } 284 }
289 - if (alarms.isEmpty()) { 285 + AlarmSeverity severity = detectHighestSeverity(alarms);
  286 + if (severity == null) {
290 continue; 287 continue;
  288 + }
  289 + if (severity == AlarmSeverity.CRITICAL || highestSeverity == null) {
  290 + highestSeverity = severity;
291 } else { 291 } else {
292 - List<AlarmInfo> sorted = new ArrayList(alarms);  
293 - sorted.sort((p1, p2) -> p1.getSeverity().compareTo(p2.getSeverity()));  
294 - AlarmSeverity severity = sorted.get(0).getSeverity();  
295 - if (severity == AlarmSeverity.CRITICAL) {  
296 - highestSeverity = severity;  
297 - break;  
298 - } else if (highestSeverity == null) {  
299 - highestSeverity = severity;  
300 - } else {  
301 - highestSeverity = highestSeverity.compareTo(severity) < 0 ? highestSeverity : severity;  
302 - } 292 + highestSeverity = highestSeverity.compareTo(severity) < 0 ? highestSeverity : severity;
303 } 293 }
304 } 294 }
305 return highestSeverity; 295 return highestSeverity;
306 } 296 }
307 297
  298 + private AlarmSeverity detectHighestSeverity(List<AlarmInfo> alarms) {
  299 + if (!alarms.isEmpty()) {
  300 + List<AlarmInfo> sorted = new ArrayList(alarms);
  301 + sorted.sort((p1, p2) -> p1.getSeverity().compareTo(p2.getSeverity()));
  302 + return sorted.get(0).getSeverity();
  303 + } else {
  304 + return null;
  305 + }
  306 + }
  307 +
308 private void deleteRelation(EntityRelation alarmRelation) throws ExecutionException, InterruptedException { 308 private void deleteRelation(EntityRelation alarmRelation) throws ExecutionException, InterruptedException {
309 log.debug("Deleting Alarm relation: {}", alarmRelation); 309 log.debug("Deleting Alarm relation: {}", alarmRelation);
310 - relationService.deleteRelation(alarmRelation).get(); 310 + relationService.deleteRelationAsync(alarmRelation).get();
311 } 311 }
312 312
313 private void createRelation(EntityRelation alarmRelation) throws ExecutionException, InterruptedException { 313 private void createRelation(EntityRelation alarmRelation) throws ExecutionException, InterruptedException {
314 log.debug("Creating Alarm relation: {}", alarmRelation); 314 log.debug("Creating Alarm relation: {}", alarmRelation);
315 - relationService.saveRelation(alarmRelation).get(); 315 + relationService.saveRelationAsync(alarmRelation).get();
316 } 316 }
317 317
318 private Alarm merge(Alarm existing, Alarm alarm) { 318 private Alarm merge(Alarm existing, Alarm alarm) {
@@ -37,19 +37,15 @@ import org.thingsboard.server.common.data.id.TenantId; @@ -37,19 +37,15 @@ import org.thingsboard.server.common.data.id.TenantId;
37 import org.thingsboard.server.common.data.page.TextPageData; 37 import org.thingsboard.server.common.data.page.TextPageData;
38 import org.thingsboard.server.common.data.page.TextPageLink; 38 import org.thingsboard.server.common.data.page.TextPageLink;
39 import org.thingsboard.server.common.data.relation.EntityRelation; 39 import org.thingsboard.server.common.data.relation.EntityRelation;
  40 +import org.thingsboard.server.common.data.relation.EntitySearchDirection;
40 import org.thingsboard.server.dao.customer.CustomerDao; 41 import org.thingsboard.server.dao.customer.CustomerDao;
41 import org.thingsboard.server.dao.entity.AbstractEntityService; 42 import org.thingsboard.server.dao.entity.AbstractEntityService;
42 import org.thingsboard.server.dao.exception.DataValidationException; 43 import org.thingsboard.server.dao.exception.DataValidationException;
43 -import org.thingsboard.server.common.data.relation.EntitySearchDirection;  
44 import org.thingsboard.server.dao.service.DataValidator; 44 import org.thingsboard.server.dao.service.DataValidator;
45 import org.thingsboard.server.dao.service.PaginatedRemover; 45 import org.thingsboard.server.dao.service.PaginatedRemover;
46 import org.thingsboard.server.dao.tenant.TenantDao; 46 import org.thingsboard.server.dao.tenant.TenantDao;
47 47
48 -import javax.annotation.Nullable;  
49 -import java.util.ArrayList;  
50 -import java.util.Comparator;  
51 -import java.util.List;  
52 -import java.util.Optional; 48 +import java.util.*;
53 import java.util.stream.Collectors; 49 import java.util.stream.Collectors;
54 50
55 import static org.thingsboard.server.dao.DaoUtil.toUUIDs; 51 import static org.thingsboard.server.dao.DaoUtil.toUUIDs;
@@ -60,6 +56,10 @@ import static org.thingsboard.server.dao.service.Validator.*; @@ -60,6 +56,10 @@ import static org.thingsboard.server.dao.service.Validator.*;
60 @Slf4j 56 @Slf4j
61 public class BaseAssetService extends AbstractEntityService implements AssetService { 57 public class BaseAssetService extends AbstractEntityService implements AssetService {
62 58
  59 + public static final String INCORRECT_TENANT_ID = "Incorrect tenantId ";
  60 + public static final String INCORRECT_PAGE_LINK = "Incorrect page link ";
  61 + public static final String INCORRECT_CUSTOMER_ID = "Incorrect customerId ";
  62 + public static final String INCORRECT_ASSET_ID = "Incorrect assetId ";
63 @Autowired 63 @Autowired
64 private AssetDao assetDao; 64 private AssetDao assetDao;
65 65
@@ -72,21 +72,21 @@ public class BaseAssetService extends AbstractEntityService implements AssetServ @@ -72,21 +72,21 @@ public class BaseAssetService extends AbstractEntityService implements AssetServ
72 @Override 72 @Override
73 public Asset findAssetById(AssetId assetId) { 73 public Asset findAssetById(AssetId assetId) {
74 log.trace("Executing findAssetById [{}]", assetId); 74 log.trace("Executing findAssetById [{}]", assetId);
75 - validateId(assetId, "Incorrect assetId " + assetId); 75 + validateId(assetId, INCORRECT_ASSET_ID + assetId);
76 return assetDao.findById(assetId.getId()); 76 return assetDao.findById(assetId.getId());
77 } 77 }
78 78
79 @Override 79 @Override
80 public ListenableFuture<Asset> findAssetByIdAsync(AssetId assetId) { 80 public ListenableFuture<Asset> findAssetByIdAsync(AssetId assetId) {
81 log.trace("Executing findAssetById [{}]", assetId); 81 log.trace("Executing findAssetById [{}]", assetId);
82 - validateId(assetId, "Incorrect assetId " + assetId); 82 + validateId(assetId, INCORRECT_ASSET_ID + assetId);
83 return assetDao.findByIdAsync(assetId.getId()); 83 return assetDao.findByIdAsync(assetId.getId());
84 } 84 }
85 85
86 @Override 86 @Override
87 public Optional<Asset> findAssetByTenantIdAndName(TenantId tenantId, String name) { 87 public Optional<Asset> findAssetByTenantIdAndName(TenantId tenantId, String name) {
88 log.trace("Executing findAssetByTenantIdAndName [{}][{}]", tenantId, name); 88 log.trace("Executing findAssetByTenantIdAndName [{}][{}]", tenantId, name);
89 - validateId(tenantId, "Incorrect tenantId " + tenantId); 89 + validateId(tenantId, INCORRECT_TENANT_ID + tenantId);
90 return assetDao.findAssetsByTenantIdAndName(tenantId.getId(), name); 90 return assetDao.findAssetsByTenantIdAndName(tenantId.getId(), name);
91 } 91 }
92 92
@@ -114,7 +114,7 @@ public class BaseAssetService extends AbstractEntityService implements AssetServ @@ -114,7 +114,7 @@ public class BaseAssetService extends AbstractEntityService implements AssetServ
114 @Override 114 @Override
115 public void deleteAsset(AssetId assetId) { 115 public void deleteAsset(AssetId assetId) {
116 log.trace("Executing deleteAsset [{}]", assetId); 116 log.trace("Executing deleteAsset [{}]", assetId);
117 - validateId(assetId, "Incorrect assetId " + assetId); 117 + validateId(assetId, INCORRECT_ASSET_ID + assetId);
118 deleteEntityRelations(assetId); 118 deleteEntityRelations(assetId);
119 assetDao.removeById(assetId.getId()); 119 assetDao.removeById(assetId.getId());
120 } 120 }
@@ -122,8 +122,8 @@ public class BaseAssetService extends AbstractEntityService implements AssetServ @@ -122,8 +122,8 @@ public class BaseAssetService extends AbstractEntityService implements AssetServ
122 @Override 122 @Override
123 public TextPageData<Asset> findAssetsByTenantId(TenantId tenantId, TextPageLink pageLink) { 123 public TextPageData<Asset> findAssetsByTenantId(TenantId tenantId, TextPageLink pageLink) {
124 log.trace("Executing findAssetsByTenantId, tenantId [{}], pageLink [{}]", tenantId, pageLink); 124 log.trace("Executing findAssetsByTenantId, tenantId [{}], pageLink [{}]", tenantId, pageLink);
125 - validateId(tenantId, "Incorrect tenantId " + tenantId);  
126 - validatePageLink(pageLink, "Incorrect page link " + pageLink); 125 + validateId(tenantId, INCORRECT_TENANT_ID + tenantId);
  126 + validatePageLink(pageLink, INCORRECT_PAGE_LINK + pageLink);
127 List<Asset> assets = assetDao.findAssetsByTenantId(tenantId.getId(), pageLink); 127 List<Asset> assets = assetDao.findAssetsByTenantId(tenantId.getId(), pageLink);
128 return new TextPageData<>(assets, pageLink); 128 return new TextPageData<>(assets, pageLink);
129 } 129 }
@@ -131,9 +131,9 @@ public class BaseAssetService extends AbstractEntityService implements AssetServ @@ -131,9 +131,9 @@ public class BaseAssetService extends AbstractEntityService implements AssetServ
131 @Override 131 @Override
132 public TextPageData<Asset> findAssetsByTenantIdAndType(TenantId tenantId, String type, TextPageLink pageLink) { 132 public TextPageData<Asset> findAssetsByTenantIdAndType(TenantId tenantId, String type, TextPageLink pageLink) {
133 log.trace("Executing findAssetsByTenantIdAndType, tenantId [{}], type [{}], pageLink [{}]", tenantId, type, pageLink); 133 log.trace("Executing findAssetsByTenantIdAndType, tenantId [{}], type [{}], pageLink [{}]", tenantId, type, pageLink);
134 - validateId(tenantId, "Incorrect tenantId " + tenantId); 134 + validateId(tenantId, INCORRECT_TENANT_ID + tenantId);
135 validateString(type, "Incorrect type " + type); 135 validateString(type, "Incorrect type " + type);
136 - validatePageLink(pageLink, "Incorrect page link " + pageLink); 136 + validatePageLink(pageLink, INCORRECT_PAGE_LINK + pageLink);
137 List<Asset> assets = assetDao.findAssetsByTenantIdAndType(tenantId.getId(), type, pageLink); 137 List<Asset> assets = assetDao.findAssetsByTenantIdAndType(tenantId.getId(), type, pageLink);
138 return new TextPageData<>(assets, pageLink); 138 return new TextPageData<>(assets, pageLink);
139 } 139 }
@@ -141,7 +141,7 @@ public class BaseAssetService extends AbstractEntityService implements AssetServ @@ -141,7 +141,7 @@ public class BaseAssetService extends AbstractEntityService implements AssetServ
141 @Override 141 @Override
142 public ListenableFuture<List<Asset>> findAssetsByTenantIdAndIdsAsync(TenantId tenantId, List<AssetId> assetIds) { 142 public ListenableFuture<List<Asset>> findAssetsByTenantIdAndIdsAsync(TenantId tenantId, List<AssetId> assetIds) {
143 log.trace("Executing findAssetsByTenantIdAndIdsAsync, tenantId [{}], assetIds [{}]", tenantId, assetIds); 143 log.trace("Executing findAssetsByTenantIdAndIdsAsync, tenantId [{}], assetIds [{}]", tenantId, assetIds);
144 - validateId(tenantId, "Incorrect tenantId " + tenantId); 144 + validateId(tenantId, INCORRECT_TENANT_ID + tenantId);
145 validateIds(assetIds, "Incorrect assetIds " + assetIds); 145 validateIds(assetIds, "Incorrect assetIds " + assetIds);
146 return assetDao.findAssetsByTenantIdAndIdsAsync(tenantId.getId(), toUUIDs(assetIds)); 146 return assetDao.findAssetsByTenantIdAndIdsAsync(tenantId.getId(), toUUIDs(assetIds));
147 } 147 }
@@ -149,27 +149,27 @@ public class BaseAssetService extends AbstractEntityService implements AssetServ @@ -149,27 +149,27 @@ public class BaseAssetService extends AbstractEntityService implements AssetServ
149 @Override 149 @Override
150 public void deleteAssetsByTenantId(TenantId tenantId) { 150 public void deleteAssetsByTenantId(TenantId tenantId) {
151 log.trace("Executing deleteAssetsByTenantId, tenantId [{}]", tenantId); 151 log.trace("Executing deleteAssetsByTenantId, tenantId [{}]", tenantId);
152 - validateId(tenantId, "Incorrect tenantId " + tenantId); 152 + validateId(tenantId, INCORRECT_TENANT_ID + tenantId);
153 tenantAssetsRemover.removeEntities(tenantId); 153 tenantAssetsRemover.removeEntities(tenantId);
154 } 154 }
155 155
156 @Override 156 @Override
157 public TextPageData<Asset> findAssetsByTenantIdAndCustomerId(TenantId tenantId, CustomerId customerId, TextPageLink pageLink) { 157 public TextPageData<Asset> findAssetsByTenantIdAndCustomerId(TenantId tenantId, CustomerId customerId, TextPageLink pageLink) {
158 log.trace("Executing findAssetsByTenantIdAndCustomerId, tenantId [{}], customerId [{}], pageLink [{}]", tenantId, customerId, pageLink); 158 log.trace("Executing findAssetsByTenantIdAndCustomerId, tenantId [{}], customerId [{}], pageLink [{}]", tenantId, customerId, pageLink);
159 - validateId(tenantId, "Incorrect tenantId " + tenantId);  
160 - validateId(customerId, "Incorrect customerId " + customerId);  
161 - validatePageLink(pageLink, "Incorrect page link " + pageLink); 159 + validateId(tenantId, INCORRECT_TENANT_ID + tenantId);
  160 + validateId(customerId, INCORRECT_CUSTOMER_ID + customerId);
  161 + validatePageLink(pageLink, INCORRECT_PAGE_LINK + pageLink);
162 List<Asset> assets = assetDao.findAssetsByTenantIdAndCustomerId(tenantId.getId(), customerId.getId(), pageLink); 162 List<Asset> assets = assetDao.findAssetsByTenantIdAndCustomerId(tenantId.getId(), customerId.getId(), pageLink);
163 - return new TextPageData<Asset>(assets, pageLink); 163 + return new TextPageData<>(assets, pageLink);
164 } 164 }
165 165
166 @Override 166 @Override
167 public TextPageData<Asset> findAssetsByTenantIdAndCustomerIdAndType(TenantId tenantId, CustomerId customerId, String type, TextPageLink pageLink) { 167 public TextPageData<Asset> findAssetsByTenantIdAndCustomerIdAndType(TenantId tenantId, CustomerId customerId, String type, TextPageLink pageLink) {
168 log.trace("Executing findAssetsByTenantIdAndCustomerIdAndType, tenantId [{}], customerId [{}], type [{}], pageLink [{}]", tenantId, customerId, type, pageLink); 168 log.trace("Executing findAssetsByTenantIdAndCustomerIdAndType, tenantId [{}], customerId [{}], type [{}], pageLink [{}]", tenantId, customerId, type, pageLink);
169 - validateId(tenantId, "Incorrect tenantId " + tenantId);  
170 - validateId(customerId, "Incorrect customerId " + customerId); 169 + validateId(tenantId, INCORRECT_TENANT_ID + tenantId);
  170 + validateId(customerId, INCORRECT_CUSTOMER_ID + customerId);
171 validateString(type, "Incorrect type " + type); 171 validateString(type, "Incorrect type " + type);
172 - validatePageLink(pageLink, "Incorrect page link " + pageLink); 172 + validatePageLink(pageLink, INCORRECT_PAGE_LINK + pageLink);
173 List<Asset> assets = assetDao.findAssetsByTenantIdAndCustomerIdAndType(tenantId.getId(), customerId.getId(), type, pageLink); 173 List<Asset> assets = assetDao.findAssetsByTenantIdAndCustomerIdAndType(tenantId.getId(), customerId.getId(), type, pageLink);
174 return new TextPageData<>(assets, pageLink); 174 return new TextPageData<>(assets, pageLink);
175 } 175 }
@@ -177,8 +177,8 @@ public class BaseAssetService extends AbstractEntityService implements AssetServ @@ -177,8 +177,8 @@ public class BaseAssetService extends AbstractEntityService implements AssetServ
177 @Override 177 @Override
178 public ListenableFuture<List<Asset>> findAssetsByTenantIdCustomerIdAndIdsAsync(TenantId tenantId, CustomerId customerId, List<AssetId> assetIds) { 178 public ListenableFuture<List<Asset>> findAssetsByTenantIdCustomerIdAndIdsAsync(TenantId tenantId, CustomerId customerId, List<AssetId> assetIds) {
179 log.trace("Executing findAssetsByTenantIdAndCustomerIdAndIdsAsync, tenantId [{}], customerId [{}], assetIds [{}]", tenantId, customerId, assetIds); 179 log.trace("Executing findAssetsByTenantIdAndCustomerIdAndIdsAsync, tenantId [{}], customerId [{}], assetIds [{}]", tenantId, customerId, assetIds);
180 - validateId(tenantId, "Incorrect tenantId " + tenantId);  
181 - validateId(customerId, "Incorrect customerId " + customerId); 180 + validateId(tenantId, INCORRECT_TENANT_ID + tenantId);
  181 + validateId(customerId, INCORRECT_CUSTOMER_ID + customerId);
182 validateIds(assetIds, "Incorrect assetIds " + assetIds); 182 validateIds(assetIds, "Incorrect assetIds " + assetIds);
183 return assetDao.findAssetsByTenantIdAndCustomerIdAndIdsAsync(tenantId.getId(), customerId.getId(), toUUIDs(assetIds)); 183 return assetDao.findAssetsByTenantIdAndCustomerIdAndIdsAsync(tenantId.getId(), customerId.getId(), toUUIDs(assetIds));
184 } 184 }
@@ -186,8 +186,8 @@ public class BaseAssetService extends AbstractEntityService implements AssetServ @@ -186,8 +186,8 @@ public class BaseAssetService extends AbstractEntityService implements AssetServ
186 @Override 186 @Override
187 public void unassignCustomerAssets(TenantId tenantId, CustomerId customerId) { 187 public void unassignCustomerAssets(TenantId tenantId, CustomerId customerId) {
188 log.trace("Executing unassignCustomerAssets, tenantId [{}], customerId [{}]", tenantId, customerId); 188 log.trace("Executing unassignCustomerAssets, tenantId [{}], customerId [{}]", tenantId, customerId);
189 - validateId(tenantId, "Incorrect tenantId " + tenantId);  
190 - validateId(customerId, "Incorrect customerId " + customerId); 189 + validateId(tenantId, INCORRECT_TENANT_ID + tenantId);
  190 + validateId(customerId, INCORRECT_CUSTOMER_ID + customerId);
191 new CustomerAssetsUnassigner(tenantId).removeEntities(customerId); 191 new CustomerAssetsUnassigner(tenantId).removeEntities(customerId);
192 } 192 }
193 193
@@ -205,22 +205,16 @@ public class BaseAssetService extends AbstractEntityService implements AssetServ @@ -205,22 +205,16 @@ public class BaseAssetService extends AbstractEntityService implements AssetServ
205 } 205 }
206 return Futures.successfulAsList(futures); 206 return Futures.successfulAsList(futures);
207 }); 207 });
208 -  
209 - assets = Futures.transform(assets, new Function<List<Asset>, List<Asset>>() {  
210 - @Nullable  
211 - @Override  
212 - public List<Asset> apply(@Nullable List<Asset> assetList) {  
213 - return assetList.stream().filter(asset -> query.getAssetTypes().contains(asset.getType())).collect(Collectors.toList());  
214 - }  
215 - });  
216 - 208 + assets = Futures.transform(assets, (Function<List<Asset>, List<Asset>>)assetList ->
  209 + assetList == null ? Collections.emptyList() : assetList.stream().filter(asset -> query.getAssetTypes().contains(asset.getType())).collect(Collectors.toList())
  210 + );
217 return assets; 211 return assets;
218 } 212 }
219 213
220 @Override 214 @Override
221 public ListenableFuture<List<EntitySubtype>> findAssetTypesByTenantId(TenantId tenantId) { 215 public ListenableFuture<List<EntitySubtype>> findAssetTypesByTenantId(TenantId tenantId) {
222 log.trace("Executing findAssetTypesByTenantId, tenantId [{}]", tenantId); 216 log.trace("Executing findAssetTypesByTenantId, tenantId [{}]", tenantId);
223 - validateId(tenantId, "Incorrect tenantId " + tenantId); 217 + validateId(tenantId, INCORRECT_TENANT_ID + tenantId);
224 ListenableFuture<List<EntitySubtype>> tenantAssetTypes = assetDao.findTenantAssetTypesAsync(tenantId.getId()); 218 ListenableFuture<List<EntitySubtype>> tenantAssetTypes = assetDao.findTenantAssetTypesAsync(tenantId.getId());
225 return Futures.transform(tenantAssetTypes, 219 return Futures.transform(tenantAssetTypes,
226 (Function<List<EntitySubtype>, List<EntitySubtype>>) assetTypes -> { 220 (Function<List<EntitySubtype>, List<EntitySubtype>>) assetTypes -> {
@@ -109,18 +109,21 @@ public class CassandraBaseAttributesDao extends CassandraAbstractAsyncDao implem @@ -109,18 +109,21 @@ public class CassandraBaseAttributesDao extends CassandraAbstractAsyncDao implem
109 stmt.setString(3, attribute.getKey()); 109 stmt.setString(3, attribute.getKey());
110 stmt.setLong(4, attribute.getLastUpdateTs()); 110 stmt.setLong(4, attribute.getLastUpdateTs());
111 stmt.setString(5, attribute.getStrValue().orElse(null)); 111 stmt.setString(5, attribute.getStrValue().orElse(null));
112 - if (attribute.getBooleanValue().isPresent()) {  
113 - stmt.setBool(6, attribute.getBooleanValue().get()); 112 + Optional<Boolean> booleanValue = attribute.getBooleanValue();
  113 + if (booleanValue.isPresent()) {
  114 + stmt.setBool(6, booleanValue.get());
114 } else { 115 } else {
115 stmt.setToNull(6); 116 stmt.setToNull(6);
116 } 117 }
117 - if (attribute.getLongValue().isPresent()) {  
118 - stmt.setLong(7, attribute.getLongValue().get()); 118 + Optional<Long> longValue = attribute.getLongValue();
  119 + if (longValue.isPresent()) {
  120 + stmt.setLong(7, longValue.get());
119 } else { 121 } else {
120 stmt.setToNull(7); 122 stmt.setToNull(7);
121 } 123 }
122 - if (attribute.getDoubleValue().isPresent()) {  
123 - stmt.setDouble(8, attribute.getDoubleValue().get()); 124 + Optional<Double> doubleValue = attribute.getDoubleValue();
  125 + if (doubleValue.isPresent()) {
  126 + stmt.setDouble(8, doubleValue.get());
124 } else { 127 } else {
125 stmt.setToNull(8); 128 stmt.setToNull(8);
126 } 129 }
@@ -153,6 +153,7 @@ public abstract class AbstractCassandraCluster { @@ -153,6 +153,7 @@ public abstract class AbstractCassandraCluster {
153 Thread.sleep(initRetryInterval); 153 Thread.sleep(initRetryInterval);
154 } catch (InterruptedException ie) { 154 } catch (InterruptedException ie) {
155 log.warn("Failed to wait until retry", ie); 155 log.warn("Failed to wait until retry", ie);
  156 + Thread.currentThread().interrupt();
156 } 157 }
157 } 158 }
158 } 159 }
@@ -49,6 +49,8 @@ import static com.datastax.driver.core.querybuilder.QueryBuilder.select; @@ -49,6 +49,8 @@ import static com.datastax.driver.core.querybuilder.QueryBuilder.select;
49 @NoSqlDao 49 @NoSqlDao
50 public class CassandraBaseComponentDescriptorDao extends CassandraAbstractSearchTextDao<ComponentDescriptorEntity, ComponentDescriptor> implements ComponentDescriptorDao { 50 public class CassandraBaseComponentDescriptorDao extends CassandraAbstractSearchTextDao<ComponentDescriptorEntity, ComponentDescriptor> implements ComponentDescriptorDao {
51 51
  52 + public static final String SEARCH_RESULT = "Search result: [{}]";
  53 +
52 @Override 54 @Override
53 protected Class<ComponentDescriptorEntity> getColumnFamilyClass() { 55 protected Class<ComponentDescriptorEntity> getColumnFamilyClass() {
54 return ComponentDescriptorEntity.class; 56 return ComponentDescriptorEntity.class;
@@ -79,7 +81,7 @@ public class CassandraBaseComponentDescriptorDao extends CassandraAbstractSearch @@ -79,7 +81,7 @@ public class CassandraBaseComponentDescriptorDao extends CassandraAbstractSearch
79 if (log.isTraceEnabled()) { 81 if (log.isTraceEnabled()) {
80 log.trace("Search result: [{}] for component entity [{}]", componentDescriptor != null, componentDescriptor); 82 log.trace("Search result: [{}] for component entity [{}]", componentDescriptor != null, componentDescriptor);
81 } else { 83 } else {
82 - log.debug("Search result: [{}]", componentDescriptor != null); 84 + log.debug(SEARCH_RESULT, componentDescriptor != null);
83 } 85 }
84 return componentDescriptor; 86 return componentDescriptor;
85 } 87 }
@@ -93,7 +95,7 @@ public class CassandraBaseComponentDescriptorDao extends CassandraAbstractSearch @@ -93,7 +95,7 @@ public class CassandraBaseComponentDescriptorDao extends CassandraAbstractSearch
93 if (log.isTraceEnabled()) { 95 if (log.isTraceEnabled()) {
94 log.trace("Search result: [{}] for component entity [{}]", entity != null, entity); 96 log.trace("Search result: [{}] for component entity [{}]", entity != null, entity);
95 } else { 97 } else {
96 - log.debug("Search result: [{}]", entity != null); 98 + log.debug(SEARCH_RESULT, entity != null);
97 } 99 }
98 return DaoUtil.getData(entity); 100 return DaoUtil.getData(entity);
99 } 101 }
@@ -104,9 +106,9 @@ public class CassandraBaseComponentDescriptorDao extends CassandraAbstractSearch @@ -104,9 +106,9 @@ public class CassandraBaseComponentDescriptorDao extends CassandraAbstractSearch
104 List<ComponentDescriptorEntity> entities = findPageWithTextSearch(ModelConstants.COMPONENT_DESCRIPTOR_BY_TYPE_AND_SEARCH_TEXT_COLUMN_FAMILY_NAME, 106 List<ComponentDescriptorEntity> entities = findPageWithTextSearch(ModelConstants.COMPONENT_DESCRIPTOR_BY_TYPE_AND_SEARCH_TEXT_COLUMN_FAMILY_NAME,
105 Arrays.asList(eq(ModelConstants.COMPONENT_DESCRIPTOR_TYPE_PROPERTY, type)), pageLink); 107 Arrays.asList(eq(ModelConstants.COMPONENT_DESCRIPTOR_TYPE_PROPERTY, type)), pageLink);
106 if (log.isTraceEnabled()) { 108 if (log.isTraceEnabled()) {
107 - log.trace("Search result: [{}]", Arrays.toString(entities.toArray())); 109 + log.trace(SEARCH_RESULT, Arrays.toString(entities.toArray()));
108 } else { 110 } else {
109 - log.debug("Search result: [{}]", entities.size()); 111 + log.debug(SEARCH_RESULT, entities.size());
110 } 112 }
111 return DaoUtil.convertDataList(entities); 113 return DaoUtil.convertDataList(entities);
112 } 114 }
@@ -118,9 +120,9 @@ public class CassandraBaseComponentDescriptorDao extends CassandraAbstractSearch @@ -118,9 +120,9 @@ public class CassandraBaseComponentDescriptorDao extends CassandraAbstractSearch
118 Arrays.asList(eq(ModelConstants.COMPONENT_DESCRIPTOR_TYPE_PROPERTY, type), 120 Arrays.asList(eq(ModelConstants.COMPONENT_DESCRIPTOR_TYPE_PROPERTY, type),
119 eq(ModelConstants.COMPONENT_DESCRIPTOR_SCOPE_PROPERTY, scope.name())), pageLink); 121 eq(ModelConstants.COMPONENT_DESCRIPTOR_SCOPE_PROPERTY, scope.name())), pageLink);
120 if (log.isTraceEnabled()) { 122 if (log.isTraceEnabled()) {
121 - log.trace("Search result: [{}]", Arrays.toString(entities.toArray())); 123 + log.trace(SEARCH_RESULT, Arrays.toString(entities.toArray()));
122 } else { 124 } else {
123 - log.debug("Search result: [{}]", entities.size()); 125 + log.debug(SEARCH_RESULT, entities.size());
124 } 126 }
125 return DaoUtil.convertDataList(entities); 127 return DaoUtil.convertDataList(entities);
126 } 128 }
@@ -51,6 +51,7 @@ import static org.thingsboard.server.dao.service.Validator.validateId; @@ -51,6 +51,7 @@ import static org.thingsboard.server.dao.service.Validator.validateId;
51 public class CustomerServiceImpl extends AbstractEntityService implements CustomerService { 51 public class CustomerServiceImpl extends AbstractEntityService implements CustomerService {
52 52
53 private static final String PUBLIC_CUSTOMER_TITLE = "Public"; 53 private static final String PUBLIC_CUSTOMER_TITLE = "Public";
  54 + public static final String INCORRECT_CUSTOMER_ID = "Incorrect customerId ";
54 55
55 @Autowired 56 @Autowired
56 private CustomerDao customerDao; 57 private CustomerDao customerDao;
@@ -73,14 +74,14 @@ public class CustomerServiceImpl extends AbstractEntityService implements Custom @@ -73,14 +74,14 @@ public class CustomerServiceImpl extends AbstractEntityService implements Custom
73 @Override 74 @Override
74 public Customer findCustomerById(CustomerId customerId) { 75 public Customer findCustomerById(CustomerId customerId) {
75 log.trace("Executing findCustomerById [{}]", customerId); 76 log.trace("Executing findCustomerById [{}]", customerId);
76 - Validator.validateId(customerId, "Incorrect customerId " + customerId); 77 + Validator.validateId(customerId, INCORRECT_CUSTOMER_ID + customerId);
77 return customerDao.findById(customerId.getId()); 78 return customerDao.findById(customerId.getId());
78 } 79 }
79 80
80 @Override 81 @Override
81 public ListenableFuture<Customer> findCustomerByIdAsync(CustomerId customerId) { 82 public ListenableFuture<Customer> findCustomerByIdAsync(CustomerId customerId) {
82 log.trace("Executing findCustomerByIdAsync [{}]", customerId); 83 log.trace("Executing findCustomerByIdAsync [{}]", customerId);
83 - validateId(customerId, "Incorrect customerId " + customerId); 84 + validateId(customerId, INCORRECT_CUSTOMER_ID + customerId);
84 return customerDao.findByIdAsync(customerId.getId()); 85 return customerDao.findByIdAsync(customerId.getId());
85 } 86 }
86 87
@@ -94,7 +95,7 @@ public class CustomerServiceImpl extends AbstractEntityService implements Custom @@ -94,7 +95,7 @@ public class CustomerServiceImpl extends AbstractEntityService implements Custom
94 @Override 95 @Override
95 public void deleteCustomer(CustomerId customerId) { 96 public void deleteCustomer(CustomerId customerId) {
96 log.trace("Executing deleteCustomer [{}]", customerId); 97 log.trace("Executing deleteCustomer [{}]", customerId);
97 - Validator.validateId(customerId, "Incorrect customerId " + customerId); 98 + Validator.validateId(customerId, INCORRECT_CUSTOMER_ID + customerId);
98 Customer customer = findCustomerById(customerId); 99 Customer customer = findCustomerById(customerId);
99 if (customer == null) { 100 if (customer == null) {
100 throw new IncorrectParameterException("Unable to delete non-existent customer."); 101 throw new IncorrectParameterException("Unable to delete non-existent customer.");
@@ -110,7 +111,7 @@ public class CustomerServiceImpl extends AbstractEntityService implements Custom @@ -110,7 +111,7 @@ public class CustomerServiceImpl extends AbstractEntityService implements Custom
110 @Override 111 @Override
111 public Customer findOrCreatePublicCustomer(TenantId tenantId) { 112 public Customer findOrCreatePublicCustomer(TenantId tenantId) {
112 log.trace("Executing findOrCreatePublicCustomer, tenantId [{}]", tenantId); 113 log.trace("Executing findOrCreatePublicCustomer, tenantId [{}]", tenantId);
113 - Validator.validateId(tenantId, "Incorrect customerId " + tenantId); 114 + Validator.validateId(tenantId, INCORRECT_CUSTOMER_ID + tenantId);
114 Optional<Customer> publicCustomerOpt = customerDao.findCustomersByTenantIdAndTitle(tenantId.getId(), PUBLIC_CUSTOMER_TITLE); 115 Optional<Customer> publicCustomerOpt = customerDao.findCustomersByTenantIdAndTitle(tenantId.getId(), PUBLIC_CUSTOMER_TITLE);
115 if (publicCustomerOpt.isPresent()) { 116 if (publicCustomerOpt.isPresent()) {
116 return publicCustomerOpt.get(); 117 return publicCustomerOpt.get();
@@ -46,6 +46,8 @@ import static org.thingsboard.server.dao.service.Validator.validateId; @@ -46,6 +46,8 @@ import static org.thingsboard.server.dao.service.Validator.validateId;
46 @Slf4j 46 @Slf4j
47 public class DashboardServiceImpl extends AbstractEntityService implements DashboardService { 47 public class DashboardServiceImpl extends AbstractEntityService implements DashboardService {
48 48
  49 + public static final String INCORRECT_DASHBOARD_ID = "Incorrect dashboardId ";
  50 + public static final String INCORRECT_TENANT_ID = "Incorrect tenantId ";
49 @Autowired 51 @Autowired
50 private DashboardDao dashboardDao; 52 private DashboardDao dashboardDao;
51 53
@@ -61,28 +63,28 @@ public class DashboardServiceImpl extends AbstractEntityService implements Dashb @@ -61,28 +63,28 @@ public class DashboardServiceImpl extends AbstractEntityService implements Dashb
61 @Override 63 @Override
62 public Dashboard findDashboardById(DashboardId dashboardId) { 64 public Dashboard findDashboardById(DashboardId dashboardId) {
63 log.trace("Executing findDashboardById [{}]", dashboardId); 65 log.trace("Executing findDashboardById [{}]", dashboardId);
64 - Validator.validateId(dashboardId, "Incorrect dashboardId " + dashboardId); 66 + Validator.validateId(dashboardId, INCORRECT_DASHBOARD_ID + dashboardId);
65 return dashboardDao.findById(dashboardId.getId()); 67 return dashboardDao.findById(dashboardId.getId());
66 } 68 }
67 69
68 @Override 70 @Override
69 public ListenableFuture<Dashboard> findDashboardByIdAsync(DashboardId dashboardId) { 71 public ListenableFuture<Dashboard> findDashboardByIdAsync(DashboardId dashboardId) {
70 log.trace("Executing findDashboardByIdAsync [{}]", dashboardId); 72 log.trace("Executing findDashboardByIdAsync [{}]", dashboardId);
71 - validateId(dashboardId, "Incorrect dashboardId " + dashboardId); 73 + validateId(dashboardId, INCORRECT_DASHBOARD_ID + dashboardId);
72 return dashboardDao.findByIdAsync(dashboardId.getId()); 74 return dashboardDao.findByIdAsync(dashboardId.getId());
73 } 75 }
74 76
75 @Override 77 @Override
76 public DashboardInfo findDashboardInfoById(DashboardId dashboardId) { 78 public DashboardInfo findDashboardInfoById(DashboardId dashboardId) {
77 log.trace("Executing findDashboardInfoById [{}]", dashboardId); 79 log.trace("Executing findDashboardInfoById [{}]", dashboardId);
78 - Validator.validateId(dashboardId, "Incorrect dashboardId " + dashboardId); 80 + Validator.validateId(dashboardId, INCORRECT_DASHBOARD_ID + dashboardId);
79 return dashboardInfoDao.findById(dashboardId.getId()); 81 return dashboardInfoDao.findById(dashboardId.getId());
80 } 82 }
81 83
82 @Override 84 @Override
83 public ListenableFuture<DashboardInfo> findDashboardInfoByIdAsync(DashboardId dashboardId) { 85 public ListenableFuture<DashboardInfo> findDashboardInfoByIdAsync(DashboardId dashboardId) {
84 log.trace("Executing findDashboardInfoByIdAsync [{}]", dashboardId); 86 log.trace("Executing findDashboardInfoByIdAsync [{}]", dashboardId);
85 - validateId(dashboardId, "Incorrect dashboardId " + dashboardId); 87 + validateId(dashboardId, INCORRECT_DASHBOARD_ID + dashboardId);
86 return dashboardInfoDao.findByIdAsync(dashboardId.getId()); 88 return dashboardInfoDao.findByIdAsync(dashboardId.getId());
87 } 89 }
88 90
@@ -110,7 +112,7 @@ public class DashboardServiceImpl extends AbstractEntityService implements Dashb @@ -110,7 +112,7 @@ public class DashboardServiceImpl extends AbstractEntityService implements Dashb
110 @Override 112 @Override
111 public void deleteDashboard(DashboardId dashboardId) { 113 public void deleteDashboard(DashboardId dashboardId) {
112 log.trace("Executing deleteDashboard [{}]", dashboardId); 114 log.trace("Executing deleteDashboard [{}]", dashboardId);
113 - Validator.validateId(dashboardId, "Incorrect dashboardId " + dashboardId); 115 + Validator.validateId(dashboardId, INCORRECT_DASHBOARD_ID + dashboardId);
114 deleteEntityRelations(dashboardId); 116 deleteEntityRelations(dashboardId);
115 dashboardDao.removeById(dashboardId.getId()); 117 dashboardDao.removeById(dashboardId.getId());
116 } 118 }
@@ -118,7 +120,7 @@ public class DashboardServiceImpl extends AbstractEntityService implements Dashb @@ -118,7 +120,7 @@ public class DashboardServiceImpl extends AbstractEntityService implements Dashb
118 @Override 120 @Override
119 public TextPageData<DashboardInfo> findDashboardsByTenantId(TenantId tenantId, TextPageLink pageLink) { 121 public TextPageData<DashboardInfo> findDashboardsByTenantId(TenantId tenantId, TextPageLink pageLink) {
120 log.trace("Executing findDashboardsByTenantId, tenantId [{}], pageLink [{}]", tenantId, pageLink); 122 log.trace("Executing findDashboardsByTenantId, tenantId [{}], pageLink [{}]", tenantId, pageLink);
121 - Validator.validateId(tenantId, "Incorrect tenantId " + tenantId); 123 + Validator.validateId(tenantId, INCORRECT_TENANT_ID + tenantId);
122 Validator.validatePageLink(pageLink, "Incorrect page link " + pageLink); 124 Validator.validatePageLink(pageLink, "Incorrect page link " + pageLink);
123 List<DashboardInfo> dashboards = dashboardInfoDao.findDashboardsByTenantId(tenantId.getId(), pageLink); 125 List<DashboardInfo> dashboards = dashboardInfoDao.findDashboardsByTenantId(tenantId.getId(), pageLink);
124 return new TextPageData<>(dashboards, pageLink); 126 return new TextPageData<>(dashboards, pageLink);
@@ -127,14 +129,14 @@ public class DashboardServiceImpl extends AbstractEntityService implements Dashb @@ -127,14 +129,14 @@ public class DashboardServiceImpl extends AbstractEntityService implements Dashb
127 @Override 129 @Override
128 public void deleteDashboardsByTenantId(TenantId tenantId) { 130 public void deleteDashboardsByTenantId(TenantId tenantId) {
129 log.trace("Executing deleteDashboardsByTenantId, tenantId [{}]", tenantId); 131 log.trace("Executing deleteDashboardsByTenantId, tenantId [{}]", tenantId);
130 - Validator.validateId(tenantId, "Incorrect tenantId " + tenantId); 132 + Validator.validateId(tenantId, INCORRECT_TENANT_ID + tenantId);
131 tenantDashboardsRemover.removeEntities(tenantId); 133 tenantDashboardsRemover.removeEntities(tenantId);
132 } 134 }
133 135
134 @Override 136 @Override
135 public TextPageData<DashboardInfo> findDashboardsByTenantIdAndCustomerId(TenantId tenantId, CustomerId customerId, TextPageLink pageLink) { 137 public TextPageData<DashboardInfo> findDashboardsByTenantIdAndCustomerId(TenantId tenantId, CustomerId customerId, TextPageLink pageLink) {
136 log.trace("Executing findDashboardsByTenantIdAndCustomerId, tenantId [{}], customerId [{}], pageLink [{}]", tenantId, customerId, pageLink); 138 log.trace("Executing findDashboardsByTenantIdAndCustomerId, tenantId [{}], customerId [{}], pageLink [{}]", tenantId, customerId, pageLink);
137 - Validator.validateId(tenantId, "Incorrect tenantId " + tenantId); 139 + Validator.validateId(tenantId, INCORRECT_TENANT_ID + tenantId);
138 Validator.validateId(customerId, "Incorrect customerId " + customerId); 140 Validator.validateId(customerId, "Incorrect customerId " + customerId);
139 Validator.validatePageLink(pageLink, "Incorrect page link " + pageLink); 141 Validator.validatePageLink(pageLink, "Incorrect page link " + pageLink);
140 List<DashboardInfo> dashboards = dashboardInfoDao.findDashboardsByTenantIdAndCustomerId(tenantId.getId(), customerId.getId(), pageLink); 142 List<DashboardInfo> dashboards = dashboardInfoDao.findDashboardsByTenantIdAndCustomerId(tenantId.getId(), customerId.getId(), pageLink);
@@ -144,7 +146,7 @@ public class DashboardServiceImpl extends AbstractEntityService implements Dashb @@ -144,7 +146,7 @@ public class DashboardServiceImpl extends AbstractEntityService implements Dashb
144 @Override 146 @Override
145 public void unassignCustomerDashboards(TenantId tenantId, CustomerId customerId) { 147 public void unassignCustomerDashboards(TenantId tenantId, CustomerId customerId) {
146 log.trace("Executing unassignCustomerDashboards, tenantId [{}], customerId [{}]", tenantId, customerId); 148 log.trace("Executing unassignCustomerDashboards, tenantId [{}], customerId [{}]", tenantId, customerId);
147 - Validator.validateId(tenantId, "Incorrect tenantId " + tenantId); 149 + Validator.validateId(tenantId, INCORRECT_TENANT_ID + tenantId);
148 Validator.validateId(customerId, "Incorrect customerId " + customerId); 150 Validator.validateId(customerId, "Incorrect customerId " + customerId);
149 new CustomerDashboardsUnassigner(tenantId).removeEntities(customerId); 151 new CustomerDashboardsUnassigner(tenantId).removeEntities(customerId);
150 } 152 }
@@ -44,10 +44,7 @@ import org.thingsboard.server.dao.service.PaginatedRemover; @@ -44,10 +44,7 @@ import org.thingsboard.server.dao.service.PaginatedRemover;
44 import org.thingsboard.server.dao.tenant.TenantDao; 44 import org.thingsboard.server.dao.tenant.TenantDao;
45 45
46 import javax.annotation.Nullable; 46 import javax.annotation.Nullable;
47 -import java.util.ArrayList;  
48 -import java.util.Comparator;  
49 -import java.util.List;  
50 -import java.util.Optional; 47 +import java.util.*;
51 import java.util.stream.Collectors; 48 import java.util.stream.Collectors;
52 49
53 import static org.thingsboard.server.dao.DaoUtil.toUUIDs; 50 import static org.thingsboard.server.dao.DaoUtil.toUUIDs;
@@ -58,6 +55,10 @@ import static org.thingsboard.server.dao.service.Validator.*; @@ -58,6 +55,10 @@ import static org.thingsboard.server.dao.service.Validator.*;
58 @Slf4j 55 @Slf4j
59 public class DeviceServiceImpl extends AbstractEntityService implements DeviceService { 56 public class DeviceServiceImpl extends AbstractEntityService implements DeviceService {
60 57
  58 + public static final String INCORRECT_TENANT_ID = "Incorrect tenantId ";
  59 + public static final String INCORRECT_PAGE_LINK = "Incorrect page link ";
  60 + public static final String INCORRECT_CUSTOMER_ID = "Incorrect customerId ";
  61 + public static final String INCORRECT_DEVICE_ID = "Incorrect deviceId ";
61 @Autowired 62 @Autowired
62 private DeviceDao deviceDao; 63 private DeviceDao deviceDao;
63 64
@@ -73,21 +74,21 @@ public class DeviceServiceImpl extends AbstractEntityService implements DeviceSe @@ -73,21 +74,21 @@ public class DeviceServiceImpl extends AbstractEntityService implements DeviceSe
73 @Override 74 @Override
74 public Device findDeviceById(DeviceId deviceId) { 75 public Device findDeviceById(DeviceId deviceId) {
75 log.trace("Executing findDeviceById [{}]", deviceId); 76 log.trace("Executing findDeviceById [{}]", deviceId);
76 - validateId(deviceId, "Incorrect deviceId " + deviceId); 77 + validateId(deviceId, INCORRECT_DEVICE_ID + deviceId);
77 return deviceDao.findById(deviceId.getId()); 78 return deviceDao.findById(deviceId.getId());
78 } 79 }
79 80
80 @Override 81 @Override
81 public ListenableFuture<Device> findDeviceByIdAsync(DeviceId deviceId) { 82 public ListenableFuture<Device> findDeviceByIdAsync(DeviceId deviceId) {
82 log.trace("Executing findDeviceById [{}]", deviceId); 83 log.trace("Executing findDeviceById [{}]", deviceId);
83 - validateId(deviceId, "Incorrect deviceId " + deviceId); 84 + validateId(deviceId, INCORRECT_DEVICE_ID + deviceId);
84 return deviceDao.findByIdAsync(deviceId.getId()); 85 return deviceDao.findByIdAsync(deviceId.getId());
85 } 86 }
86 87
87 @Override 88 @Override
88 public Optional<Device> findDeviceByTenantIdAndName(TenantId tenantId, String name) { 89 public Optional<Device> findDeviceByTenantIdAndName(TenantId tenantId, String name) {
89 log.trace("Executing findDeviceByTenantIdAndName [{}][{}]", tenantId, name); 90 log.trace("Executing findDeviceByTenantIdAndName [{}][{}]", tenantId, name);
90 - validateId(tenantId, "Incorrect tenantId " + tenantId); 91 + validateId(tenantId, INCORRECT_TENANT_ID + tenantId);
91 Optional<Device> deviceOpt = deviceDao.findDeviceByTenantIdAndName(tenantId.getId(), name); 92 Optional<Device> deviceOpt = deviceDao.findDeviceByTenantIdAndName(tenantId.getId(), name);
92 if (deviceOpt.isPresent()) { 93 if (deviceOpt.isPresent()) {
93 return Optional.of(deviceOpt.get()); 94 return Optional.of(deviceOpt.get());
@@ -128,7 +129,7 @@ public class DeviceServiceImpl extends AbstractEntityService implements DeviceSe @@ -128,7 +129,7 @@ public class DeviceServiceImpl extends AbstractEntityService implements DeviceSe
128 @Override 129 @Override
129 public void deleteDevice(DeviceId deviceId) { 130 public void deleteDevice(DeviceId deviceId) {
130 log.trace("Executing deleteDevice [{}]", deviceId); 131 log.trace("Executing deleteDevice [{}]", deviceId);
131 - validateId(deviceId, "Incorrect deviceId " + deviceId); 132 + validateId(deviceId, INCORRECT_DEVICE_ID + deviceId);
132 DeviceCredentials deviceCredentials = deviceCredentialsService.findDeviceCredentialsByDeviceId(deviceId); 133 DeviceCredentials deviceCredentials = deviceCredentialsService.findDeviceCredentialsByDeviceId(deviceId);
133 if (deviceCredentials != null) { 134 if (deviceCredentials != null) {
134 deviceCredentialsService.deleteDeviceCredentials(deviceCredentials); 135 deviceCredentialsService.deleteDeviceCredentials(deviceCredentials);
@@ -140,8 +141,8 @@ public class DeviceServiceImpl extends AbstractEntityService implements DeviceSe @@ -140,8 +141,8 @@ public class DeviceServiceImpl extends AbstractEntityService implements DeviceSe
140 @Override 141 @Override
141 public TextPageData<Device> findDevicesByTenantId(TenantId tenantId, TextPageLink pageLink) { 142 public TextPageData<Device> findDevicesByTenantId(TenantId tenantId, TextPageLink pageLink) {
142 log.trace("Executing findDevicesByTenantId, tenantId [{}], pageLink [{}]", tenantId, pageLink); 143 log.trace("Executing findDevicesByTenantId, tenantId [{}], pageLink [{}]", tenantId, pageLink);
143 - validateId(tenantId, "Incorrect tenantId " + tenantId);  
144 - validatePageLink(pageLink, "Incorrect page link " + pageLink); 144 + validateId(tenantId, INCORRECT_TENANT_ID + tenantId);
  145 + validatePageLink(pageLink, INCORRECT_PAGE_LINK + pageLink);
145 List<Device> devices = deviceDao.findDevicesByTenantId(tenantId.getId(), pageLink); 146 List<Device> devices = deviceDao.findDevicesByTenantId(tenantId.getId(), pageLink);
146 return new TextPageData<>(devices, pageLink); 147 return new TextPageData<>(devices, pageLink);
147 } 148 }
@@ -149,9 +150,9 @@ public class DeviceServiceImpl extends AbstractEntityService implements DeviceSe @@ -149,9 +150,9 @@ public class DeviceServiceImpl extends AbstractEntityService implements DeviceSe
149 @Override 150 @Override
150 public TextPageData<Device> findDevicesByTenantIdAndType(TenantId tenantId, String type, TextPageLink pageLink) { 151 public TextPageData<Device> findDevicesByTenantIdAndType(TenantId tenantId, String type, TextPageLink pageLink) {
151 log.trace("Executing findDevicesByTenantIdAndType, tenantId [{}], type [{}], pageLink [{}]", tenantId, type, pageLink); 152 log.trace("Executing findDevicesByTenantIdAndType, tenantId [{}], type [{}], pageLink [{}]", tenantId, type, pageLink);
152 - validateId(tenantId, "Incorrect tenantId " + tenantId); 153 + validateId(tenantId, INCORRECT_TENANT_ID + tenantId);
153 validateString(type, "Incorrect type " + type); 154 validateString(type, "Incorrect type " + type);
154 - validatePageLink(pageLink, "Incorrect page link " + pageLink); 155 + validatePageLink(pageLink, INCORRECT_PAGE_LINK + pageLink);
155 List<Device> devices = deviceDao.findDevicesByTenantIdAndType(tenantId.getId(), type, pageLink); 156 List<Device> devices = deviceDao.findDevicesByTenantIdAndType(tenantId.getId(), type, pageLink);
156 return new TextPageData<>(devices, pageLink); 157 return new TextPageData<>(devices, pageLink);
157 } 158 }
@@ -159,7 +160,7 @@ public class DeviceServiceImpl extends AbstractEntityService implements DeviceSe @@ -159,7 +160,7 @@ public class DeviceServiceImpl extends AbstractEntityService implements DeviceSe
159 @Override 160 @Override
160 public ListenableFuture<List<Device>> findDevicesByTenantIdAndIdsAsync(TenantId tenantId, List<DeviceId> deviceIds) { 161 public ListenableFuture<List<Device>> findDevicesByTenantIdAndIdsAsync(TenantId tenantId, List<DeviceId> deviceIds) {
161 log.trace("Executing findDevicesByTenantIdAndIdsAsync, tenantId [{}], deviceIds [{}]", tenantId, deviceIds); 162 log.trace("Executing findDevicesByTenantIdAndIdsAsync, tenantId [{}], deviceIds [{}]", tenantId, deviceIds);
162 - validateId(tenantId, "Incorrect tenantId " + tenantId); 163 + validateId(tenantId, INCORRECT_TENANT_ID + tenantId);
163 validateIds(deviceIds, "Incorrect deviceIds " + deviceIds); 164 validateIds(deviceIds, "Incorrect deviceIds " + deviceIds);
164 return deviceDao.findDevicesByTenantIdAndIdsAsync(tenantId.getId(), toUUIDs(deviceIds)); 165 return deviceDao.findDevicesByTenantIdAndIdsAsync(tenantId.getId(), toUUIDs(deviceIds));
165 } 166 }
@@ -168,16 +169,16 @@ public class DeviceServiceImpl extends AbstractEntityService implements DeviceSe @@ -168,16 +169,16 @@ public class DeviceServiceImpl extends AbstractEntityService implements DeviceSe
168 @Override 169 @Override
169 public void deleteDevicesByTenantId(TenantId tenantId) { 170 public void deleteDevicesByTenantId(TenantId tenantId) {
170 log.trace("Executing deleteDevicesByTenantId, tenantId [{}]", tenantId); 171 log.trace("Executing deleteDevicesByTenantId, tenantId [{}]", tenantId);
171 - validateId(tenantId, "Incorrect tenantId " + tenantId); 172 + validateId(tenantId, INCORRECT_TENANT_ID + tenantId);
172 tenantDevicesRemover.removeEntities(tenantId); 173 tenantDevicesRemover.removeEntities(tenantId);
173 } 174 }
174 175
175 @Override 176 @Override
176 public TextPageData<Device> findDevicesByTenantIdAndCustomerId(TenantId tenantId, CustomerId customerId, TextPageLink pageLink) { 177 public TextPageData<Device> findDevicesByTenantIdAndCustomerId(TenantId tenantId, CustomerId customerId, TextPageLink pageLink) {
177 log.trace("Executing findDevicesByTenantIdAndCustomerId, tenantId [{}], customerId [{}], pageLink [{}]", tenantId, customerId, pageLink); 178 log.trace("Executing findDevicesByTenantIdAndCustomerId, tenantId [{}], customerId [{}], pageLink [{}]", tenantId, customerId, pageLink);
178 - validateId(tenantId, "Incorrect tenantId " + tenantId);  
179 - validateId(customerId, "Incorrect customerId " + customerId);  
180 - validatePageLink(pageLink, "Incorrect page link " + pageLink); 179 + validateId(tenantId, INCORRECT_TENANT_ID + tenantId);
  180 + validateId(customerId, INCORRECT_CUSTOMER_ID + customerId);
  181 + validatePageLink(pageLink, INCORRECT_PAGE_LINK + pageLink);
181 List<Device> devices = deviceDao.findDevicesByTenantIdAndCustomerId(tenantId.getId(), customerId.getId(), pageLink); 182 List<Device> devices = deviceDao.findDevicesByTenantIdAndCustomerId(tenantId.getId(), customerId.getId(), pageLink);
182 return new TextPageData<>(devices, pageLink); 183 return new TextPageData<>(devices, pageLink);
183 } 184 }
@@ -185,10 +186,10 @@ public class DeviceServiceImpl extends AbstractEntityService implements DeviceSe @@ -185,10 +186,10 @@ public class DeviceServiceImpl extends AbstractEntityService implements DeviceSe
185 @Override 186 @Override
186 public TextPageData<Device> findDevicesByTenantIdAndCustomerIdAndType(TenantId tenantId, CustomerId customerId, String type, TextPageLink pageLink) { 187 public TextPageData<Device> findDevicesByTenantIdAndCustomerIdAndType(TenantId tenantId, CustomerId customerId, String type, TextPageLink pageLink) {
187 log.trace("Executing findDevicesByTenantIdAndCustomerIdAndType, tenantId [{}], customerId [{}], type [{}], pageLink [{}]", tenantId, customerId, type, pageLink); 188 log.trace("Executing findDevicesByTenantIdAndCustomerIdAndType, tenantId [{}], customerId [{}], type [{}], pageLink [{}]", tenantId, customerId, type, pageLink);
188 - validateId(tenantId, "Incorrect tenantId " + tenantId);  
189 - validateId(customerId, "Incorrect customerId " + customerId); 189 + validateId(tenantId, INCORRECT_TENANT_ID + tenantId);
  190 + validateId(customerId, INCORRECT_CUSTOMER_ID + customerId);
190 validateString(type, "Incorrect type " + type); 191 validateString(type, "Incorrect type " + type);
191 - validatePageLink(pageLink, "Incorrect page link " + pageLink); 192 + validatePageLink(pageLink, INCORRECT_PAGE_LINK + pageLink);
192 List<Device> devices = deviceDao.findDevicesByTenantIdAndCustomerIdAndType(tenantId.getId(), customerId.getId(), type, pageLink); 193 List<Device> devices = deviceDao.findDevicesByTenantIdAndCustomerIdAndType(tenantId.getId(), customerId.getId(), type, pageLink);
193 return new TextPageData<>(devices, pageLink); 194 return new TextPageData<>(devices, pageLink);
194 } 195 }
@@ -196,8 +197,8 @@ public class DeviceServiceImpl extends AbstractEntityService implements DeviceSe @@ -196,8 +197,8 @@ public class DeviceServiceImpl extends AbstractEntityService implements DeviceSe
196 @Override 197 @Override
197 public ListenableFuture<List<Device>> findDevicesByTenantIdCustomerIdAndIdsAsync(TenantId tenantId, CustomerId customerId, List<DeviceId> deviceIds) { 198 public ListenableFuture<List<Device>> findDevicesByTenantIdCustomerIdAndIdsAsync(TenantId tenantId, CustomerId customerId, List<DeviceId> deviceIds) {
198 log.trace("Executing findDevicesByTenantIdCustomerIdAndIdsAsync, tenantId [{}], customerId [{}], deviceIds [{}]", tenantId, customerId, deviceIds); 199 log.trace("Executing findDevicesByTenantIdCustomerIdAndIdsAsync, tenantId [{}], customerId [{}], deviceIds [{}]", tenantId, customerId, deviceIds);
199 - validateId(tenantId, "Incorrect tenantId " + tenantId);  
200 - validateId(customerId, "Incorrect customerId " + customerId); 200 + validateId(tenantId, INCORRECT_TENANT_ID + tenantId);
  201 + validateId(customerId, INCORRECT_CUSTOMER_ID + customerId);
201 validateIds(deviceIds, "Incorrect deviceIds " + deviceIds); 202 validateIds(deviceIds, "Incorrect deviceIds " + deviceIds);
202 return deviceDao.findDevicesByTenantIdCustomerIdAndIdsAsync(tenantId.getId(), 203 return deviceDao.findDevicesByTenantIdCustomerIdAndIdsAsync(tenantId.getId(),
203 customerId.getId(), toUUIDs(deviceIds)); 204 customerId.getId(), toUUIDs(deviceIds));
@@ -206,8 +207,8 @@ public class DeviceServiceImpl extends AbstractEntityService implements DeviceSe @@ -206,8 +207,8 @@ public class DeviceServiceImpl extends AbstractEntityService implements DeviceSe
206 @Override 207 @Override
207 public void unassignCustomerDevices(TenantId tenantId, CustomerId customerId) { 208 public void unassignCustomerDevices(TenantId tenantId, CustomerId customerId) {
208 log.trace("Executing unassignCustomerDevices, tenantId [{}], customerId [{}]", tenantId, customerId); 209 log.trace("Executing unassignCustomerDevices, tenantId [{}], customerId [{}]", tenantId, customerId);
209 - validateId(tenantId, "Incorrect tenantId " + tenantId);  
210 - validateId(customerId, "Incorrect customerId " + customerId); 210 + validateId(tenantId, INCORRECT_TENANT_ID + tenantId);
  211 + validateId(customerId, INCORRECT_CUSTOMER_ID + customerId);
211 new CustomerDevicesUnassigner(tenantId).removeEntities(customerId); 212 new CustomerDevicesUnassigner(tenantId).removeEntities(customerId);
212 } 213 }
213 214
@@ -230,7 +231,7 @@ public class DeviceServiceImpl extends AbstractEntityService implements DeviceSe @@ -230,7 +231,7 @@ public class DeviceServiceImpl extends AbstractEntityService implements DeviceSe
230 @Nullable 231 @Nullable
231 @Override 232 @Override
232 public List<Device> apply(@Nullable List<Device> deviceList) { 233 public List<Device> apply(@Nullable List<Device> deviceList) {
233 - return deviceList.stream().filter(device -> query.getDeviceTypes().contains(device.getType())).collect(Collectors.toList()); 234 + return deviceList == null ? Collections.emptyList() : deviceList.stream().filter(device -> query.getDeviceTypes().contains(device.getType())).collect(Collectors.toList());
234 } 235 }
235 }); 236 });
236 237
@@ -240,7 +241,7 @@ public class DeviceServiceImpl extends AbstractEntityService implements DeviceSe @@ -240,7 +241,7 @@ public class DeviceServiceImpl extends AbstractEntityService implements DeviceSe
240 @Override 241 @Override
241 public ListenableFuture<List<EntitySubtype>> findDeviceTypesByTenantId(TenantId tenantId) { 242 public ListenableFuture<List<EntitySubtype>> findDeviceTypesByTenantId(TenantId tenantId) {
242 log.trace("Executing findDeviceTypesByTenantId, tenantId [{}]", tenantId); 243 log.trace("Executing findDeviceTypesByTenantId, tenantId [{}]", tenantId);
243 - validateId(tenantId, "Incorrect tenantId " + tenantId); 244 + validateId(tenantId, INCORRECT_TENANT_ID + tenantId);
244 ListenableFuture<List<EntitySubtype>> tenantDeviceTypes = deviceDao.findTenantDeviceTypesAsync(tenantId.getId()); 245 ListenableFuture<List<EntitySubtype>> tenantDeviceTypes = deviceDao.findTenantDeviceTypesAsync(tenantId.getId());
245 return Futures.transform(tenantDeviceTypes, 246 return Futures.transform(tenantDeviceTypes,
246 (Function<List<EntitySubtype>, List<EntitySubtype>>) deviceTypes -> { 247 (Function<List<EntitySubtype>, List<EntitySubtype>>) deviceTypes -> {
@@ -31,12 +31,7 @@ public abstract class AbstractEntityService { @@ -31,12 +31,7 @@ public abstract class AbstractEntityService {
31 31
32 protected void deleteEntityRelations(EntityId entityId) { 32 protected void deleteEntityRelations(EntityId entityId) {
33 log.trace("Executing deleteEntityRelations [{}]", entityId); 33 log.trace("Executing deleteEntityRelations [{}]", entityId);
34 - try {  
35 - relationService.deleteEntityRelations(entityId).get();  
36 - } catch (InterruptedException | ExecutionException e) {  
37 - throw new RuntimeException(e);  
38 - } 34 + relationService.deleteEntityRelations(entityId);
39 } 35 }
40 36
41 -  
42 } 37 }
@@ -18,7 +18,7 @@ package org.thingsboard.server.dao.model; @@ -18,7 +18,7 @@ package org.thingsboard.server.dao.model;
18 import java.io.Serializable; 18 import java.io.Serializable;
19 import java.util.UUID; 19 import java.util.UUID;
20 20
21 -public interface BaseEntity<D> extends ToData<D>, Serializable { 21 +public interface BaseEntity<D> extends ToData<D> {
22 22
23 UUID getId(); 23 UUID getId();
24 24
@@ -19,7 +19,6 @@ package org.thingsboard.server.dao.model; @@ -19,7 +19,6 @@ package org.thingsboard.server.dao.model;
19 import com.datastax.driver.mapping.annotations.Column; 19 import com.datastax.driver.mapping.annotations.Column;
20 import com.datastax.driver.mapping.annotations.PartitionKey; 20 import com.datastax.driver.mapping.annotations.PartitionKey;
21 import com.datastax.driver.mapping.annotations.Table; 21 import com.datastax.driver.mapping.annotations.Table;
22 -import com.datastax.driver.mapping.annotations.Transient;  
23 import org.thingsboard.server.common.data.EntitySubtype; 22 import org.thingsboard.server.common.data.EntitySubtype;
24 import org.thingsboard.server.common.data.EntityType; 23 import org.thingsboard.server.common.data.EntityType;
25 import org.thingsboard.server.common.data.id.TenantId; 24 import org.thingsboard.server.common.data.id.TenantId;
@@ -32,9 +31,6 @@ import static org.thingsboard.server.dao.model.ModelConstants.*; @@ -32,9 +31,6 @@ import static org.thingsboard.server.dao.model.ModelConstants.*;
32 @Table(name = ENTITY_SUBTYPE_COLUMN_FAMILY_NAME) 31 @Table(name = ENTITY_SUBTYPE_COLUMN_FAMILY_NAME)
33 public class EntitySubtypeEntity { 32 public class EntitySubtypeEntity {
34 33
35 - @Transient  
36 - private static final long serialVersionUID = -1268181961886910152L;  
37 -  
38 @PartitionKey(value = 0) 34 @PartitionKey(value = 0)
39 @Column(name = ENTITY_SUBTYPE_TENANT_ID_PROPERTY) 35 @Column(name = ENTITY_SUBTYPE_TENANT_ID_PROPERTY)
40 private UUID tenantId; 36 private UUID tenantId;
@@ -27,8 +27,8 @@ public class ModelConstants { @@ -27,8 +27,8 @@ public class ModelConstants {
27 private ModelConstants() { 27 private ModelConstants() {
28 } 28 }
29 29
30 - public static UUID NULL_UUID = UUIDs.startOf(0);  
31 - public static String NULL_UUID_STR = UUIDConverter.fromTimeUUID(NULL_UUID); 30 + public static final UUID NULL_UUID = UUIDs.startOf(0);
  31 + public static final String NULL_UUID_STR = UUIDConverter.fromTimeUUID(NULL_UUID);
32 32
33 /** 33 /**
34 * Generic constants. 34 * Generic constants.
@@ -42,6 +42,7 @@ public class ModelConstants { @@ -42,6 +42,7 @@ public class ModelConstants {
42 public static final String ALIAS_PROPERTY = "alias"; 42 public static final String ALIAS_PROPERTY = "alias";
43 public static final String SEARCH_TEXT_PROPERTY = "search_text"; 43 public static final String SEARCH_TEXT_PROPERTY = "search_text";
44 public static final String ADDITIONAL_INFO_PROPERTY = "additional_info"; 44 public static final String ADDITIONAL_INFO_PROPERTY = "additional_info";
  45 + public static final String ENTITY_TYPE_PROPERTY = "entity_type";
45 46
46 /** 47 /**
47 * Cassandra user constants. 48 * Cassandra user constants.
@@ -66,7 +67,7 @@ public class ModelConstants { @@ -66,7 +67,7 @@ public class ModelConstants {
66 public static final String USER_CREDENTIALS_COLUMN_FAMILY_NAME = "user_credentials"; 67 public static final String USER_CREDENTIALS_COLUMN_FAMILY_NAME = "user_credentials";
67 public static final String USER_CREDENTIALS_USER_ID_PROPERTY = USER_ID_PROPERTY; 68 public static final String USER_CREDENTIALS_USER_ID_PROPERTY = USER_ID_PROPERTY;
68 public static final String USER_CREDENTIALS_ENABLED_PROPERTY = "enabled"; 69 public static final String USER_CREDENTIALS_ENABLED_PROPERTY = "enabled";
69 - public static final String USER_CREDENTIALS_PASSWORD_PROPERTY = "password"; 70 + public static final String USER_CREDENTIALS_PASSWORD_PROPERTY = "password"; //NOSONAR, the constant used to identify password column name (not password value itself)
70 public static final String USER_CREDENTIALS_ACTIVATE_TOKEN_PROPERTY = "activate_token"; 71 public static final String USER_CREDENTIALS_ACTIVATE_TOKEN_PROPERTY = "activate_token";
71 public static final String USER_CREDENTIALS_RESET_TOKEN_PROPERTY = "reset_token"; 72 public static final String USER_CREDENTIALS_RESET_TOKEN_PROPERTY = "reset_token";
72 73
@@ -155,7 +156,7 @@ public class ModelConstants { @@ -155,7 +156,7 @@ public class ModelConstants {
155 */ 156 */
156 public static final String ENTITY_SUBTYPE_COLUMN_FAMILY_NAME = "entity_subtype"; 157 public static final String ENTITY_SUBTYPE_COLUMN_FAMILY_NAME = "entity_subtype";
157 public static final String ENTITY_SUBTYPE_TENANT_ID_PROPERTY = TENANT_ID_PROPERTY; 158 public static final String ENTITY_SUBTYPE_TENANT_ID_PROPERTY = TENANT_ID_PROPERTY;
158 - public static final String ENTITY_SUBTYPE_ENTITY_TYPE_PROPERTY = "entity_type"; 159 + public static final String ENTITY_SUBTYPE_ENTITY_TYPE_PROPERTY = ENTITY_TYPE_PROPERTY;
159 public static final String ENTITY_SUBTYPE_TYPE_PROPERTY = "type"; 160 public static final String ENTITY_SUBTYPE_TYPE_PROPERTY = "type";
160 161
161 /** 162 /**
@@ -250,7 +251,7 @@ public class ModelConstants { @@ -250,7 +251,7 @@ public class ModelConstants {
250 public static final String PLUGIN_API_TOKEN_PROPERTY = "api_token"; 251 public static final String PLUGIN_API_TOKEN_PROPERTY = "api_token";
251 public static final String PLUGIN_CLASS_PROPERTY = "plugin_class"; 252 public static final String PLUGIN_CLASS_PROPERTY = "plugin_class";
252 public static final String PLUGIN_ACCESS_PROPERTY = "public_access"; 253 public static final String PLUGIN_ACCESS_PROPERTY = "public_access";
253 - public static final String PLUGIN_STATE_PROPERTY = "state"; 254 + public static final String PLUGIN_STATE_PROPERTY = STATE_PROPERTY;
254 public static final String PLUGIN_CONFIGURATION_PROPERTY = "configuration"; 255 public static final String PLUGIN_CONFIGURATION_PROPERTY = "configuration";
255 256
256 public static final String PLUGIN_BY_API_TOKEN_COLUMN_FAMILY_NAME = "plugin_by_api_token"; 257 public static final String PLUGIN_BY_API_TOKEN_COLUMN_FAMILY_NAME = "plugin_by_api_token";
@@ -277,7 +278,7 @@ public class ModelConstants { @@ -277,7 +278,7 @@ public class ModelConstants {
277 public static final String RULE_COLUMN_FAMILY_NAME = "rule"; 278 public static final String RULE_COLUMN_FAMILY_NAME = "rule";
278 public static final String RULE_TENANT_ID_PROPERTY = TENANT_ID_PROPERTY; 279 public static final String RULE_TENANT_ID_PROPERTY = TENANT_ID_PROPERTY;
279 public static final String RULE_NAME_PROPERTY = "name"; 280 public static final String RULE_NAME_PROPERTY = "name";
280 - public static final String RULE_STATE_PROPERTY = "state"; 281 + public static final String RULE_STATE_PROPERTY = STATE_PROPERTY;
281 public static final String RULE_WEIGHT_PROPERTY = "weight"; 282 public static final String RULE_WEIGHT_PROPERTY = "weight";
282 public static final String RULE_PLUGIN_TOKEN_PROPERTY = "plugin_token"; 283 public static final String RULE_PLUGIN_TOKEN_PROPERTY = "plugin_token";
283 public static final String RULE_FILTERS = "filters"; 284 public static final String RULE_FILTERS = "filters";
@@ -294,7 +295,7 @@ public class ModelConstants { @@ -294,7 +295,7 @@ public class ModelConstants {
294 public static final String EVENT_TENANT_ID_PROPERTY = TENANT_ID_PROPERTY; 295 public static final String EVENT_TENANT_ID_PROPERTY = TENANT_ID_PROPERTY;
295 public static final String EVENT_TYPE_PROPERTY = "event_type"; 296 public static final String EVENT_TYPE_PROPERTY = "event_type";
296 public static final String EVENT_UID_PROPERTY = "event_uid"; 297 public static final String EVENT_UID_PROPERTY = "event_uid";
297 - public static final String EVENT_ENTITY_TYPE_PROPERTY = "entity_type"; 298 + public static final String EVENT_ENTITY_TYPE_PROPERTY = ENTITY_TYPE_PROPERTY;
298 public static final String EVENT_ENTITY_ID_PROPERTY = "entity_id"; 299 public static final String EVENT_ENTITY_ID_PROPERTY = "entity_id";
299 public static final String EVENT_BODY_PROPERTY = "body"; 300 public static final String EVENT_BODY_PROPERTY = "body";
300 301
@@ -310,7 +311,7 @@ public class ModelConstants { @@ -310,7 +311,7 @@ public class ModelConstants {
310 public static final String TS_KV_LATEST_CF = "ts_kv_latest_cf"; 311 public static final String TS_KV_LATEST_CF = "ts_kv_latest_cf";
311 312
312 313
313 - public static final String ENTITY_TYPE_COLUMN = "entity_type"; 314 + public static final String ENTITY_TYPE_COLUMN = ENTITY_TYPE_PROPERTY;
314 public static final String ENTITY_ID_COLUMN = "entity_id"; 315 public static final String ENTITY_ID_COLUMN = "entity_id";
315 public static final String ATTRIBUTE_TYPE_COLUMN = "attribute_type"; 316 public static final String ATTRIBUTE_TYPE_COLUMN = "attribute_type";
316 public static final String ATTRIBUTE_KEY_COLUMN = "attribute_key"; 317 public static final String ATTRIBUTE_KEY_COLUMN = "attribute_key";
@@ -328,17 +329,17 @@ public class ModelConstants { @@ -328,17 +329,17 @@ public class ModelConstants {
328 public static final String LONG_VALUE_COLUMN = "long_v"; 329 public static final String LONG_VALUE_COLUMN = "long_v";
329 public static final String DOUBLE_VALUE_COLUMN = "dbl_v"; 330 public static final String DOUBLE_VALUE_COLUMN = "dbl_v";
330 331
331 - public static final String[] NONE_AGGREGATION_COLUMNS = new String[]{LONG_VALUE_COLUMN, DOUBLE_VALUE_COLUMN, BOOLEAN_VALUE_COLUMN, STRING_VALUE_COLUMN, KEY_COLUMN, TS_COLUMN}; 332 + protected static final String[] NONE_AGGREGATION_COLUMNS = new String[]{LONG_VALUE_COLUMN, DOUBLE_VALUE_COLUMN, BOOLEAN_VALUE_COLUMN, STRING_VALUE_COLUMN, KEY_COLUMN, TS_COLUMN};
332 333
333 - public static final String[] COUNT_AGGREGATION_COLUMNS = new String[]{count(LONG_VALUE_COLUMN), count(DOUBLE_VALUE_COLUMN), count(BOOLEAN_VALUE_COLUMN), count(STRING_VALUE_COLUMN)}; 334 + protected static final String[] COUNT_AGGREGATION_COLUMNS = new String[]{count(LONG_VALUE_COLUMN), count(DOUBLE_VALUE_COLUMN), count(BOOLEAN_VALUE_COLUMN), count(STRING_VALUE_COLUMN)};
334 335
335 - public static final String[] MIN_AGGREGATION_COLUMNS = ArrayUtils.addAll(COUNT_AGGREGATION_COLUMNS, 336 + protected static final String[] MIN_AGGREGATION_COLUMNS = ArrayUtils.addAll(COUNT_AGGREGATION_COLUMNS,
336 new String[]{min(LONG_VALUE_COLUMN), min(DOUBLE_VALUE_COLUMN), min(BOOLEAN_VALUE_COLUMN), min(STRING_VALUE_COLUMN)}); 337 new String[]{min(LONG_VALUE_COLUMN), min(DOUBLE_VALUE_COLUMN), min(BOOLEAN_VALUE_COLUMN), min(STRING_VALUE_COLUMN)});
337 - public static final String[] MAX_AGGREGATION_COLUMNS = ArrayUtils.addAll(COUNT_AGGREGATION_COLUMNS, 338 + protected static final String[] MAX_AGGREGATION_COLUMNS = ArrayUtils.addAll(COUNT_AGGREGATION_COLUMNS,
338 new String[]{max(LONG_VALUE_COLUMN), max(DOUBLE_VALUE_COLUMN), max(BOOLEAN_VALUE_COLUMN), max(STRING_VALUE_COLUMN)}); 339 new String[]{max(LONG_VALUE_COLUMN), max(DOUBLE_VALUE_COLUMN), max(BOOLEAN_VALUE_COLUMN), max(STRING_VALUE_COLUMN)});
339 - public static final String[] SUM_AGGREGATION_COLUMNS = ArrayUtils.addAll(COUNT_AGGREGATION_COLUMNS, 340 + protected static final String[] SUM_AGGREGATION_COLUMNS = ArrayUtils.addAll(COUNT_AGGREGATION_COLUMNS,
340 new String[]{sum(LONG_VALUE_COLUMN), sum(DOUBLE_VALUE_COLUMN)}); 341 new String[]{sum(LONG_VALUE_COLUMN), sum(DOUBLE_VALUE_COLUMN)});
341 - public static final String[] AVG_AGGREGATION_COLUMNS = SUM_AGGREGATION_COLUMNS; 342 + protected static final String[] AVG_AGGREGATION_COLUMNS = SUM_AGGREGATION_COLUMNS;
342 343
343 public static String min(String s) { 344 public static String min(String s) {
344 return "min(" + s + ")"; 345 return "min(" + s + ")";
@@ -19,8 +19,9 @@ import com.datastax.driver.core.utils.UUIDs; @@ -19,8 +19,9 @@ import com.datastax.driver.core.utils.UUIDs;
19 import com.datastax.driver.mapping.annotations.Column; 19 import com.datastax.driver.mapping.annotations.Column;
20 import com.datastax.driver.mapping.annotations.PartitionKey; 20 import com.datastax.driver.mapping.annotations.PartitionKey;
21 import com.datastax.driver.mapping.annotations.Table; 21 import com.datastax.driver.mapping.annotations.Table;
22 -import com.datastax.driver.mapping.annotations.Transient;  
23 import com.fasterxml.jackson.databind.JsonNode; 22 import com.fasterxml.jackson.databind.JsonNode;
  23 +import lombok.EqualsAndHashCode;
  24 +import lombok.ToString;
24 import org.thingsboard.server.common.data.AdminSettings; 25 import org.thingsboard.server.common.data.AdminSettings;
25 import org.thingsboard.server.common.data.id.AdminSettingsId; 26 import org.thingsboard.server.common.data.id.AdminSettingsId;
26 import org.thingsboard.server.dao.model.BaseEntity; 27 import org.thingsboard.server.dao.model.BaseEntity;
@@ -31,11 +32,10 @@ import java.util.UUID; @@ -31,11 +32,10 @@ import java.util.UUID;
31 import static org.thingsboard.server.dao.model.ModelConstants.*; 32 import static org.thingsboard.server.dao.model.ModelConstants.*;
32 33
33 @Table(name = ADMIN_SETTINGS_COLUMN_FAMILY_NAME) 34 @Table(name = ADMIN_SETTINGS_COLUMN_FAMILY_NAME)
  35 +@EqualsAndHashCode
  36 +@ToString
34 public final class AdminSettingsEntity implements BaseEntity<AdminSettings> { 37 public final class AdminSettingsEntity implements BaseEntity<AdminSettings> {
35 38
36 - @Transient  
37 - private static final long serialVersionUID = 899117723388310403L;  
38 -  
39 @PartitionKey(value = 0) 39 @PartitionKey(value = 0)
40 @Column(name = ID_PROPERTY) 40 @Column(name = ID_PROPERTY)
41 private UUID id; 41 private UUID id;
@@ -83,56 +83,6 @@ public final class AdminSettingsEntity implements BaseEntity<AdminSettings> { @@ -83,56 +83,6 @@ public final class AdminSettingsEntity implements BaseEntity<AdminSettings> {
83 } 83 }
84 84
85 @Override 85 @Override
86 - public int hashCode() {  
87 - final int prime = 31;  
88 - int result = 1;  
89 - result = prime * result + ((id == null) ? 0 : id.hashCode());  
90 - result = prime * result + ((jsonValue == null) ? 0 : jsonValue.hashCode());  
91 - result = prime * result + ((key == null) ? 0 : key.hashCode());  
92 - return result;  
93 - }  
94 -  
95 - @Override  
96 - public boolean equals(Object obj) {  
97 - if (this == obj)  
98 - return true;  
99 - if (obj == null)  
100 - return false;  
101 - if (getClass() != obj.getClass())  
102 - return false;  
103 - AdminSettingsEntity other = (AdminSettingsEntity) obj;  
104 - if (id == null) {  
105 - if (other.id != null)  
106 - return false;  
107 - } else if (!id.equals(other.id))  
108 - return false;  
109 - if (jsonValue == null) {  
110 - if (other.jsonValue != null)  
111 - return false;  
112 - } else if (!jsonValue.equals(other.jsonValue))  
113 - return false;  
114 - if (key == null) {  
115 - if (other.key != null)  
116 - return false;  
117 - } else if (!key.equals(other.key))  
118 - return false;  
119 - return true;  
120 - }  
121 -  
122 - @Override  
123 - public String toString() {  
124 - StringBuilder builder = new StringBuilder();  
125 - builder.append("AdminSettingsEntity [id=");  
126 - builder.append(id);  
127 - builder.append(", key=");  
128 - builder.append(key);  
129 - builder.append(", jsonValue=");  
130 - builder.append(jsonValue);  
131 - builder.append("]");  
132 - return builder.toString();  
133 - }  
134 -  
135 - @Override  
136 public AdminSettings toData() { 86 public AdminSettings toData() {
137 AdminSettings adminSettings = new AdminSettings(new AdminSettingsId(id)); 87 AdminSettings adminSettings = new AdminSettings(new AdminSettingsId(id));
138 adminSettings.setCreatedTime(UUIDs.unixTimestamp(id)); 88 adminSettings.setCreatedTime(UUIDs.unixTimestamp(id));
@@ -18,6 +18,8 @@ package org.thingsboard.server.dao.model.nosql; @@ -18,6 +18,8 @@ package org.thingsboard.server.dao.model.nosql;
18 import com.datastax.driver.core.utils.UUIDs; 18 import com.datastax.driver.core.utils.UUIDs;
19 import com.datastax.driver.mapping.annotations.*; 19 import com.datastax.driver.mapping.annotations.*;
20 import com.fasterxml.jackson.databind.JsonNode; 20 import com.fasterxml.jackson.databind.JsonNode;
  21 +import lombok.EqualsAndHashCode;
  22 +import lombok.ToString;
21 import org.thingsboard.server.common.data.EntityType; 23 import org.thingsboard.server.common.data.EntityType;
22 import org.thingsboard.server.common.data.alarm.Alarm; 24 import org.thingsboard.server.common.data.alarm.Alarm;
23 import org.thingsboard.server.common.data.alarm.AlarmId; 25 import org.thingsboard.server.common.data.alarm.AlarmId;
@@ -36,11 +38,10 @@ import java.util.UUID; @@ -36,11 +38,10 @@ import java.util.UUID;
36 import static org.thingsboard.server.dao.model.ModelConstants.*; 38 import static org.thingsboard.server.dao.model.ModelConstants.*;
37 39
38 @Table(name = ALARM_COLUMN_FAMILY_NAME) 40 @Table(name = ALARM_COLUMN_FAMILY_NAME)
  41 +@EqualsAndHashCode
  42 +@ToString
39 public final class AlarmEntity implements BaseEntity<Alarm> { 43 public final class AlarmEntity implements BaseEntity<Alarm> {
40 44
41 - @Transient  
42 - private static final long serialVersionUID = -1265181166886910152L;  
43 -  
44 @ClusteringColumn(value = 1) 45 @ClusteringColumn(value = 1)
45 @Column(name = ID_PROPERTY) 46 @Column(name = ID_PROPERTY)
46 private UUID id; 47 private UUID id;
@@ -19,8 +19,9 @@ import com.datastax.driver.core.utils.UUIDs; @@ -19,8 +19,9 @@ import com.datastax.driver.core.utils.UUIDs;
19 import com.datastax.driver.mapping.annotations.Column; 19 import com.datastax.driver.mapping.annotations.Column;
20 import com.datastax.driver.mapping.annotations.PartitionKey; 20 import com.datastax.driver.mapping.annotations.PartitionKey;
21 import com.datastax.driver.mapping.annotations.Table; 21 import com.datastax.driver.mapping.annotations.Table;
22 -import com.datastax.driver.mapping.annotations.Transient;  
23 import com.fasterxml.jackson.databind.JsonNode; 22 import com.fasterxml.jackson.databind.JsonNode;
  23 +import lombok.EqualsAndHashCode;
  24 +import lombok.ToString;
24 import org.thingsboard.server.common.data.asset.Asset; 25 import org.thingsboard.server.common.data.asset.Asset;
25 import org.thingsboard.server.common.data.id.AssetId; 26 import org.thingsboard.server.common.data.id.AssetId;
26 import org.thingsboard.server.common.data.id.CustomerId; 27 import org.thingsboard.server.common.data.id.CustomerId;
@@ -33,11 +34,10 @@ import java.util.UUID; @@ -33,11 +34,10 @@ import java.util.UUID;
33 import static org.thingsboard.server.dao.model.ModelConstants.*; 34 import static org.thingsboard.server.dao.model.ModelConstants.*;
34 35
35 @Table(name = ASSET_COLUMN_FAMILY_NAME) 36 @Table(name = ASSET_COLUMN_FAMILY_NAME)
  37 +@EqualsAndHashCode
  38 +@ToString
36 public final class AssetEntity implements SearchTextEntity<Asset> { 39 public final class AssetEntity implements SearchTextEntity<Asset> {
37 40
38 - @Transient  
39 - private static final long serialVersionUID = -1265181166886910152L;  
40 -  
41 @PartitionKey(value = 0) 41 @PartitionKey(value = 0)
42 @Column(name = ID_PROPERTY) 42 @Column(name = ID_PROPERTY)
43 private UUID id; 43 private UUID id;
@@ -132,7 +132,7 @@ public final class AssetEntity implements SearchTextEntity<Asset> { @@ -132,7 +132,7 @@ public final class AssetEntity implements SearchTextEntity<Asset> {
132 132
133 @Override 133 @Override
134 public String getSearchTextSource() { 134 public String getSearchTextSource() {
135 - return name; 135 + return getName();
136 } 136 }
137 137
138 @Override 138 @Override
@@ -145,80 +145,6 @@ public final class AssetEntity implements SearchTextEntity<Asset> { @@ -145,80 +145,6 @@ public final class AssetEntity implements SearchTextEntity<Asset> {
145 } 145 }
146 146
147 @Override 147 @Override
148 - public int hashCode() {  
149 - final int prime = 31;  
150 - int result = 1;  
151 - result = prime * result + ((additionalInfo == null) ? 0 : additionalInfo.hashCode());  
152 - result = prime * result + ((customerId == null) ? 0 : customerId.hashCode());  
153 - result = prime * result + ((id == null) ? 0 : id.hashCode());  
154 - result = prime * result + ((name == null) ? 0 : name.hashCode());  
155 - result = prime * result + ((type == null) ? 0 : type.hashCode());  
156 - result = prime * result + ((tenantId == null) ? 0 : tenantId.hashCode());  
157 - return result;  
158 - }  
159 -  
160 - @Override  
161 - public boolean equals(Object obj) {  
162 - if (this == obj)  
163 - return true;  
164 - if (obj == null)  
165 - return false;  
166 - if (getClass() != obj.getClass())  
167 - return false;  
168 - AssetEntity other = (AssetEntity) obj;  
169 - if (additionalInfo == null) {  
170 - if (other.additionalInfo != null)  
171 - return false;  
172 - } else if (!additionalInfo.equals(other.additionalInfo))  
173 - return false;  
174 - if (customerId == null) {  
175 - if (other.customerId != null)  
176 - return false;  
177 - } else if (!customerId.equals(other.customerId))  
178 - return false;  
179 - if (id == null) {  
180 - if (other.id != null)  
181 - return false;  
182 - } else if (!id.equals(other.id))  
183 - return false;  
184 - if (name == null) {  
185 - if (other.name != null)  
186 - return false;  
187 - } else if (!name.equals(other.name))  
188 - return false;  
189 - if (type == null) {  
190 - if (other.type != null)  
191 - return false;  
192 - } else if (!type.equals(other.type))  
193 - return false;  
194 - if (tenantId == null) {  
195 - if (other.tenantId != null)  
196 - return false;  
197 - } else if (!tenantId.equals(other.tenantId))  
198 - return false;  
199 - return true;  
200 - }  
201 -  
202 - @Override  
203 - public String toString() {  
204 - StringBuilder builder = new StringBuilder();  
205 - builder.append("AssetEntity [id=");  
206 - builder.append(id);  
207 - builder.append(", tenantId=");  
208 - builder.append(tenantId);  
209 - builder.append(", customerId=");  
210 - builder.append(customerId);  
211 - builder.append(", name=");  
212 - builder.append(name);  
213 - builder.append(", type=");  
214 - builder.append(type);  
215 - builder.append(", additionalInfo=");  
216 - builder.append(additionalInfo);  
217 - builder.append("]");  
218 - return builder.toString();  
219 - }  
220 -  
221 - @Override  
222 public Asset toData() { 148 public Asset toData() {
223 Asset asset = new Asset(new AssetId(id)); 149 Asset asset = new Asset(new AssetId(id));
224 asset.setCreatedTime(UUIDs.unixTimestamp(id)); 150 asset.setCreatedTime(UUIDs.unixTimestamp(id));
@@ -36,8 +36,6 @@ import static org.thingsboard.server.dao.model.ModelConstants.*; @@ -36,8 +36,6 @@ import static org.thingsboard.server.dao.model.ModelConstants.*;
36 @Table(name = COMPONENT_DESCRIPTOR_COLUMN_FAMILY_NAME) 36 @Table(name = COMPONENT_DESCRIPTOR_COLUMN_FAMILY_NAME)
37 public class ComponentDescriptorEntity implements SearchTextEntity<ComponentDescriptor> { 37 public class ComponentDescriptorEntity implements SearchTextEntity<ComponentDescriptor> {
38 38
39 - private static final long serialVersionUID = 1L;  
40 -  
41 @PartitionKey 39 @PartitionKey
42 @Column(name = ID_PROPERTY) 40 @Column(name = ID_PROPERTY)
43 private UUID id; 41 private UUID id;
@@ -160,6 +158,6 @@ public class ComponentDescriptorEntity implements SearchTextEntity<ComponentDesc @@ -160,6 +158,6 @@ public class ComponentDescriptorEntity implements SearchTextEntity<ComponentDesc
160 158
161 @Override 159 @Override
162 public String getSearchTextSource() { 160 public String getSearchTextSource() {
163 - return searchText; 161 + return getSearchText();
164 } 162 }
165 } 163 }
@@ -19,8 +19,9 @@ import com.datastax.driver.core.utils.UUIDs; @@ -19,8 +19,9 @@ import com.datastax.driver.core.utils.UUIDs;
19 import com.datastax.driver.mapping.annotations.Column; 19 import com.datastax.driver.mapping.annotations.Column;
20 import com.datastax.driver.mapping.annotations.PartitionKey; 20 import com.datastax.driver.mapping.annotations.PartitionKey;
21 import com.datastax.driver.mapping.annotations.Table; 21 import com.datastax.driver.mapping.annotations.Table;
22 -import com.datastax.driver.mapping.annotations.Transient;  
23 import com.fasterxml.jackson.databind.JsonNode; 22 import com.fasterxml.jackson.databind.JsonNode;
  23 +import lombok.EqualsAndHashCode;
  24 +import lombok.ToString;
24 import org.thingsboard.server.common.data.Customer; 25 import org.thingsboard.server.common.data.Customer;
25 import org.thingsboard.server.common.data.id.CustomerId; 26 import org.thingsboard.server.common.data.id.CustomerId;
26 import org.thingsboard.server.common.data.id.TenantId; 27 import org.thingsboard.server.common.data.id.TenantId;
@@ -32,11 +33,10 @@ import java.util.UUID; @@ -32,11 +33,10 @@ import java.util.UUID;
32 import static org.thingsboard.server.dao.model.ModelConstants.*; 33 import static org.thingsboard.server.dao.model.ModelConstants.*;
33 34
34 @Table(name = CUSTOMER_COLUMN_FAMILY_NAME) 35 @Table(name = CUSTOMER_COLUMN_FAMILY_NAME)
  36 +@EqualsAndHashCode
  37 +@ToString
35 public final class CustomerEntity implements SearchTextEntity<Customer> { 38 public final class CustomerEntity implements SearchTextEntity<Customer> {
36 39
37 - @Transient  
38 - private static final long serialVersionUID = -7732527103760948490L;  
39 -  
40 @PartitionKey(value = 0) 40 @PartitionKey(value = 0)
41 @Column(name = ID_PROPERTY) 41 @Column(name = ID_PROPERTY)
42 private UUID id; 42 private UUID id;
@@ -197,7 +197,7 @@ public final class CustomerEntity implements SearchTextEntity<Customer> { @@ -197,7 +197,7 @@ public final class CustomerEntity implements SearchTextEntity<Customer> {
197 197
198 @Override 198 @Override
199 public String getSearchTextSource() { 199 public String getSearchTextSource() {
200 - return title; 200 + return getTitle();
201 } 201 }
202 202
203 @Override 203 @Override
@@ -210,128 +210,6 @@ public final class CustomerEntity implements SearchTextEntity<Customer> { @@ -210,128 +210,6 @@ public final class CustomerEntity implements SearchTextEntity<Customer> {
210 } 210 }
211 211
212 @Override 212 @Override
213 - public int hashCode() {  
214 - final int prime = 31;  
215 - int result = 1;  
216 - result = prime * result + ((additionalInfo == null) ? 0 : additionalInfo.hashCode());  
217 - result = prime * result + ((address == null) ? 0 : address.hashCode());  
218 - result = prime * result + ((address2 == null) ? 0 : address2.hashCode());  
219 - result = prime * result + ((city == null) ? 0 : city.hashCode());  
220 - result = prime * result + ((country == null) ? 0 : country.hashCode());  
221 - result = prime * result + ((email == null) ? 0 : email.hashCode());  
222 - result = prime * result + ((id == null) ? 0 : id.hashCode());  
223 - result = prime * result + ((phone == null) ? 0 : phone.hashCode());  
224 - result = prime * result + ((state == null) ? 0 : state.hashCode());  
225 - result = prime * result + ((tenantId == null) ? 0 : tenantId.hashCode());  
226 - result = prime * result + ((title == null) ? 0 : title.hashCode());  
227 - result = prime * result + ((zip == null) ? 0 : zip.hashCode());  
228 - return result;  
229 - }  
230 -  
231 - @Override  
232 - public boolean equals(Object obj) {  
233 - if (this == obj)  
234 - return true;  
235 - if (obj == null)  
236 - return false;  
237 - if (getClass() != obj.getClass())  
238 - return false;  
239 - CustomerEntity other = (CustomerEntity) obj;  
240 - if (additionalInfo == null) {  
241 - if (other.additionalInfo != null)  
242 - return false;  
243 - } else if (!additionalInfo.equals(other.additionalInfo))  
244 - return false;  
245 - if (address == null) {  
246 - if (other.address != null)  
247 - return false;  
248 - } else if (!address.equals(other.address))  
249 - return false;  
250 - if (address2 == null) {  
251 - if (other.address2 != null)  
252 - return false;  
253 - } else if (!address2.equals(other.address2))  
254 - return false;  
255 - if (city == null) {  
256 - if (other.city != null)  
257 - return false;  
258 - } else if (!city.equals(other.city))  
259 - return false;  
260 - if (country == null) {  
261 - if (other.country != null)  
262 - return false;  
263 - } else if (!country.equals(other.country))  
264 - return false;  
265 - if (email == null) {  
266 - if (other.email != null)  
267 - return false;  
268 - } else if (!email.equals(other.email))  
269 - return false;  
270 - if (id == null) {  
271 - if (other.id != null)  
272 - return false;  
273 - } else if (!id.equals(other.id))  
274 - return false;  
275 - if (phone == null) {  
276 - if (other.phone != null)  
277 - return false;  
278 - } else if (!phone.equals(other.phone))  
279 - return false;  
280 - if (state == null) {  
281 - if (other.state != null)  
282 - return false;  
283 - } else if (!state.equals(other.state))  
284 - return false;  
285 - if (tenantId == null) {  
286 - if (other.tenantId != null)  
287 - return false;  
288 - } else if (!tenantId.equals(other.tenantId))  
289 - return false;  
290 - if (title == null) {  
291 - if (other.title != null)  
292 - return false;  
293 - } else if (!title.equals(other.title))  
294 - return false;  
295 - if (zip == null) {  
296 - if (other.zip != null)  
297 - return false;  
298 - } else if (!zip.equals(other.zip))  
299 - return false;  
300 - return true;  
301 - }  
302 -  
303 - @Override  
304 - public String toString() {  
305 - StringBuilder builder = new StringBuilder();  
306 - builder.append("CustomerEntity [id=");  
307 - builder.append(id);  
308 - builder.append(", tenantId=");  
309 - builder.append(tenantId);  
310 - builder.append(", title=");  
311 - builder.append(title);  
312 - builder.append(", country=");  
313 - builder.append(country);  
314 - builder.append(", state=");  
315 - builder.append(state);  
316 - builder.append(", city=");  
317 - builder.append(city);  
318 - builder.append(", address=");  
319 - builder.append(address);  
320 - builder.append(", address2=");  
321 - builder.append(address2);  
322 - builder.append(", zip=");  
323 - builder.append(zip);  
324 - builder.append(", phone=");  
325 - builder.append(phone);  
326 - builder.append(", email=");  
327 - builder.append(email);  
328 - builder.append(", additionalInfo=");  
329 - builder.append(additionalInfo);  
330 - builder.append("]");  
331 - return builder.toString();  
332 - }  
333 -  
334 - @Override  
335 public Customer toData() { 213 public Customer toData() {
336 Customer customer = new Customer(new CustomerId(id)); 214 Customer customer = new Customer(new CustomerId(id));
337 customer.setCreatedTime(UUIDs.unixTimestamp(id)); 215 customer.setCreatedTime(UUIDs.unixTimestamp(id));
@@ -19,8 +19,9 @@ import com.datastax.driver.core.utils.UUIDs; @@ -19,8 +19,9 @@ import com.datastax.driver.core.utils.UUIDs;
19 import com.datastax.driver.mapping.annotations.Column; 19 import com.datastax.driver.mapping.annotations.Column;
20 import com.datastax.driver.mapping.annotations.PartitionKey; 20 import com.datastax.driver.mapping.annotations.PartitionKey;
21 import com.datastax.driver.mapping.annotations.Table; 21 import com.datastax.driver.mapping.annotations.Table;
22 -import com.datastax.driver.mapping.annotations.Transient;  
23 import com.fasterxml.jackson.databind.JsonNode; 22 import com.fasterxml.jackson.databind.JsonNode;
  23 +import lombok.EqualsAndHashCode;
  24 +import lombok.ToString;
24 import org.thingsboard.server.common.data.Dashboard; 25 import org.thingsboard.server.common.data.Dashboard;
25 import org.thingsboard.server.common.data.id.CustomerId; 26 import org.thingsboard.server.common.data.id.CustomerId;
26 import org.thingsboard.server.common.data.id.DashboardId; 27 import org.thingsboard.server.common.data.id.DashboardId;
@@ -33,11 +34,10 @@ import java.util.UUID; @@ -33,11 +34,10 @@ import java.util.UUID;
33 import static org.thingsboard.server.dao.model.ModelConstants.*; 34 import static org.thingsboard.server.dao.model.ModelConstants.*;
34 35
35 @Table(name = DASHBOARD_COLUMN_FAMILY_NAME) 36 @Table(name = DASHBOARD_COLUMN_FAMILY_NAME)
  37 +@EqualsAndHashCode
  38 +@ToString
36 public final class DashboardEntity implements SearchTextEntity<Dashboard> { 39 public final class DashboardEntity implements SearchTextEntity<Dashboard> {
37 40
38 - @Transient  
39 - private static final long serialVersionUID = 2998395951247446191L;  
40 -  
41 @PartitionKey(value = 0) 41 @PartitionKey(value = 0)
42 @Column(name = ID_PROPERTY) 42 @Column(name = ID_PROPERTY)
43 private UUID id; 43 private UUID id;
@@ -119,7 +119,7 @@ public final class DashboardEntity implements SearchTextEntity<Dashboard> { @@ -119,7 +119,7 @@ public final class DashboardEntity implements SearchTextEntity<Dashboard> {
119 119
120 @Override 120 @Override
121 public String getSearchTextSource() { 121 public String getSearchTextSource() {
122 - return title; 122 + return getTitle();
123 } 123 }
124 124
125 @Override 125 @Override
@@ -132,80 +132,6 @@ public final class DashboardEntity implements SearchTextEntity<Dashboard> { @@ -132,80 +132,6 @@ public final class DashboardEntity implements SearchTextEntity<Dashboard> {
132 } 132 }
133 133
134 @Override 134 @Override
135 - public int hashCode() {  
136 - final int prime = 31;  
137 - int result = 1;  
138 - result = prime * result + ((configuration == null) ? 0 : configuration.hashCode());  
139 - result = prime * result + ((customerId == null) ? 0 : customerId.hashCode());  
140 - result = prime * result + ((id == null) ? 0 : id.hashCode());  
141 - result = prime * result + ((searchText == null) ? 0 : searchText.hashCode());  
142 - result = prime * result + ((tenantId == null) ? 0 : tenantId.hashCode());  
143 - result = prime * result + ((title == null) ? 0 : title.hashCode());  
144 - return result;  
145 - }  
146 -  
147 - @Override  
148 - public boolean equals(Object obj) {  
149 - if (this == obj)  
150 - return true;  
151 - if (obj == null)  
152 - return false;  
153 - if (getClass() != obj.getClass())  
154 - return false;  
155 - DashboardEntity other = (DashboardEntity) obj;  
156 - if (configuration == null) {  
157 - if (other.configuration != null)  
158 - return false;  
159 - } else if (!configuration.equals(other.configuration))  
160 - return false;  
161 - if (customerId == null) {  
162 - if (other.customerId != null)  
163 - return false;  
164 - } else if (!customerId.equals(other.customerId))  
165 - return false;  
166 - if (id == null) {  
167 - if (other.id != null)  
168 - return false;  
169 - } else if (!id.equals(other.id))  
170 - return false;  
171 - if (searchText == null) {  
172 - if (other.searchText != null)  
173 - return false;  
174 - } else if (!searchText.equals(other.searchText))  
175 - return false;  
176 - if (tenantId == null) {  
177 - if (other.tenantId != null)  
178 - return false;  
179 - } else if (!tenantId.equals(other.tenantId))  
180 - return false;  
181 - if (title == null) {  
182 - if (other.title != null)  
183 - return false;  
184 - } else if (!title.equals(other.title))  
185 - return false;  
186 - return true;  
187 - }  
188 -  
189 - @Override  
190 - public String toString() {  
191 - StringBuilder builder = new StringBuilder();  
192 - builder.append("DashboardEntity [id=");  
193 - builder.append(id);  
194 - builder.append(", tenantId=");  
195 - builder.append(tenantId);  
196 - builder.append(", customerId=");  
197 - builder.append(customerId);  
198 - builder.append(", title=");  
199 - builder.append(title);  
200 - builder.append(", searchText=");  
201 - builder.append(searchText);  
202 - builder.append(", configuration=");  
203 - builder.append(configuration);  
204 - builder.append("]");  
205 - return builder.toString();  
206 - }  
207 -  
208 - @Override  
209 public Dashboard toData() { 135 public Dashboard toData() {
210 Dashboard dashboard = new Dashboard(new DashboardId(id)); 136 Dashboard dashboard = new Dashboard(new DashboardId(id));
211 dashboard.setCreatedTime(UUIDs.unixTimestamp(id)); 137 dashboard.setCreatedTime(UUIDs.unixTimestamp(id));
@@ -19,7 +19,8 @@ import com.datastax.driver.core.utils.UUIDs; @@ -19,7 +19,8 @@ import com.datastax.driver.core.utils.UUIDs;
19 import com.datastax.driver.mapping.annotations.Column; 19 import com.datastax.driver.mapping.annotations.Column;
20 import com.datastax.driver.mapping.annotations.PartitionKey; 20 import com.datastax.driver.mapping.annotations.PartitionKey;
21 import com.datastax.driver.mapping.annotations.Table; 21 import com.datastax.driver.mapping.annotations.Table;
22 -import com.datastax.driver.mapping.annotations.Transient; 22 +import lombok.EqualsAndHashCode;
  23 +import lombok.ToString;
23 import org.thingsboard.server.common.data.DashboardInfo; 24 import org.thingsboard.server.common.data.DashboardInfo;
24 import org.thingsboard.server.common.data.id.CustomerId; 25 import org.thingsboard.server.common.data.id.CustomerId;
25 import org.thingsboard.server.common.data.id.DashboardId; 26 import org.thingsboard.server.common.data.id.DashboardId;
@@ -31,11 +32,10 @@ import java.util.UUID; @@ -31,11 +32,10 @@ import java.util.UUID;
31 import static org.thingsboard.server.dao.model.ModelConstants.*; 32 import static org.thingsboard.server.dao.model.ModelConstants.*;
32 33
33 @Table(name = DASHBOARD_COLUMN_FAMILY_NAME) 34 @Table(name = DASHBOARD_COLUMN_FAMILY_NAME)
  35 +@EqualsAndHashCode
  36 +@ToString
34 public class DashboardInfoEntity implements SearchTextEntity<DashboardInfo> { 37 public class DashboardInfoEntity implements SearchTextEntity<DashboardInfo> {
35 38
36 - @Transient  
37 - private static final long serialVersionUID = 2998395951247446191L;  
38 -  
39 @PartitionKey(value = 0) 39 @PartitionKey(value = 0)
40 @Column(name = ID_PROPERTY) 40 @Column(name = ID_PROPERTY)
41 private UUID id; 41 private UUID id;
@@ -105,7 +105,7 @@ public class DashboardInfoEntity implements SearchTextEntity<DashboardInfo> { @@ -105,7 +105,7 @@ public class DashboardInfoEntity implements SearchTextEntity<DashboardInfo> {
105 105
106 @Override 106 @Override
107 public String getSearchTextSource() { 107 public String getSearchTextSource() {
108 - return title; 108 + return getTitle();
109 } 109 }
110 110
111 @Override 111 @Override
@@ -118,72 +118,6 @@ public class DashboardInfoEntity implements SearchTextEntity<DashboardInfo> { @@ -118,72 +118,6 @@ public class DashboardInfoEntity implements SearchTextEntity<DashboardInfo> {
118 } 118 }
119 119
120 @Override 120 @Override
121 - public int hashCode() {  
122 - final int prime = 31;  
123 - int result = 1;  
124 - result = prime * result + ((customerId == null) ? 0 : customerId.hashCode());  
125 - result = prime * result + ((id == null) ? 0 : id.hashCode());  
126 - result = prime * result + ((searchText == null) ? 0 : searchText.hashCode());  
127 - result = prime * result + ((tenantId == null) ? 0 : tenantId.hashCode());  
128 - result = prime * result + ((title == null) ? 0 : title.hashCode());  
129 - return result;  
130 - }  
131 -  
132 - @Override  
133 - public boolean equals(Object obj) {  
134 - if (this == obj)  
135 - return true;  
136 - if (obj == null)  
137 - return false;  
138 - if (getClass() != obj.getClass())  
139 - return false;  
140 - DashboardInfoEntity other = (DashboardInfoEntity) obj;  
141 - if (customerId == null) {  
142 - if (other.customerId != null)  
143 - return false;  
144 - } else if (!customerId.equals(other.customerId))  
145 - return false;  
146 - if (id == null) {  
147 - if (other.id != null)  
148 - return false;  
149 - } else if (!id.equals(other.id))  
150 - return false;  
151 - if (searchText == null) {  
152 - if (other.searchText != null)  
153 - return false;  
154 - } else if (!searchText.equals(other.searchText))  
155 - return false;  
156 - if (tenantId == null) {  
157 - if (other.tenantId != null)  
158 - return false;  
159 - } else if (!tenantId.equals(other.tenantId))  
160 - return false;  
161 - if (title == null) {  
162 - if (other.title != null)  
163 - return false;  
164 - } else if (!title.equals(other.title))  
165 - return false;  
166 - return true;  
167 - }  
168 -  
169 - @Override  
170 - public String toString() {  
171 - StringBuilder builder = new StringBuilder();  
172 - builder.append("DashboardInfoEntity [id=");  
173 - builder.append(id);  
174 - builder.append(", tenantId=");  
175 - builder.append(tenantId);  
176 - builder.append(", customerId=");  
177 - builder.append(customerId);  
178 - builder.append(", title=");  
179 - builder.append(title);  
180 - builder.append(", searchText=");  
181 - builder.append(searchText);  
182 - builder.append("]");  
183 - return builder.toString();  
184 - }  
185 -  
186 - @Override  
187 public DashboardInfo toData() { 121 public DashboardInfo toData() {
188 DashboardInfo dashboardInfo = new DashboardInfo(new DashboardId(id)); 122 DashboardInfo dashboardInfo = new DashboardInfo(new DashboardId(id));
189 dashboardInfo.setCreatedTime(UUIDs.unixTimestamp(id)); 123 dashboardInfo.setCreatedTime(UUIDs.unixTimestamp(id));