Browse Source

Merge remote-tracking branch 'origin/master'

pull/326/head
Unknown 9 years ago
parent
commit
80e8b2efaf
  1. 14
      application/src/main/java/org/thingsboard/server/actors/app/AppActor.java
  2. 256
      application/src/main/java/org/thingsboard/server/actors/plugin/PluginProcessingContext.java
  3. 2
      application/src/main/java/org/thingsboard/server/actors/plugin/RuleToPluginMsgWrapper.java
  4. 9
      application/src/main/java/org/thingsboard/server/actors/rpc/BasicRpcSessionListener.java
  5. 2
      application/src/main/java/org/thingsboard/server/actors/rule/RuleActorMessageProcessor.java
  6. 3
      application/src/main/java/org/thingsboard/server/actors/service/ComponentActor.java
  7. 2
      application/src/main/java/org/thingsboard/server/actors/service/ContextBasedCreator.java
  8. 2
      application/src/main/java/org/thingsboard/server/actors/service/DefaultActorService.java
  9. 5
      application/src/main/java/org/thingsboard/server/actors/session/ASyncMsgProcessor.java
  10. 1
      application/src/main/java/org/thingsboard/server/actors/shared/plugin/TenantPluginManager.java
  11. 14
      application/src/main/java/org/thingsboard/server/actors/tenant/TenantActor.java
  12. 1
      application/src/main/java/org/thingsboard/server/config/MvcCorsProperties.java
  13. 2
      application/src/main/java/org/thingsboard/server/config/ThingsboardSecurityConfiguration.java
  14. 1
      application/src/main/java/org/thingsboard/server/config/WebSocketConfiguration.java
  15. 19
      application/src/main/java/org/thingsboard/server/controller/AlarmController.java
  16. 22
      application/src/main/java/org/thingsboard/server/controller/AssetController.java
  17. 19
      application/src/main/java/org/thingsboard/server/controller/AuthController.java
  18. 22
      application/src/main/java/org/thingsboard/server/controller/BaseController.java
  19. 21
      application/src/main/java/org/thingsboard/server/controller/CustomerController.java
  20. 26
      application/src/main/java/org/thingsboard/server/controller/DashboardController.java
  21. 26
      application/src/main/java/org/thingsboard/server/controller/DeviceController.java
  22. 126
      application/src/main/java/org/thingsboard/server/controller/EntityRelationController.java
  23. 18
      application/src/main/java/org/thingsboard/server/controller/PluginController.java
  24. 18
      application/src/main/java/org/thingsboard/server/controller/RuleController.java
  25. 27
      application/src/main/java/org/thingsboard/server/controller/UserController.java
  26. 10
      application/src/main/java/org/thingsboard/server/controller/plugin/PluginApiController.java
  27. 5
      application/src/main/java/org/thingsboard/server/install/ThingsboardInstallService.java
  28. 4
      application/src/main/java/org/thingsboard/server/service/cluster/discovery/DummyDiscoveryService.java
  29. 2
      application/src/main/java/org/thingsboard/server/service/cluster/discovery/ZkDiscoveryService.java
  30. 2
      application/src/main/java/org/thingsboard/server/service/cluster/rpc/ClusterGrpcService.java
  31. 60
      application/src/main/java/org/thingsboard/server/service/cluster/rpc/GrpcSession.java
  32. 139
      application/src/main/java/org/thingsboard/server/service/component/AnnotationComponentDiscoveryService.java
  33. 38
      application/src/main/java/org/thingsboard/server/service/install/CassandraDatabaseUpgradeService.java
  34. 187
      application/src/main/java/org/thingsboard/server/service/install/DefaultSystemDataLoaderService.java
  35. 3
      application/src/main/java/org/thingsboard/server/service/install/SqlDatabaseSchemaService.java
  36. 91
      application/src/main/java/org/thingsboard/server/service/install/cql/CQLStatementsParser.java
  37. 35
      application/src/main/java/org/thingsboard/server/service/mail/DefaultMailService.java
  38. 7
      application/src/main/java/org/thingsboard/server/service/security/auth/jwt/RefreshTokenProcessingFilter.java
  39. 2
      application/src/main/java/org/thingsboard/server/service/security/auth/jwt/extractor/JwtHeaderTokenExtractor.java
  40. 7
      application/src/main/java/org/thingsboard/server/service/security/auth/rest/RestLoginProcessingFilter.java
  41. 7
      application/src/main/java/org/thingsboard/server/service/security/auth/rest/RestPublicLoginProcessingFilter.java
  42. 2
      application/src/main/java/org/thingsboard/server/service/security/model/SecurityUser.java
  43. 4
      application/src/main/java/org/thingsboard/server/service/security/model/UserPrincipal.java
  44. 2
      application/src/main/java/org/thingsboard/server/service/security/model/token/AccessJwtToken.java
  45. 4
      application/src/main/java/org/thingsboard/server/service/security/model/token/JwtToken.java
  46. 7
      application/src/main/java/org/thingsboard/server/service/security/model/token/RawAccessJwtToken.java
  47. 75
      application/src/main/java/org/thingsboard/server/service/update/DefaultUpdateService.java
  48. 2
      common/data/src/main/java/org/thingsboard/server/common/data/AdminSettings.java
  49. 70
      common/data/src/main/java/org/thingsboard/server/common/data/ContactBased.java
  50. 4
      common/data/src/main/java/org/thingsboard/server/common/data/Customer.java
  51. 2
      common/data/src/main/java/org/thingsboard/server/common/data/Dashboard.java
  52. 2
      common/data/src/main/java/org/thingsboard/server/common/data/DashboardInfo.java
  53. 4
      common/data/src/main/java/org/thingsboard/server/common/data/DataConstants.java
  54. 55
      common/data/src/main/java/org/thingsboard/server/common/data/Device.java
  55. 2
      common/data/src/main/java/org/thingsboard/server/common/data/Event.java
  56. 43
      common/data/src/main/java/org/thingsboard/server/common/data/Tenant.java
  57. 64
      common/data/src/main/java/org/thingsboard/server/common/data/User.java
  58. 2
      common/data/src/main/java/org/thingsboard/server/common/data/alarm/Alarm.java
  59. 55
      common/data/src/main/java/org/thingsboard/server/common/data/asset/Asset.java
  60. 3
      common/data/src/main/java/org/thingsboard/server/common/data/id/EntityId.java
  61. 6
      common/data/src/main/java/org/thingsboard/server/common/data/page/PageDataIterable.java
  62. 2
      common/data/src/main/java/org/thingsboard/server/common/data/plugin/ComponentDescriptor.java
  63. 51
      common/data/src/main/java/org/thingsboard/server/common/data/plugin/PluginMetaData.java
  64. 10
      common/data/src/main/java/org/thingsboard/server/common/data/rule/RuleMetaData.java
  65. 42
      common/data/src/main/java/org/thingsboard/server/common/data/security/DeviceCredentials.java
  66. 48
      common/data/src/main/java/org/thingsboard/server/common/data/security/UserCredentials.java
  67. 31
      common/data/src/main/java/org/thingsboard/server/common/data/widget/WidgetType.java
  68. 2
      common/data/src/main/java/org/thingsboard/server/common/data/widget/WidgetsBundle.java
  69. 11
      common/transport/src/main/java/org/thingsboard/server/common/transport/adaptor/JsonConverter.java
  70. 38
      dao/src/main/java/org/thingsboard/server/dao/alarm/BaseAlarmService.java
  71. 68
      dao/src/main/java/org/thingsboard/server/dao/asset/BaseAssetService.java
  72. 15
      dao/src/main/java/org/thingsboard/server/dao/attributes/CassandraBaseAttributesDao.java
  73. 1
      dao/src/main/java/org/thingsboard/server/dao/cassandra/AbstractCassandraCluster.java
  74. 14
      dao/src/main/java/org/thingsboard/server/dao/component/CassandraBaseComponentDescriptorDao.java
  75. 9
      dao/src/main/java/org/thingsboard/server/dao/customer/CustomerServiceImpl.java
  76. 20
      dao/src/main/java/org/thingsboard/server/dao/dashboard/DashboardServiceImpl.java
  77. 53
      dao/src/main/java/org/thingsboard/server/dao/device/DeviceServiceImpl.java
  78. 7
      dao/src/main/java/org/thingsboard/server/dao/entity/AbstractEntityService.java
  79. 2
      dao/src/main/java/org/thingsboard/server/dao/model/BaseEntity.java
  80. 4
      dao/src/main/java/org/thingsboard/server/dao/model/EntitySubtypeEntity.java
  81. 29
      dao/src/main/java/org/thingsboard/server/dao/model/ModelConstants.java
  82. 58
      dao/src/main/java/org/thingsboard/server/dao/model/nosql/AdminSettingsEntity.java
  83. 7
      dao/src/main/java/org/thingsboard/server/dao/model/nosql/AlarmEntity.java
  84. 84
      dao/src/main/java/org/thingsboard/server/dao/model/nosql/AssetEntity.java
  85. 4
      dao/src/main/java/org/thingsboard/server/dao/model/nosql/ComponentDescriptorEntity.java
  86. 132
      dao/src/main/java/org/thingsboard/server/dao/model/nosql/CustomerEntity.java
  87. 84
      dao/src/main/java/org/thingsboard/server/dao/model/nosql/DashboardEntity.java
  88. 76
      dao/src/main/java/org/thingsboard/server/dao/model/nosql/DashboardInfoEntity.java
  89. 71
      dao/src/main/java/org/thingsboard/server/dao/model/nosql/DeviceCredentialsEntity.java
  90. 84
      dao/src/main/java/org/thingsboard/server/dao/model/nosql/DeviceEntity.java
  91. 3
      dao/src/main/java/org/thingsboard/server/dao/model/nosql/EventEntity.java
  92. 32
      dao/src/main/java/org/thingsboard/server/dao/model/nosql/PluginMetaDataEntity.java
  93. 41
      dao/src/main/java/org/thingsboard/server/dao/model/nosql/RuleMetaDataEntity.java
  94. 132
      dao/src/main/java/org/thingsboard/server/dao/model/nosql/TenantEntity.java
  95. 58
      dao/src/main/java/org/thingsboard/server/dao/model/nosql/UserCredentialsEntity.java
  96. 97
      dao/src/main/java/org/thingsboard/server/dao/model/nosql/UserEntity.java
  97. 47
      dao/src/main/java/org/thingsboard/server/dao/model/nosql/WidgetTypeEntity.java
  98. 50
      dao/src/main/java/org/thingsboard/server/dao/model/nosql/WidgetsBundleEntity.java
  99. 4
      dao/src/main/java/org/thingsboard/server/dao/model/sql/AdminSettingsEntity.java
  100. 3
      dao/src/main/java/org/thingsboard/server/dao/model/sql/AlarmEntity.java

14
application/src/main/java/org/thingsboard/server/actors/app/AppActor.java

@ -32,6 +32,8 @@ import org.thingsboard.server.actors.shared.rule.SystemRuleManager;
import org.thingsboard.server.actors.tenant.RuleChainDeviceMsg;
import org.thingsboard.server.actors.tenant.TenantActor;
import org.thingsboard.server.common.data.Tenant;
import org.thingsboard.server.common.data.id.PluginId;
import org.thingsboard.server.common.data.id.RuleId;
import org.thingsboard.server.common.data.id.TenantId;
import org.thingsboard.server.common.data.page.PageDataIterable;
import org.thingsboard.server.common.msg.cluster.ClusterEventMsg;
@ -149,14 +151,16 @@ public class AppActor extends ContextAwareActor {
private void onComponentLifecycleMsg(ComponentLifecycleMsg msg) {
ActorRef target = null;
if (SYSTEM_TENANT.equals(msg.getTenantId())) {
if (msg.getPluginId().isPresent()) {
target = pluginManager.getOrCreatePluginActor(this.context(), msg.getPluginId().get());
} else if (msg.getRuleId().isPresent()) {
Optional<ActorRef> ref = ruleManager.update(this.context(), msg.getRuleId().get(), msg.getEvent());
Optional<PluginId> pluginId = msg.getPluginId();
Optional<RuleId> ruleId = msg.getRuleId();
if (pluginId.isPresent()) {
target = pluginManager.getOrCreatePluginActor(this.context(), pluginId.get());
} else if (ruleId.isPresent()) {
Optional<ActorRef> ref = ruleManager.update(this.context(), ruleId.get(), msg.getEvent());
if (ref.isPresent()) {
target = ref.get();
} else {
logger.debug("Failed to find actor for rule: [{}]", msg.getRuleId());
logger.debug("Failed to find actor for rule: [{}]", ruleId);
return;
}
}

256
application/src/main/java/org/thingsboard/server/actors/plugin/PluginProcessingContext.java

@ -272,130 +272,150 @@ public final class PluginProcessingContext implements PluginContext {
private void validate(EntityId entityId, ValidationCallback callback) {
if (securityCtx.isPresent()) {
final PluginApiCallSecurityContext ctx = securityCtx.get();
if (ctx.isTenantAdmin() || ctx.isCustomerUser() || ctx.isSystemAdmin()) {
switch (entityId.getEntityType()) {
case DEVICE:
if (ctx.isSystemAdmin()) {
callback.onSuccess(this, Boolean.FALSE);
} else {
ListenableFuture<Device> deviceFuture = pluginCtx.deviceService.findDeviceByIdAsync(new DeviceId(entityId.getId()));
Futures.addCallback(deviceFuture, getCallback(callback, device -> {
if (device == null) {
return Boolean.FALSE;
} else {
if (!device.getTenantId().equals(ctx.getTenantId())) {
return Boolean.FALSE;
} else if (ctx.isCustomerUser() && !device.getCustomerId().equals(ctx.getCustomerId())) {
return Boolean.FALSE;
} else {
return Boolean.TRUE;
}
}
}));
}
return;
case ASSET:
if (ctx.isSystemAdmin()) {
callback.onSuccess(this, Boolean.FALSE);
} else {
ListenableFuture<Asset> assetFuture = pluginCtx.assetService.findAssetByIdAsync(new AssetId(entityId.getId()));
Futures.addCallback(assetFuture, getCallback(callback, asset -> {
if (asset == null) {
return Boolean.FALSE;
} else {
if (!asset.getTenantId().equals(ctx.getTenantId())) {
return Boolean.FALSE;
} else if (ctx.isCustomerUser() && !asset.getCustomerId().equals(ctx.getCustomerId())) {
return Boolean.FALSE;
} else {
return Boolean.TRUE;
}
}
}));
}
return;
case RULE:
if (ctx.isCustomerUser()) {
callback.onSuccess(this, Boolean.FALSE);
} else {
ListenableFuture<RuleMetaData> ruleFuture = pluginCtx.ruleService.findRuleByIdAsync(new RuleId(entityId.getId()));
Futures.addCallback(ruleFuture, getCallback(callback, rule -> {
if (rule == null) {
return Boolean.FALSE;
} else {
if (ctx.isTenantAdmin() && !rule.getTenantId().equals(ctx.getTenantId())) {
return Boolean.FALSE;
} else if (ctx.isSystemAdmin() && !rule.getTenantId().isNullUid()) {
return Boolean.FALSE;
} else {
return Boolean.TRUE;
}
}
}));
}
return;
case PLUGIN:
if (ctx.isCustomerUser()) {
callback.onSuccess(this, Boolean.FALSE);
} else {
ListenableFuture<PluginMetaData> pluginFuture = pluginCtx.pluginService.findPluginByIdAsync(new PluginId(entityId.getId()));
Futures.addCallback(pluginFuture, getCallback(callback, plugin -> {
if (plugin == null) {
return Boolean.FALSE;
} else {
if (ctx.isTenantAdmin() && !plugin.getTenantId().equals(ctx.getTenantId())) {
return Boolean.FALSE;
} else if (ctx.isSystemAdmin() && !plugin.getTenantId().isNullUid()) {
return Boolean.FALSE;
} else {
return Boolean.TRUE;
}
}
}));
}
return;
case CUSTOMER:
if (ctx.isSystemAdmin()) {
callback.onSuccess(this, Boolean.FALSE);
} else {
ListenableFuture<Customer> customerFuture = pluginCtx.customerService.findCustomerByIdAsync(new CustomerId(entityId.getId()));
Futures.addCallback(customerFuture, getCallback(callback, customer -> {
if (customer == null) {
return Boolean.FALSE;
} else {
if (!customer.getTenantId().equals(ctx.getTenantId())) {
return Boolean.FALSE;
} else if (ctx.isCustomerUser() && !customer.getId().equals(ctx.getCustomerId())) {
return Boolean.FALSE;
} else {
return Boolean.TRUE;
}
}
}));
}
return;
case TENANT:
if (ctx.isCustomerUser()) {
callback.onSuccess(this, Boolean.FALSE);
} else if (ctx.isSystemAdmin()) {
callback.onSuccess(this, Boolean.TRUE);
} else {
ListenableFuture<Tenant> tenantFuture = pluginCtx.tenantService.findTenantByIdAsync(new TenantId(entityId.getId()));
Futures.addCallback(tenantFuture, getCallback(callback, tenant -> tenant != null && tenant.getId().equals(ctx.getTenantId())));
}
return;
default:
//TODO: add support of other entities
throw new IllegalStateException("Not Implemented!");
}
} else {
callback.onSuccess(this, Boolean.FALSE);
switch (entityId.getEntityType()) {
case DEVICE:
validateDevice(ctx, entityId, callback);
return;
case ASSET:
validateAsset(ctx, entityId, callback);
return;
case RULE:
validateRule(ctx, entityId, callback);
return;
case PLUGIN:
validatePlugin(ctx, entityId, callback);
return;
case CUSTOMER:
validateCustomer(ctx, entityId, callback);
return;
case TENANT:
validateTenant(ctx, entityId, callback);
return;
default:
//TODO: add support of other entities
throw new IllegalStateException("Not Implemented!");
}
} else {
callback.onSuccess(this, Boolean.TRUE);
}
}
private void validateDevice(final PluginApiCallSecurityContext ctx, EntityId entityId, ValidationCallback callback) {
if (ctx.isSystemAdmin()) {
callback.onSuccess(this, Boolean.FALSE);
} else {
ListenableFuture<Device> deviceFuture = pluginCtx.deviceService.findDeviceByIdAsync(new DeviceId(entityId.getId()));
Futures.addCallback(deviceFuture, getCallback(callback, device -> {
if (device == null) {
return Boolean.FALSE;
} else {
if (!device.getTenantId().equals(ctx.getTenantId())) {
return Boolean.FALSE;
} else if (ctx.isCustomerUser() && !device.getCustomerId().equals(ctx.getCustomerId())) {
return Boolean.FALSE;
} else {
return Boolean.TRUE;
}
}
}));
}
}
private void validateAsset(final PluginApiCallSecurityContext ctx, EntityId entityId, ValidationCallback callback) {
if (ctx.isSystemAdmin()) {
callback.onSuccess(this, Boolean.FALSE);
} else {
ListenableFuture<Asset> assetFuture = pluginCtx.assetService.findAssetByIdAsync(new AssetId(entityId.getId()));
Futures.addCallback(assetFuture, getCallback(callback, asset -> {
if (asset == null) {
return Boolean.FALSE;
} else {
if (!asset.getTenantId().equals(ctx.getTenantId())) {
return Boolean.FALSE;
} else if (ctx.isCustomerUser() && !asset.getCustomerId().equals(ctx.getCustomerId())) {
return Boolean.FALSE;
} else {
return Boolean.TRUE;
}
}
}));
}
}
private void validateRule(final PluginApiCallSecurityContext ctx, EntityId entityId, ValidationCallback callback) {
if (ctx.isCustomerUser()) {
callback.onSuccess(this, Boolean.FALSE);
} else {
ListenableFuture<RuleMetaData> ruleFuture = pluginCtx.ruleService.findRuleByIdAsync(new RuleId(entityId.getId()));
Futures.addCallback(ruleFuture, getCallback(callback, rule -> {
if (rule == null) {
return Boolean.FALSE;
} else {
if (ctx.isTenantAdmin() && !rule.getTenantId().equals(ctx.getTenantId())) {
return Boolean.FALSE;
} else if (ctx.isSystemAdmin() && !rule.getTenantId().isNullUid()) {
return Boolean.FALSE;
} else {
return Boolean.TRUE;
}
}
}));
}
}
private void validatePlugin(final PluginApiCallSecurityContext ctx, EntityId entityId, ValidationCallback callback) {
if (ctx.isCustomerUser()) {
callback.onSuccess(this, Boolean.FALSE);
} else {
ListenableFuture<PluginMetaData> pluginFuture = pluginCtx.pluginService.findPluginByIdAsync(new PluginId(entityId.getId()));
Futures.addCallback(pluginFuture, getCallback(callback, plugin -> {
if (plugin == null) {
return Boolean.FALSE;
} else {
if (ctx.isTenantAdmin() && !plugin.getTenantId().equals(ctx.getTenantId())) {
return Boolean.FALSE;
} else if (ctx.isSystemAdmin() && !plugin.getTenantId().isNullUid()) {
return Boolean.FALSE;
} else {
return Boolean.TRUE;
}
}
}));
}
}
private void validateCustomer(final PluginApiCallSecurityContext ctx, EntityId entityId, ValidationCallback callback) {
if (ctx.isSystemAdmin()) {
callback.onSuccess(this, Boolean.FALSE);
} else {
ListenableFuture<Customer> customerFuture = pluginCtx.customerService.findCustomerByIdAsync(new CustomerId(entityId.getId()));
Futures.addCallback(customerFuture, getCallback(callback, customer -> {
if (customer == null) {
return Boolean.FALSE;
} else {
if (!customer.getTenantId().equals(ctx.getTenantId())) {
return Boolean.FALSE;
} else if (ctx.isCustomerUser() && !customer.getId().equals(ctx.getCustomerId())) {
return Boolean.FALSE;
} else {
return Boolean.TRUE;
}
}
}));
}
}
private void validateTenant(final PluginApiCallSecurityContext ctx, EntityId entityId, ValidationCallback callback) {
if (ctx.isCustomerUser()) {
callback.onSuccess(this, Boolean.FALSE);
} else if (ctx.isSystemAdmin()) {
callback.onSuccess(this, Boolean.TRUE);
} else {
ListenableFuture<Tenant> tenantFuture = pluginCtx.tenantService.findTenantByIdAsync(new TenantId(entityId.getId()));
Futures.addCallback(tenantFuture, getCallback(callback, tenant -> tenant != null && tenant.getId().equals(ctx.getTenantId())));
}
}
@Override
public ListenableFuture<List<EntityRelation>> findByFromAndType(EntityId from, String relationType) {
return this.pluginCtx.relationService.findByFromAndType(from, relationType, RelationTypeGroup.COMMON);

2
application/src/main/java/org/thingsboard/server/actors/plugin/RuleToPluginMsgWrapper.java

@ -59,7 +59,7 @@ public class RuleToPluginMsgWrapper implements ToPluginActorMsg, RuleAwareMsg {
}
public RuleToPluginMsg<?> getMsg() {
public RuleToPluginMsg getMsg() {
return msg;
}

9
application/src/main/java/org/thingsboard/server/actors/rpc/BasicRpcSessionListener.java

@ -45,6 +45,7 @@ import java.util.UUID;
@Slf4j
public class BasicRpcSessionListener implements GrpcSessionListener {
public static final String SESSION_RECEIVED_SESSION_ACTOR_MSG = "{} session [{}] received session actor msg {}";
private final ActorSystemContext context;
private final ActorService service;
private final ActorRef manager;
@ -93,25 +94,25 @@ public class BasicRpcSessionListener implements GrpcSessionListener {
@Override
public void onToDeviceSessionActorRpcMsg(GrpcSession session, ClusterAPIProtos.ToDeviceSessionActorRpcMessage msg) {
log.trace("{} session [{}] received session actor msg {}", getType(session), session.getRemoteServer(), msg);
log.trace(SESSION_RECEIVED_SESSION_ACTOR_MSG, getType(session), session.getRemoteServer(), msg);
service.onMsg((ToDeviceSessionActorMsg) deserialize(msg.getData().toByteArray()));
}
@Override
public void onToDeviceRpcRequestRpcMsg(GrpcSession session, ClusterAPIProtos.ToDeviceRpcRequestRpcMessage msg) {
log.trace("{} session [{}] received session actor msg {}", getType(session), session.getRemoteServer(), msg);
log.trace(SESSION_RECEIVED_SESSION_ACTOR_MSG, getType(session), session.getRemoteServer(), msg);
service.onMsg(deserialize(session.getRemoteServer(), msg));
}
@Override
public void onFromDeviceRpcResponseRpcMsg(GrpcSession session, ClusterAPIProtos.ToPluginRpcResponseRpcMessage msg) {
log.trace("{} session [{}] received session actor msg {}", getType(session), session.getRemoteServer(), msg);
log.trace(SESSION_RECEIVED_SESSION_ACTOR_MSG, getType(session), session.getRemoteServer(), msg);
service.onMsg(deserialize(session.getRemoteServer(), msg));
}
@Override
public void onToAllNodesRpcMessage(GrpcSession session, ClusterAPIProtos.ToAllNodesRpcMessage msg) {
log.trace("{} session [{}] received session actor msg {}", getType(session), session.getRemoteServer(), msg);
log.trace(SESSION_RECEIVED_SESSION_ACTOR_MSG, getType(session), session.getRemoteServer(), msg);
service.onMsg((ToAllNodesMsg) deserialize(msg.getData().toByteArray()));
}

2
application/src/main/java/org/thingsboard/server/actors/rule/RuleActorMessageProcessor.java

@ -322,7 +322,7 @@ class RuleActorMessageProcessor extends ComponentMsgProcessor<RuleId> {
@Override
public void onClusterEventMsg(ClusterEventMsg msg) throws Exception {
//Do nothing
}
private void stopAction() {

3
application/src/main/java/org/thingsboard/server/actors/service/ComponentActor.java

@ -104,6 +104,9 @@ public abstract class ComponentActor<T extends EntityId, P extends ComponentMsgP
break;
case DELETED:
processor.onStop(context());
break;
default:
break;
}
logLifecycleEvent(msg.getEvent());
} catch (Exception e) {

2
application/src/main/java/org/thingsboard/server/actors/service/ContextBasedCreator.java

@ -23,7 +23,7 @@ public abstract class ContextBasedCreator<T> implements Creator<T> {
private static final long serialVersionUID = 1L;
protected final ActorSystemContext context;
protected final transient ActorSystemContext context;
public ContextBasedCreator(ActorSystemContext context) {
super();

2
application/src/main/java/org/thingsboard/server/actors/service/DefaultActorService.java

@ -202,7 +202,7 @@ public class DefaultActorService implements ActorService {
@Override
public void onServerUpdated(ServerInstance server) {
//Do nothing
}
@Override

5
application/src/main/java/org/thingsboard/server/actors/session/ASyncMsgProcessor.java

@ -77,6 +77,8 @@ class ASyncMsgProcessor extends AbstractSessionActorMsgProcessor {
case UNSUBSCRIBE_RPC_COMMANDS_REQUEST:
subscribedToRpcCommands = false;
break;
default:
break;
}
currentTargetServer = forwardToAppActor(ctx, pendingMsg);
}
@ -94,6 +96,8 @@ class ASyncMsgProcessor extends AbstractSessionActorMsgProcessor {
pendingMap.remove(responseMsg.getRequestId());
}
break;
default:
break;
}
sessionCtx.onMsg(new BasicSessionActorToAdaptorMsg(this.sessionCtx, msg));
} else {
@ -109,6 +113,7 @@ class ASyncMsgProcessor extends AbstractSessionActorMsgProcessor {
// TODO Auto-generated method stub
}
@Override
protected void cleanupSession(ActorContext ctx) {
toDeviceMsg(new SessionCloseMsg()).ifPresent(m -> forwardToAppActor(ctx, m));
}

1
application/src/main/java/org/thingsboard/server/actors/shared/plugin/TenantPluginManager.java

@ -31,6 +31,7 @@ public class TenantPluginManager extends PluginManager {
this.tenantId = tenantId;
}
@Override
public void init(ActorContext context) {
if (systemContext.isTenantComponentsInitEnabled()) {
super.init(context);

14
application/src/main/java/org/thingsboard/server/actors/tenant/TenantActor.java

@ -32,6 +32,8 @@ import org.thingsboard.server.actors.shared.plugin.TenantPluginManager;
import org.thingsboard.server.actors.shared.rule.RuleManager;
import org.thingsboard.server.actors.shared.rule.TenantRuleManager;
import org.thingsboard.server.common.data.id.DeviceId;
import org.thingsboard.server.common.data.id.PluginId;
import org.thingsboard.server.common.data.id.RuleId;
import org.thingsboard.server.common.data.id.TenantId;
import org.thingsboard.server.common.msg.cluster.ClusterEventMsg;
import org.thingsboard.server.common.msg.device.ToDeviceActorMsg;
@ -126,16 +128,18 @@ public class TenantActor extends ContextAwareActor {
}
private void onComponentLifecycleMsg(ComponentLifecycleMsg msg) {
if (msg.getPluginId().isPresent()) {
ActorRef pluginActor = pluginManager.getOrCreatePluginActor(this.context(), msg.getPluginId().get());
Optional<PluginId> pluginId = msg.getPluginId();
Optional<RuleId> ruleId = msg.getRuleId();
if (pluginId.isPresent()) {
ActorRef pluginActor = pluginManager.getOrCreatePluginActor(this.context(), pluginId.get());
pluginActor.tell(msg, ActorRef.noSender());
} else if (msg.getRuleId().isPresent()) {
} else if (ruleId.isPresent()) {
ActorRef target;
Optional<ActorRef> ref = ruleManager.update(this.context(), msg.getRuleId().get(), msg.getEvent());
Optional<ActorRef> ref = ruleManager.update(this.context(), ruleId.get(), msg.getEvent());
if (ref.isPresent()) {
target = ref.get();
} else {
logger.debug("Failed to find actor for rule: [{}]", msg.getRuleId());
logger.debug("Failed to find actor for rule: [{}]", ruleId);
return;
}
target.tell(msg, ActorRef.noSender());

1
application/src/main/java/org/thingsboard/server/config/MvcCorsProperties.java

@ -33,6 +33,7 @@ public class MvcCorsProperties {
private Map<String, CorsConfiguration> mappings = new HashMap<>();
public MvcCorsProperties() {
super();
}
public Map<String, CorsConfiguration> getMappings() {

2
application/src/main/java/org/thingsboard/server/config/ThingsboardSecurityConfiguration.java

@ -64,7 +64,7 @@ public class ThingsboardSecurityConfiguration extends WebSecurityConfigurerAdapt
public static final String FORM_BASED_LOGIN_ENTRY_POINT = "/api/auth/login";
public static final String PUBLIC_LOGIN_ENTRY_POINT = "/api/auth/login/public";
public static final String TOKEN_REFRESH_ENTRY_POINT = "/api/auth/token";
public static final String[] NON_TOKEN_BASED_AUTH_ENTRY_POINTS = new String[] {"/index.html", "/static/**", "/api/noauth/**", "/webjars/**"};
protected static final String[] NON_TOKEN_BASED_AUTH_ENTRY_POINTS = new String[] {"/index.html", "/static/**", "/api/noauth/**", "/webjars/**"};
public static final String TOKEN_BASED_AUTH_ENTRY_POINT = "/api/**";
public static final String WS_TOKEN_BASED_AUTH_ENTRY_POINT = "/api/ws/**";

1
application/src/main/java/org/thingsboard/server/config/WebSocketConfiguration.java

@ -76,6 +76,7 @@ public class WebSocketConfiguration implements WebSocketConfigurer {
@Override
public void afterHandshake(ServerHttpRequest request, ServerHttpResponse response, WebSocketHandler wsHandler,
Exception exception) {
//Do nothing
}
});
}

19
application/src/main/java/org/thingsboard/server/controller/AlarmController.java

@ -30,13 +30,16 @@ import org.thingsboard.server.exception.ThingsboardException;
@RequestMapping("/api")
public class AlarmController extends BaseController {
public static final String ALARM_ID = "alarmId";
@PreAuthorize("hasAnyAuthority('SYS_ADMIN', 'TENANT_ADMIN', 'CUSTOMER_USER')")
@RequestMapping(value = "/alarm/{alarmId}", method = RequestMethod.GET)
@ResponseBody
public Alarm getAlarmById(@PathVariable("alarmId") String strAlarmId) throws ThingsboardException {
checkParameter("alarmId", strAlarmId);
public Alarm getAlarmById(@PathVariable(ALARM_ID) String strAlarmId) throws ThingsboardException {
checkParameter(ALARM_ID, strAlarmId);
try {
AlarmId alarmId = new AlarmId(toUUID(strAlarmId));
return checkAlarmId(alarmId);
} catch (Exception e) {
throw handleException(e);
@ -46,8 +49,8 @@ public class AlarmController extends BaseController {
@PreAuthorize("hasAnyAuthority('SYS_ADMIN', 'TENANT_ADMIN', 'CUSTOMER_USER')")
@RequestMapping(value = "/alarm/info/{alarmId}", method = RequestMethod.GET)
@ResponseBody
public AlarmInfo getAlarmInfoById(@PathVariable("alarmId") String strAlarmId) throws ThingsboardException {
checkParameter("alarmId", strAlarmId);
public AlarmInfo getAlarmInfoById(@PathVariable(ALARM_ID) String strAlarmId) throws ThingsboardException {
checkParameter(ALARM_ID, strAlarmId);
try {
AlarmId alarmId = new AlarmId(toUUID(strAlarmId));
return checkAlarmInfoId(alarmId);
@ -71,8 +74,8 @@ public class AlarmController extends BaseController {
@PreAuthorize("hasAnyAuthority('SYS_ADMIN', 'TENANT_ADMIN', 'CUSTOMER_USER')")
@RequestMapping(value = "/alarm/{alarmId}/ack", method = RequestMethod.POST)
@ResponseStatus(value = HttpStatus.OK)
public void ackAlarm(@PathVariable("alarmId") String strAlarmId) throws ThingsboardException {
checkParameter("alarmId", strAlarmId);
public void ackAlarm(@PathVariable(ALARM_ID) String strAlarmId) throws ThingsboardException {
checkParameter(ALARM_ID, strAlarmId);
try {
AlarmId alarmId = new AlarmId(toUUID(strAlarmId));
checkAlarmId(alarmId);
@ -85,8 +88,8 @@ public class AlarmController extends BaseController {
@PreAuthorize("hasAnyAuthority('SYS_ADMIN', 'TENANT_ADMIN', 'CUSTOMER_USER')")
@RequestMapping(value = "/alarm/{alarmId}/clear", method = RequestMethod.POST)
@ResponseStatus(value = HttpStatus.OK)
public void clearAlarm(@PathVariable("alarmId") String strAlarmId) throws ThingsboardException {
checkParameter("alarmId", strAlarmId);
public void clearAlarm(@PathVariable(ALARM_ID) String strAlarmId) throws ThingsboardException {
checkParameter(ALARM_ID, strAlarmId);
try {
AlarmId alarmId = new AlarmId(toUUID(strAlarmId));
checkAlarmId(alarmId);

22
application/src/main/java/org/thingsboard/server/controller/AssetController.java

@ -43,11 +43,13 @@ import java.util.stream.Collectors;
@RequestMapping("/api")
public class AssetController extends BaseController {
public static final String ASSET_ID = "assetId";
@PreAuthorize("hasAnyAuthority('TENANT_ADMIN', 'CUSTOMER_USER')")
@RequestMapping(value = "/asset/{assetId}", method = RequestMethod.GET)
@ResponseBody
public Asset getAssetById(@PathVariable("assetId") String strAssetId) throws ThingsboardException {
checkParameter("assetId", strAssetId);
public Asset getAssetById(@PathVariable(ASSET_ID) String strAssetId) throws ThingsboardException {
checkParameter(ASSET_ID, strAssetId);
try {
AssetId assetId = new AssetId(toUUID(strAssetId));
return checkAssetId(assetId);
@ -80,8 +82,8 @@ public class AssetController extends BaseController {
@PreAuthorize("hasAuthority('TENANT_ADMIN')")
@RequestMapping(value = "/asset/{assetId}", method = RequestMethod.DELETE)
@ResponseStatus(value = HttpStatus.OK)
public void deleteAsset(@PathVariable("assetId") String strAssetId) throws ThingsboardException {
checkParameter("assetId", strAssetId);
public void deleteAsset(@PathVariable(ASSET_ID) String strAssetId) throws ThingsboardException {
checkParameter(ASSET_ID, strAssetId);
try {
AssetId assetId = new AssetId(toUUID(strAssetId));
checkAssetId(assetId);
@ -95,9 +97,9 @@ public class AssetController extends BaseController {
@RequestMapping(value = "/customer/{customerId}/asset/{assetId}", method = RequestMethod.POST)
@ResponseBody
public Asset assignAssetToCustomer(@PathVariable("customerId") String strCustomerId,
@PathVariable("assetId") String strAssetId) throws ThingsboardException {
@PathVariable(ASSET_ID) String strAssetId) throws ThingsboardException {
checkParameter("customerId", strCustomerId);
checkParameter("assetId", strAssetId);
checkParameter(ASSET_ID, strAssetId);
try {
CustomerId customerId = new CustomerId(toUUID(strCustomerId));
checkCustomerId(customerId);
@ -114,8 +116,8 @@ public class AssetController extends BaseController {
@PreAuthorize("hasAuthority('TENANT_ADMIN')")
@RequestMapping(value = "/customer/asset/{assetId}", method = RequestMethod.DELETE)
@ResponseBody
public Asset unassignAssetFromCustomer(@PathVariable("assetId") String strAssetId) throws ThingsboardException {
checkParameter("assetId", strAssetId);
public Asset unassignAssetFromCustomer(@PathVariable(ASSET_ID) String strAssetId) throws ThingsboardException {
checkParameter(ASSET_ID, strAssetId);
try {
AssetId assetId = new AssetId(toUUID(strAssetId));
Asset asset = checkAssetId(assetId);
@ -131,8 +133,8 @@ public class AssetController extends BaseController {
@PreAuthorize("hasAuthority('TENANT_ADMIN')")
@RequestMapping(value = "/customer/public/asset/{assetId}", method = RequestMethod.POST)
@ResponseBody
public Asset assignAssetToPublicCustomer(@PathVariable("assetId") String strAssetId) throws ThingsboardException {
checkParameter("assetId", strAssetId);
public Asset assignAssetToPublicCustomer(@PathVariable(ASSET_ID) String strAssetId) throws ThingsboardException {
checkParameter(ASSET_ID, strAssetId);
try {
AssetId assetId = new AssetId(toUUID(strAssetId));
Asset asset = checkAssetId(assetId);

19
application/src/main/java/org/thingsboard/server/controller/AuthController.java

@ -60,9 +60,6 @@ public class AuthController extends BaseController {
@Autowired
private RefreshTokenRepository refreshTokenRepository;
@Autowired
private UserService userService;
@Autowired
private MailService mailService;
@ -103,13 +100,13 @@ public class AuthController extends BaseController {
HttpStatus responseStatus;
UserCredentials userCredentials = userService.findUserCredentialsByActivateToken(activateToken);
if (userCredentials != null) {
String createPasswordURI = "/login/createPassword";
String createURI = "/login/createPassword";
try {
URI location = new URI(createPasswordURI + "?activateToken=" + activateToken);
URI location = new URI(createURI + "?activateToken=" + activateToken);
headers.setLocation(location);
responseStatus = HttpStatus.SEE_OTHER;
} catch (URISyntaxException e) {
log.error("Unable to create URI with address [{}]", createPasswordURI);
log.error("Unable to create URI with address [{}]", createURI);
responseStatus = HttpStatus.BAD_REQUEST;
}
} else {
@ -126,10 +123,10 @@ public class AuthController extends BaseController {
try {
UserCredentials userCredentials = userService.requestPasswordReset(email);
String baseUrl = constructBaseUrl(request);
String resetPasswordUrl = String.format("%s/api/noauth/resetPassword?resetToken=%s", baseUrl,
String resetUrl = String.format("%s/api/noauth/resetPassword?resetToken=%s", baseUrl,
userCredentials.getResetToken());
mailService.sendResetPasswordEmail(resetPasswordUrl, email);
mailService.sendResetPasswordEmail(resetUrl, email);
} catch (Exception e) {
throw handleException(e);
}
@ -140,15 +137,15 @@ public class AuthController extends BaseController {
@RequestParam(value = "resetToken") String resetToken) {
HttpHeaders headers = new HttpHeaders();
HttpStatus responseStatus;
String resetPasswordURI = "/login/resetPassword";
String resetURI = "/login/resetPassword";
UserCredentials userCredentials = userService.findUserCredentialsByResetToken(resetToken);
if (userCredentials != null) {
try {
URI location = new URI(resetPasswordURI + "?resetToken=" + resetToken);
URI location = new URI(resetURI + "?resetToken=" + resetToken);
headers.setLocation(location);
responseStatus = HttpStatus.SEE_OTHER;
} catch (URISyntaxException e) {
log.error("Unable to create URI with address [{}]", resetPasswordURI);
log.error("Unable to create URI with address [{}]", resetURI);
responseStatus = HttpStatus.BAD_REQUEST;
}
} else {

22
application/src/main/java/org/thingsboard/server/controller/BaseController.java

@ -70,6 +70,8 @@ import static org.thingsboard.server.dao.service.Validator.validateId;
@Slf4j
public abstract class BaseController {
public static final String INCORRECT_TENANT_ID = "Incorrect tenantId ";
public static final String YOU_DON_T_HAVE_PERMISSION_TO_PERFORM_THIS_OPERATION = "You don't have permission to perform this operation!";
@Autowired
private ThingsboardErrorResponseHandler errorResponseHandler;
@ -209,11 +211,11 @@ public abstract class BaseController {
}
void checkTenantId(TenantId tenantId) throws ThingsboardException {
validateId(tenantId, "Incorrect tenantId " + tenantId);
validateId(tenantId, INCORRECT_TENANT_ID + tenantId);
SecurityUser authUser = getCurrentUser();
if (authUser.getAuthority() != Authority.SYS_ADMIN &&
(authUser.getTenantId() == null || !authUser.getTenantId().equals(tenantId))) {
throw new ThingsboardException("You don't have permission to perform this operation!",
throw new ThingsboardException(YOU_DON_T_HAVE_PERMISSION_TO_PERFORM_THIS_OPERATION,
ThingsboardErrorCode.PERMISSION_DENIED);
}
}
@ -229,7 +231,7 @@ public abstract class BaseController {
if (authUser.getAuthority() == Authority.SYS_ADMIN ||
(authUser.getAuthority() != Authority.TENANT_ADMIN &&
(authUser.getCustomerId() == null || !authUser.getCustomerId().equals(customerId)))) {
throw new ThingsboardException("You don't have permission to perform this operation!",
throw new ThingsboardException(YOU_DON_T_HAVE_PERMISSION_TO_PERFORM_THIS_OPERATION,
ThingsboardErrorCode.PERMISSION_DENIED);
}
Customer customer = customerService.findCustomerById(customerId);
@ -382,7 +384,7 @@ public abstract class BaseController {
if (widgetsBundle.getTenantId() != null && !widgetsBundle.getTenantId().getId().equals(ModelConstants.NULL_UUID)) {
checkTenantId(widgetsBundle.getTenantId());
} else if (modify && getCurrentUser().getAuthority() != Authority.SYS_ADMIN) {
throw new ThingsboardException("You don't have permission to perform this operation!",
throw new ThingsboardException(YOU_DON_T_HAVE_PERMISSION_TO_PERFORM_THIS_OPERATION,
ThingsboardErrorCode.PERMISSION_DENIED);
}
}
@ -403,7 +405,7 @@ public abstract class BaseController {
if (widgetType.getTenantId() != null && !widgetType.getTenantId().getId().equals(ModelConstants.NULL_UUID)) {
checkTenantId(widgetType.getTenantId());
} else if (modify && getCurrentUser().getAuthority() != Authority.SYS_ADMIN) {
throw new ThingsboardException("You don't have permission to perform this operation!",
throw new ThingsboardException(YOU_DON_T_HAVE_PERMISSION_TO_PERFORM_THIS_OPERATION,
ThingsboardErrorCode.PERMISSION_DENIED);
}
}
@ -437,7 +439,7 @@ public abstract class BaseController {
SecurityUser authUser = getCurrentUser();
if (authUser.getAuthority() == Authority.CUSTOMER_USER) {
if (dashboard.getCustomerId() == null || dashboard.getCustomerId().getId().equals(ModelConstants.NULL_UUID)) {
throw new ThingsboardException("You don't have permission to perform this operation!",
throw new ThingsboardException(YOU_DON_T_HAVE_PERMISSION_TO_PERFORM_THIS_OPERATION,
ThingsboardErrorCode.PERMISSION_DENIED);
}
}
@ -480,11 +482,11 @@ public abstract class BaseController {
checkNotNull(plugin);
SecurityUser authUser = getCurrentUser();
TenantId tenantId = plugin.getTenantId();
validateId(tenantId, "Incorrect tenantId " + tenantId);
validateId(tenantId, INCORRECT_TENANT_ID + tenantId);
if (authUser.getAuthority() != Authority.SYS_ADMIN) {
if (authUser.getTenantId() == null ||
!tenantId.getId().equals(ModelConstants.NULL_UUID) && !authUser.getTenantId().equals(tenantId)) {
throw new ThingsboardException("You don't have permission to perform this operation!",
throw new ThingsboardException(YOU_DON_T_HAVE_PERMISSION_TO_PERFORM_THIS_OPERATION,
ThingsboardErrorCode.PERMISSION_DENIED);
} else if (tenantId.getId().equals(ModelConstants.NULL_UUID)) {
@ -508,11 +510,11 @@ public abstract class BaseController {
checkNotNull(rule);
SecurityUser authUser = getCurrentUser();
TenantId tenantId = rule.getTenantId();
validateId(tenantId, "Incorrect tenantId " + tenantId);
validateId(tenantId, INCORRECT_TENANT_ID + tenantId);
if (authUser.getAuthority() != Authority.SYS_ADMIN) {
if (authUser.getTenantId() == null ||
!tenantId.getId().equals(ModelConstants.NULL_UUID) && !authUser.getTenantId().equals(tenantId)) {
throw new ThingsboardException("You don't have permission to perform this operation!",
throw new ThingsboardException(YOU_DON_T_HAVE_PERMISSION_TO_PERFORM_THIS_OPERATION,
ThingsboardErrorCode.PERMISSION_DENIED);
}

21
application/src/main/java/org/thingsboard/server/controller/CustomerController.java

@ -32,11 +32,14 @@ import org.thingsboard.server.exception.ThingsboardException;
@RequestMapping("/api")
public class CustomerController extends BaseController {
public static final String CUSTOMER_ID = "customerId";
public static final String IS_PUBLIC = "isPublic";
@PreAuthorize("hasAnyAuthority('TENANT_ADMIN', 'CUSTOMER_USER')")
@RequestMapping(value = "/customer/{customerId}", method = RequestMethod.GET)
@ResponseBody
public Customer getCustomerById(@PathVariable("customerId") String strCustomerId) throws ThingsboardException {
checkParameter("customerId", strCustomerId);
public Customer getCustomerById(@PathVariable(CUSTOMER_ID) String strCustomerId) throws ThingsboardException {
checkParameter(CUSTOMER_ID, strCustomerId);
try {
CustomerId customerId = new CustomerId(toUUID(strCustomerId));
return checkCustomerId(customerId);
@ -48,15 +51,15 @@ public class CustomerController extends BaseController {
@PreAuthorize("hasAnyAuthority('TENANT_ADMIN', 'CUSTOMER_USER')")
@RequestMapping(value = "/customer/{customerId}/shortInfo", method = RequestMethod.GET)
@ResponseBody
public JsonNode getShortCustomerInfoById(@PathVariable("customerId") String strCustomerId) throws ThingsboardException {
checkParameter("customerId", strCustomerId);
public JsonNode getShortCustomerInfoById(@PathVariable(CUSTOMER_ID) String strCustomerId) throws ThingsboardException {
checkParameter(CUSTOMER_ID, strCustomerId);
try {
CustomerId customerId = new CustomerId(toUUID(strCustomerId));
Customer customer = checkCustomerId(customerId);
ObjectMapper objectMapper = new ObjectMapper();
ObjectNode infoObject = objectMapper.createObjectNode();
infoObject.put("title", customer.getTitle());
infoObject.put("isPublic", customer.isPublic());
infoObject.put(IS_PUBLIC, customer.isPublic());
return infoObject;
} catch (Exception e) {
throw handleException(e);
@ -66,8 +69,8 @@ public class CustomerController extends BaseController {
@PreAuthorize("hasAnyAuthority('TENANT_ADMIN', 'CUSTOMER_USER')")
@RequestMapping(value = "/customer/{customerId}/title", method = RequestMethod.GET, produces = "application/text")
@ResponseBody
public String getCustomerTitleById(@PathVariable("customerId") String strCustomerId) throws ThingsboardException {
checkParameter("customerId", strCustomerId);
public String getCustomerTitleById(@PathVariable(CUSTOMER_ID) String strCustomerId) throws ThingsboardException {
checkParameter(CUSTOMER_ID, strCustomerId);
try {
CustomerId customerId = new CustomerId(toUUID(strCustomerId));
Customer customer = checkCustomerId(customerId);
@ -92,8 +95,8 @@ public class CustomerController extends BaseController {
@PreAuthorize("hasAuthority('TENANT_ADMIN')")
@RequestMapping(value = "/customer/{customerId}", method = RequestMethod.DELETE)
@ResponseStatus(value = HttpStatus.OK)
public void deleteCustomer(@PathVariable("customerId") String strCustomerId) throws ThingsboardException {
checkParameter("customerId", strCustomerId);
public void deleteCustomer(@PathVariable(CUSTOMER_ID) String strCustomerId) throws ThingsboardException {
checkParameter(CUSTOMER_ID, strCustomerId);
try {
CustomerId customerId = new CustomerId(toUUID(strCustomerId));
checkCustomerId(customerId);

26
application/src/main/java/org/thingsboard/server/controller/DashboardController.java

@ -34,6 +34,8 @@ import org.thingsboard.server.exception.ThingsboardException;
@RequestMapping("/api")
public class DashboardController extends BaseController {
public static final String DASHBOARD_ID = "dashboardId";
@PreAuthorize("hasAnyAuthority('SYS_ADMIN', 'TENANT_ADMIN', 'CUSTOMER_USER')")
@RequestMapping(value = "/dashboard/serverTime", method = RequestMethod.GET)
@ResponseBody
@ -44,8 +46,8 @@ public class DashboardController extends BaseController {
@PreAuthorize("hasAnyAuthority('SYS_ADMIN', 'TENANT_ADMIN', 'CUSTOMER_USER')")
@RequestMapping(value = "/dashboard/info/{dashboardId}", method = RequestMethod.GET)
@ResponseBody
public DashboardInfo getDashboardInfoById(@PathVariable("dashboardId") String strDashboardId) throws ThingsboardException {
checkParameter("dashboardId", strDashboardId);
public DashboardInfo getDashboardInfoById(@PathVariable(DASHBOARD_ID) String strDashboardId) throws ThingsboardException {
checkParameter(DASHBOARD_ID, strDashboardId);
try {
DashboardId dashboardId = new DashboardId(toUUID(strDashboardId));
return checkDashboardInfoId(dashboardId);
@ -57,8 +59,8 @@ public class DashboardController extends BaseController {
@PreAuthorize("hasAnyAuthority('TENANT_ADMIN', 'CUSTOMER_USER')")
@RequestMapping(value = "/dashboard/{dashboardId}", method = RequestMethod.GET)
@ResponseBody
public Dashboard getDashboardById(@PathVariable("dashboardId") String strDashboardId) throws ThingsboardException {
checkParameter("dashboardId", strDashboardId);
public Dashboard getDashboardById(@PathVariable(DASHBOARD_ID) String strDashboardId) throws ThingsboardException {
checkParameter(DASHBOARD_ID, strDashboardId);
try {
DashboardId dashboardId = new DashboardId(toUUID(strDashboardId));
return checkDashboardId(dashboardId);
@ -82,8 +84,8 @@ public class DashboardController extends BaseController {
@PreAuthorize("hasAuthority('TENANT_ADMIN')")
@RequestMapping(value = "/dashboard/{dashboardId}", method = RequestMethod.DELETE)
@ResponseStatus(value = HttpStatus.OK)
public void deleteDashboard(@PathVariable("dashboardId") String strDashboardId) throws ThingsboardException {
checkParameter("dashboardId", strDashboardId);
public void deleteDashboard(@PathVariable(DASHBOARD_ID) String strDashboardId) throws ThingsboardException {
checkParameter(DASHBOARD_ID, strDashboardId);
try {
DashboardId dashboardId = new DashboardId(toUUID(strDashboardId));
checkDashboardId(dashboardId);
@ -97,9 +99,9 @@ public class DashboardController extends BaseController {
@RequestMapping(value = "/customer/{customerId}/dashboard/{dashboardId}", method = RequestMethod.POST)
@ResponseBody
public Dashboard assignDashboardToCustomer(@PathVariable("customerId") String strCustomerId,
@PathVariable("dashboardId") String strDashboardId) throws ThingsboardException {
@PathVariable(DASHBOARD_ID) String strDashboardId) throws ThingsboardException {
checkParameter("customerId", strCustomerId);
checkParameter("dashboardId", strDashboardId);
checkParameter(DASHBOARD_ID, strDashboardId);
try {
CustomerId customerId = new CustomerId(toUUID(strCustomerId));
checkCustomerId(customerId);
@ -116,8 +118,8 @@ public class DashboardController extends BaseController {
@PreAuthorize("hasAuthority('TENANT_ADMIN')")
@RequestMapping(value = "/customer/dashboard/{dashboardId}", method = RequestMethod.DELETE)
@ResponseBody
public Dashboard unassignDashboardFromCustomer(@PathVariable("dashboardId") String strDashboardId) throws ThingsboardException {
checkParameter("dashboardId", strDashboardId);
public Dashboard unassignDashboardFromCustomer(@PathVariable(DASHBOARD_ID) String strDashboardId) throws ThingsboardException {
checkParameter(DASHBOARD_ID, strDashboardId);
try {
DashboardId dashboardId = new DashboardId(toUUID(strDashboardId));
Dashboard dashboard = checkDashboardId(dashboardId);
@ -133,8 +135,8 @@ public class DashboardController extends BaseController {
@PreAuthorize("hasAuthority('TENANT_ADMIN')")
@RequestMapping(value = "/customer/public/dashboard/{dashboardId}", method = RequestMethod.POST)
@ResponseBody
public Dashboard assignDashboardToPublicCustomer(@PathVariable("dashboardId") String strDashboardId) throws ThingsboardException {
checkParameter("dashboardId", strDashboardId);
public Dashboard assignDashboardToPublicCustomer(@PathVariable(DASHBOARD_ID) String strDashboardId) throws ThingsboardException {
checkParameter(DASHBOARD_ID, strDashboardId);
try {
DashboardId dashboardId = new DashboardId(toUUID(strDashboardId));
Dashboard dashboard = checkDashboardId(dashboardId);

26
application/src/main/java/org/thingsboard/server/controller/DeviceController.java

@ -44,11 +44,13 @@ import java.util.stream.Collectors;
@RequestMapping("/api")
public class DeviceController extends BaseController {
public static final String DEVICE_ID = "deviceId";
@PreAuthorize("hasAnyAuthority('TENANT_ADMIN', 'CUSTOMER_USER')")
@RequestMapping(value = "/device/{deviceId}", method = RequestMethod.GET)
@ResponseBody
public Device getDeviceById(@PathVariable("deviceId") String strDeviceId) throws ThingsboardException {
checkParameter("deviceId", strDeviceId);
public Device getDeviceById(@PathVariable(DEVICE_ID) String strDeviceId) throws ThingsboardException {
checkParameter(DEVICE_ID, strDeviceId);
try {
DeviceId deviceId = new DeviceId(toUUID(strDeviceId));
return checkDeviceId(deviceId);
@ -88,8 +90,8 @@ public class DeviceController extends BaseController {
@PreAuthorize("hasAuthority('TENANT_ADMIN')")
@RequestMapping(value = "/device/{deviceId}", method = RequestMethod.DELETE)
@ResponseStatus(value = HttpStatus.OK)
public void deleteDevice(@PathVariable("deviceId") String strDeviceId) throws ThingsboardException {
checkParameter("deviceId", strDeviceId);
public void deleteDevice(@PathVariable(DEVICE_ID) String strDeviceId) throws ThingsboardException {
checkParameter(DEVICE_ID, strDeviceId);
try {
DeviceId deviceId = new DeviceId(toUUID(strDeviceId));
checkDeviceId(deviceId);
@ -103,9 +105,9 @@ public class DeviceController extends BaseController {
@RequestMapping(value = "/customer/{customerId}/device/{deviceId}", method = RequestMethod.POST)
@ResponseBody
public Device assignDeviceToCustomer(@PathVariable("customerId") String strCustomerId,
@PathVariable("deviceId") String strDeviceId) throws ThingsboardException {
@PathVariable(DEVICE_ID) String strDeviceId) throws ThingsboardException {
checkParameter("customerId", strCustomerId);
checkParameter("deviceId", strDeviceId);
checkParameter(DEVICE_ID, strDeviceId);
try {
CustomerId customerId = new CustomerId(toUUID(strCustomerId));
checkCustomerId(customerId);
@ -122,8 +124,8 @@ public class DeviceController extends BaseController {
@PreAuthorize("hasAuthority('TENANT_ADMIN')")
@RequestMapping(value = "/customer/device/{deviceId}", method = RequestMethod.DELETE)
@ResponseBody
public Device unassignDeviceFromCustomer(@PathVariable("deviceId") String strDeviceId) throws ThingsboardException {
checkParameter("deviceId", strDeviceId);
public Device unassignDeviceFromCustomer(@PathVariable(DEVICE_ID) String strDeviceId) throws ThingsboardException {
checkParameter(DEVICE_ID, strDeviceId);
try {
DeviceId deviceId = new DeviceId(toUUID(strDeviceId));
Device device = checkDeviceId(deviceId);
@ -139,8 +141,8 @@ public class DeviceController extends BaseController {
@PreAuthorize("hasAuthority('TENANT_ADMIN')")
@RequestMapping(value = "/customer/public/device/{deviceId}", method = RequestMethod.POST)
@ResponseBody
public Device assignDeviceToPublicCustomer(@PathVariable("deviceId") String strDeviceId) throws ThingsboardException {
checkParameter("deviceId", strDeviceId);
public Device assignDeviceToPublicCustomer(@PathVariable(DEVICE_ID) String strDeviceId) throws ThingsboardException {
checkParameter(DEVICE_ID, strDeviceId);
try {
DeviceId deviceId = new DeviceId(toUUID(strDeviceId));
Device device = checkDeviceId(deviceId);
@ -154,8 +156,8 @@ public class DeviceController extends BaseController {
@PreAuthorize("hasAnyAuthority('TENANT_ADMIN', 'CUSTOMER_USER')")
@RequestMapping(value = "/device/{deviceId}/credentials", method = RequestMethod.GET)
@ResponseBody
public DeviceCredentials getDeviceCredentialsByDeviceId(@PathVariable("deviceId") String strDeviceId) throws ThingsboardException {
checkParameter("deviceId", strDeviceId);
public DeviceCredentials getDeviceCredentialsByDeviceId(@PathVariable(DEVICE_ID) String strDeviceId) throws ThingsboardException {
checkParameter(DEVICE_ID, strDeviceId);
try {
DeviceId deviceId = new DeviceId(toUUID(strDeviceId));
checkDeviceId(deviceId);

126
application/src/main/java/org/thingsboard/server/controller/EntityRelationController.java

@ -34,6 +34,12 @@ import java.util.List;
@RequestMapping("/api")
public class EntityRelationController extends BaseController {
public static final String TO_TYPE = "toType";
public static final String FROM_ID = "fromId";
public static final String FROM_TYPE = "fromType";
public static final String RELATION_TYPE = "relationType";
public static final String TO_ID = "toId";
@PreAuthorize("hasAnyAuthority('SYS_ADMIN', 'TENANT_ADMIN', 'CUSTOMER_USER')")
@RequestMapping(value = "/relation", method = RequestMethod.POST)
@ResponseStatus(value = HttpStatus.OK)
@ -45,32 +51,32 @@ public class EntityRelationController extends BaseController {
if (relation.getTypeGroup() == null) {
relation.setTypeGroup(RelationTypeGroup.COMMON);
}
relationService.saveRelation(relation).get();
relationService.saveRelation(relation);
} catch (Exception e) {
throw handleException(e);
}
}
@PreAuthorize("hasAnyAuthority('SYS_ADMIN', 'TENANT_ADMIN', 'CUSTOMER_USER')")
@RequestMapping(value = "/relation", method = RequestMethod.DELETE, params = {"fromId", "fromType", "relationType", "toId", "toType"})
@RequestMapping(value = "/relation", method = RequestMethod.DELETE, params = {FROM_ID, FROM_TYPE, RELATION_TYPE, TO_ID, TO_TYPE})
@ResponseStatus(value = HttpStatus.OK)
public void deleteRelation(@RequestParam("fromId") String strFromId,
@RequestParam("fromType") String strFromType,
@RequestParam("relationType") String strRelationType,
public void deleteRelation(@RequestParam(FROM_ID) String strFromId,
@RequestParam(FROM_TYPE) String strFromType,
@RequestParam(RELATION_TYPE) String strRelationType,
@RequestParam(value = "relationTypeGroup", required = false) String strRelationTypeGroup,
@RequestParam("toId") String strToId, @RequestParam("toType") String strToType) throws ThingsboardException {
checkParameter("fromId", strFromId);
checkParameter("fromType", strFromType);
checkParameter("relationType", strRelationType);
checkParameter("toId", strToId);
checkParameter("toType", strToType);
@RequestParam(TO_ID) String strToId, @RequestParam(TO_TYPE) String strToType) throws ThingsboardException {
checkParameter(FROM_ID, strFromId);
checkParameter(FROM_TYPE, strFromType);
checkParameter(RELATION_TYPE, strRelationType);
checkParameter(TO_ID, strToId);
checkParameter(TO_TYPE, strToType);
EntityId fromId = EntityIdFactory.getByTypeAndId(strFromType, strFromId);
EntityId toId = EntityIdFactory.getByTypeAndId(strToType, strToId);
checkEntityId(fromId);
checkEntityId(toId);
RelationTypeGroup relationTypeGroup = parseRelationTypeGroup(strRelationTypeGroup, RelationTypeGroup.COMMON);
try {
Boolean found = relationService.deleteRelation(fromId, toId, strRelationType, relationTypeGroup).get();
Boolean found = relationService.deleteRelation(fromId, toId, strRelationType, relationTypeGroup);
if (!found) {
throw new ThingsboardException("Requested item wasn't found!", ThingsboardErrorCode.ITEM_NOT_FOUND);
}
@ -89,26 +95,26 @@ public class EntityRelationController extends BaseController {
EntityId entityId = EntityIdFactory.getByTypeAndId(strType, strId);
checkEntityId(entityId);
try {
relationService.deleteEntityRelations(entityId).get();
relationService.deleteEntityRelations(entityId);
} catch (Exception e) {
throw handleException(e);
}
}
@PreAuthorize("hasAnyAuthority('SYS_ADMIN', 'TENANT_ADMIN', 'CUSTOMER_USER')")
@RequestMapping(value = "/relation", method = RequestMethod.GET, params = {"fromId", "fromType", "relationType", "toId", "toType"})
@RequestMapping(value = "/relation", method = RequestMethod.GET, params = {FROM_ID, FROM_TYPE, RELATION_TYPE, TO_ID, TO_TYPE})
@ResponseBody
public EntityRelation getRelation(@RequestParam("fromId") String strFromId,
@RequestParam("fromType") String strFromType,
@RequestParam("relationType") String strRelationType,
@RequestParam(value = "relationTypeGroup", required = false) String strRelationTypeGroup,
@RequestParam("toId") String strToId, @RequestParam("toType") String strToType) throws ThingsboardException {
public EntityRelation getRelation(@RequestParam(FROM_ID) String strFromId,
@RequestParam(FROM_TYPE) String strFromType,
@RequestParam(RELATION_TYPE) String strRelationType,
@RequestParam(value = "relationTypeGroup", required = false) String strRelationTypeGroup,
@RequestParam(TO_ID) String strToId, @RequestParam(TO_TYPE) String strToType) throws ThingsboardException {
try {
checkParameter("fromId", strFromId);
checkParameter("fromType", strFromType);
checkParameter("relationType", strRelationType);
checkParameter("toId", strToId);
checkParameter("toType", strToType);
checkParameter(FROM_ID, strFromId);
checkParameter(FROM_TYPE, strFromType);
checkParameter(RELATION_TYPE, strRelationType);
checkParameter(TO_ID, strToId);
checkParameter(TO_TYPE, strToType);
EntityId fromId = EntityIdFactory.getByTypeAndId(strFromType, strFromId);
EntityId toId = EntityIdFactory.getByTypeAndId(strToType, strToId);
checkEntityId(fromId);
@ -121,13 +127,13 @@ public class EntityRelationController extends BaseController {
}
@PreAuthorize("hasAnyAuthority('SYS_ADMIN', 'TENANT_ADMIN', 'CUSTOMER_USER')")
@RequestMapping(value = "/relations", method = RequestMethod.GET, params = {"fromId", "fromType"})
@RequestMapping(value = "/relations", method = RequestMethod.GET, params = {FROM_ID, FROM_TYPE})
@ResponseBody
public List<EntityRelation> findByFrom(@RequestParam("fromId") String strFromId,
@RequestParam("fromType") String strFromType,
public List<EntityRelation> findByFrom(@RequestParam(FROM_ID) String strFromId,
@RequestParam(FROM_TYPE) String strFromType,
@RequestParam(value = "relationTypeGroup", required = false) String strRelationTypeGroup) throws ThingsboardException {
checkParameter("fromId", strFromId);
checkParameter("fromType", strFromType);
checkParameter(FROM_ID, strFromId);
checkParameter(FROM_TYPE, strFromType);
EntityId entityId = EntityIdFactory.getByTypeAndId(strFromType, strFromId);
checkEntityId(entityId);
RelationTypeGroup typeGroup = parseRelationTypeGroup(strRelationTypeGroup, RelationTypeGroup.COMMON);
@ -139,13 +145,13 @@ public class EntityRelationController extends BaseController {
}
@PreAuthorize("hasAnyAuthority('SYS_ADMIN', 'TENANT_ADMIN', 'CUSTOMER_USER')")
@RequestMapping(value = "/relations/info", method = RequestMethod.GET, params = {"fromId", "fromType"})
@RequestMapping(value = "/relations/info", method = RequestMethod.GET, params = {FROM_ID, FROM_TYPE})
@ResponseBody
public List<EntityRelationInfo> findInfoByFrom(@RequestParam("fromId") String strFromId,
@RequestParam("fromType") String strFromType,
public List<EntityRelationInfo> findInfoByFrom(@RequestParam(FROM_ID) String strFromId,
@RequestParam(FROM_TYPE) String strFromType,
@RequestParam(value = "relationTypeGroup", required = false) String strRelationTypeGroup) throws ThingsboardException {
checkParameter("fromId", strFromId);
checkParameter("fromType", strFromType);
checkParameter(FROM_ID, strFromId);
checkParameter(FROM_TYPE, strFromType);
EntityId entityId = EntityIdFactory.getByTypeAndId(strFromType, strFromId);
checkEntityId(entityId);
RelationTypeGroup typeGroup = parseRelationTypeGroup(strRelationTypeGroup, RelationTypeGroup.COMMON);
@ -157,15 +163,15 @@ public class EntityRelationController extends BaseController {
}
@PreAuthorize("hasAnyAuthority('SYS_ADMIN', 'TENANT_ADMIN', 'CUSTOMER_USER')")
@RequestMapping(value = "/relations", method = RequestMethod.GET, params = {"fromId", "fromType", "relationType"})
@RequestMapping(value = "/relations", method = RequestMethod.GET, params = {FROM_ID, FROM_TYPE, RELATION_TYPE})
@ResponseBody
public List<EntityRelation> findByFrom(@RequestParam("fromId") String strFromId,
@RequestParam("fromType") String strFromType,
@RequestParam("relationType") String strRelationType,
public List<EntityRelation> findByFrom(@RequestParam(FROM_ID) String strFromId,
@RequestParam(FROM_TYPE) String strFromType,
@RequestParam(RELATION_TYPE) String strRelationType,
@RequestParam(value = "relationTypeGroup", required = false) String strRelationTypeGroup) throws ThingsboardException {
checkParameter("fromId", strFromId);
checkParameter("fromType", strFromType);
checkParameter("relationType", strRelationType);
checkParameter(FROM_ID, strFromId);
checkParameter(FROM_TYPE, strFromType);
checkParameter(RELATION_TYPE, strRelationType);
EntityId entityId = EntityIdFactory.getByTypeAndId(strFromType, strFromId);
checkEntityId(entityId);
RelationTypeGroup typeGroup = parseRelationTypeGroup(strRelationTypeGroup, RelationTypeGroup.COMMON);
@ -177,13 +183,13 @@ public class EntityRelationController extends BaseController {
}
@PreAuthorize("hasAnyAuthority('SYS_ADMIN', 'TENANT_ADMIN', 'CUSTOMER_USER')")
@RequestMapping(value = "/relations", method = RequestMethod.GET, params = {"toId", "toType"})
@RequestMapping(value = "/relations", method = RequestMethod.GET, params = {TO_ID, TO_TYPE})
@ResponseBody
public List<EntityRelation> findByTo(@RequestParam("toId") String strToId,
@RequestParam("toType") String strToType,
public List<EntityRelation> findByTo(@RequestParam(TO_ID) String strToId,
@RequestParam(TO_TYPE) String strToType,
@RequestParam(value = "relationTypeGroup", required = false) String strRelationTypeGroup) throws ThingsboardException {
checkParameter("toId", strToId);
checkParameter("toType", strToType);
checkParameter(TO_ID, strToId);
checkParameter(TO_TYPE, strToType);
EntityId entityId = EntityIdFactory.getByTypeAndId(strToType, strToId);
checkEntityId(entityId);
RelationTypeGroup typeGroup = parseRelationTypeGroup(strRelationTypeGroup, RelationTypeGroup.COMMON);
@ -195,13 +201,13 @@ public class EntityRelationController extends BaseController {
}
@PreAuthorize("hasAnyAuthority('SYS_ADMIN', 'TENANT_ADMIN', 'CUSTOMER_USER')")
@RequestMapping(value = "/relations/info", method = RequestMethod.GET, params = {"toId", "toType"})
@RequestMapping(value = "/relations/info", method = RequestMethod.GET, params = {TO_ID, TO_TYPE})
@ResponseBody
public List<EntityRelationInfo> findInfoByTo(@RequestParam("toId") String strToId,
@RequestParam("toType") String strToType,
public List<EntityRelationInfo> findInfoByTo(@RequestParam(TO_ID) String strToId,
@RequestParam(TO_TYPE) String strToType,
@RequestParam(value = "relationTypeGroup", required = false) String strRelationTypeGroup) throws ThingsboardException {
checkParameter("toId", strToId);
checkParameter("toType", strToType);
checkParameter(TO_ID, strToId);
checkParameter(TO_TYPE, strToType);
EntityId entityId = EntityIdFactory.getByTypeAndId(strToType, strToId);
checkEntityId(entityId);
RelationTypeGroup typeGroup = parseRelationTypeGroup(strRelationTypeGroup, RelationTypeGroup.COMMON);
@ -213,15 +219,15 @@ public class EntityRelationController extends BaseController {
}
@PreAuthorize("hasAnyAuthority('SYS_ADMIN', 'TENANT_ADMIN', 'CUSTOMER_USER')")
@RequestMapping(value = "/relations", method = RequestMethod.GET, params = {"toId", "toType", "relationType"})
@RequestMapping(value = "/relations", method = RequestMethod.GET, params = {TO_ID, TO_TYPE, RELATION_TYPE})
@ResponseBody
public List<EntityRelation> findByTo(@RequestParam("toId") String strToId,
@RequestParam("toType") String strToType,
@RequestParam("relationType") String strRelationType,
public List<EntityRelation> findByTo(@RequestParam(TO_ID) String strToId,
@RequestParam(TO_TYPE) String strToType,
@RequestParam(RELATION_TYPE) String strRelationType,
@RequestParam(value = "relationTypeGroup", required = false) String strRelationTypeGroup) throws ThingsboardException {
checkParameter("toId", strToId);
checkParameter("toType", strToType);
checkParameter("relationType", strRelationType);
checkParameter(TO_ID, strToId);
checkParameter(TO_TYPE, strToType);
checkParameter(RELATION_TYPE, strRelationType);
EntityId entityId = EntityIdFactory.getByTypeAndId(strToType, strToId);
checkEntityId(entityId);
RelationTypeGroup typeGroup = parseRelationTypeGroup(strRelationTypeGroup, RelationTypeGroup.COMMON);
@ -267,9 +273,7 @@ public class EntityRelationController extends BaseController {
if (strRelationTypeGroup != null && strRelationTypeGroup.trim().length()>0) {
try {
result = RelationTypeGroup.valueOf(strRelationTypeGroup);
} catch (IllegalArgumentException e) {
result = defaultValue;
}
} catch (IllegalArgumentException e) { }
}
return result;
}

18
application/src/main/java/org/thingsboard/server/controller/PluginController.java

@ -34,11 +34,13 @@ import java.util.List;
@RequestMapping("/api")
public class PluginController extends BaseController {
public static final String PLUGIN_ID = "pluginId";
@PreAuthorize("hasAnyAuthority('SYS_ADMIN', 'TENANT_ADMIN')")
@RequestMapping(value = "/plugin/{pluginId}", method = RequestMethod.GET)
@ResponseBody
public PluginMetaData getPluginById(@PathVariable("pluginId") String strPluginId) throws ThingsboardException {
checkParameter("pluginId", strPluginId);
public PluginMetaData getPluginById(@PathVariable(PLUGIN_ID) String strPluginId) throws ThingsboardException {
checkParameter(PLUGIN_ID, strPluginId);
try {
PluginId pluginId = new PluginId(toUUID(strPluginId));
return checkPlugin(pluginService.findPluginById(pluginId));
@ -78,8 +80,8 @@ public class PluginController extends BaseController {
@PreAuthorize("hasAnyAuthority('SYS_ADMIN', 'TENANT_ADMIN')")
@RequestMapping(value = "/plugin/{pluginId}/activate", method = RequestMethod.POST)
@ResponseStatus(value = HttpStatus.OK)
public void activatePluginById(@PathVariable("pluginId") String strPluginId) throws ThingsboardException {
checkParameter("pluginId", strPluginId);
public void activatePluginById(@PathVariable(PLUGIN_ID) String strPluginId) throws ThingsboardException {
checkParameter(PLUGIN_ID, strPluginId);
try {
PluginId pluginId = new PluginId(toUUID(strPluginId));
PluginMetaData plugin = checkPlugin(pluginService.findPluginById(pluginId));
@ -93,8 +95,8 @@ public class PluginController extends BaseController {
@PreAuthorize("hasAnyAuthority('SYS_ADMIN', 'TENANT_ADMIN')")
@RequestMapping(value = "/plugin/{pluginId}/suspend", method = RequestMethod.POST)
@ResponseStatus(value = HttpStatus.OK)
public void suspendPluginById(@PathVariable("pluginId") String strPluginId) throws ThingsboardException {
checkParameter("pluginId", strPluginId);
public void suspendPluginById(@PathVariable(PLUGIN_ID) String strPluginId) throws ThingsboardException {
checkParameter(PLUGIN_ID, strPluginId);
try {
PluginId pluginId = new PluginId(toUUID(strPluginId));
PluginMetaData plugin = checkPlugin(pluginService.findPluginById(pluginId));
@ -180,8 +182,8 @@ public class PluginController extends BaseController {
@PreAuthorize("hasAnyAuthority('SYS_ADMIN', 'TENANT_ADMIN')")
@RequestMapping(value = "/plugin/{pluginId}", method = RequestMethod.DELETE)
@ResponseStatus(value = HttpStatus.OK)
public void deletePlugin(@PathVariable("pluginId") String strPluginId) throws ThingsboardException {
checkParameter("pluginId", strPluginId);
public void deletePlugin(@PathVariable(PLUGIN_ID) String strPluginId) throws ThingsboardException {
checkParameter(PLUGIN_ID, strPluginId);
try {
PluginId pluginId = new PluginId(toUUID(strPluginId));
PluginMetaData plugin = checkPlugin(pluginService.findPluginById(pluginId));

18
application/src/main/java/org/thingsboard/server/controller/RuleController.java

@ -34,11 +34,13 @@ import java.util.List;
@RequestMapping("/api")
public class RuleController extends BaseController {
public static final String RULE_ID = "ruleId";
@PreAuthorize("hasAnyAuthority('SYS_ADMIN', 'TENANT_ADMIN')")
@RequestMapping(value = "/rule/{ruleId}", method = RequestMethod.GET)
@ResponseBody
public RuleMetaData getRuleById(@PathVariable("ruleId") String strRuleId) throws ThingsboardException {
checkParameter("ruleId", strRuleId);
public RuleMetaData getRuleById(@PathVariable(RULE_ID) String strRuleId) throws ThingsboardException {
checkParameter(RULE_ID, strRuleId);
try {
RuleId ruleId = new RuleId(toUUID(strRuleId));
return checkRule(ruleService.findRuleById(ruleId));
@ -80,8 +82,8 @@ public class RuleController extends BaseController {
@PreAuthorize("hasAnyAuthority('SYS_ADMIN', 'TENANT_ADMIN')")
@RequestMapping(value = "/rule/{ruleId}/activate", method = RequestMethod.POST)
@ResponseStatus(value = HttpStatus.OK)
public void activateRuleById(@PathVariable("ruleId") String strRuleId) throws ThingsboardException {
checkParameter("ruleId", strRuleId);
public void activateRuleById(@PathVariable(RULE_ID) String strRuleId) throws ThingsboardException {
checkParameter(RULE_ID, strRuleId);
try {
RuleId ruleId = new RuleId(toUUID(strRuleId));
RuleMetaData rule = checkRule(ruleService.findRuleById(ruleId));
@ -95,8 +97,8 @@ public class RuleController extends BaseController {
@PreAuthorize("hasAnyAuthority('SYS_ADMIN', 'TENANT_ADMIN')")
@RequestMapping(value = "/rule/{ruleId}/suspend", method = RequestMethod.POST)
@ResponseStatus(value = HttpStatus.OK)
public void suspendRuleById(@PathVariable("ruleId") String strRuleId) throws ThingsboardException {
checkParameter("ruleId", strRuleId);
public void suspendRuleById(@PathVariable(RULE_ID) String strRuleId) throws ThingsboardException {
checkParameter(RULE_ID, strRuleId);
try {
RuleId ruleId = new RuleId(toUUID(strRuleId));
RuleMetaData rule = checkRule(ruleService.findRuleById(ruleId));
@ -178,8 +180,8 @@ public class RuleController extends BaseController {
@PreAuthorize("hasAnyAuthority('SYS_ADMIN', 'TENANT_ADMIN')")
@RequestMapping(value = "/rule/{ruleId}", method = RequestMethod.DELETE)
@ResponseStatus(value = HttpStatus.OK)
public void deleteRule(@PathVariable("ruleId") String strRuleId) throws ThingsboardException {
checkParameter("ruleId", strRuleId);
public void deleteRule(@PathVariable(RULE_ID) String strRuleId) throws ThingsboardException {
checkParameter(RULE_ID, strRuleId);
try {
RuleId ruleId = new RuleId(toUUID(strRuleId));
RuleMetaData rule = checkRule(ruleService.findRuleById(ruleId));

27
application/src/main/java/org/thingsboard/server/controller/UserController.java

@ -38,19 +38,22 @@ import javax.servlet.http.HttpServletRequest;
@RequestMapping("/api")
public class UserController extends BaseController {
public static final String USER_ID = "userId";
public static final String YOU_DON_T_HAVE_PERMISSION_TO_PERFORM_THIS_OPERATION = "You don't have permission to perform this operation!";
public static final String ACTIVATE_URL_PATTERN = "%s/api/noauth/activate?activateToken=%s";
@Autowired
private MailService mailService;
@PreAuthorize("hasAnyAuthority('SYS_ADMIN', 'TENANT_ADMIN', 'CUSTOMER_USER')")
@RequestMapping(value = "/user/{userId}", method = RequestMethod.GET)
@ResponseBody
public User getUserById(@PathVariable("userId") String strUserId) throws ThingsboardException {
checkParameter("userId", strUserId);
public User getUserById(@PathVariable(USER_ID) String strUserId) throws ThingsboardException {
checkParameter(USER_ID, strUserId);
try {
UserId userId = new UserId(toUUID(strUserId));
SecurityUser authUser = getCurrentUser();
if (authUser.getAuthority() == Authority.CUSTOMER_USER && !authUser.getId().equals(userId)) {
throw new ThingsboardException("You don't have permission to perform this operation!",
throw new ThingsboardException(YOU_DON_T_HAVE_PERMISSION_TO_PERFORM_THIS_OPERATION,
ThingsboardErrorCode.PERMISSION_DENIED);
}
return checkUserId(userId);
@ -68,7 +71,7 @@ public class UserController extends BaseController {
try {
SecurityUser authUser = getCurrentUser();
if (authUser.getAuthority() == Authority.CUSTOMER_USER && !authUser.getId().equals(user.getId())) {
throw new ThingsboardException("You don't have permission to perform this operation!",
throw new ThingsboardException(YOU_DON_T_HAVE_PERMISSION_TO_PERFORM_THIS_OPERATION,
ThingsboardErrorCode.PERMISSION_DENIED);
}
boolean sendEmail = user.getId() == null && sendActivationMail;
@ -79,7 +82,7 @@ public class UserController extends BaseController {
if (sendEmail) {
UserCredentials userCredentials = userService.findUserCredentialsByUserId(savedUser.getId());
String baseUrl = constructBaseUrl(request);
String activateUrl = String.format("%s/api/noauth/activate?activateToken=%s", baseUrl,
String activateUrl = String.format(ACTIVATE_URL_PATTERN, baseUrl,
userCredentials.getActivateToken());
String email = savedUser.getEmail();
try {
@ -106,7 +109,7 @@ public class UserController extends BaseController {
UserCredentials userCredentials = userService.findUserCredentialsByUserId(user.getId());
if (!userCredentials.isEnabled()) {
String baseUrl = constructBaseUrl(request);
String activateUrl = String.format("%s/api/noauth/activate?activateToken=%s", baseUrl,
String activateUrl = String.format(ACTIVATE_URL_PATTERN, baseUrl,
userCredentials.getActivateToken());
mailService.sendActivationEmail(activateUrl, email);
} else {
@ -121,21 +124,21 @@ public class UserController extends BaseController {
@RequestMapping(value = "/user/{userId}/activationLink", method = RequestMethod.GET, produces = "text/plain")
@ResponseBody
public String getActivationLink(
@PathVariable("userId") String strUserId,
@PathVariable(USER_ID) String strUserId,
HttpServletRequest request) throws ThingsboardException {
checkParameter("userId", strUserId);
checkParameter(USER_ID, strUserId);
try {
UserId userId = new UserId(toUUID(strUserId));
SecurityUser authUser = getCurrentUser();
if (authUser.getAuthority() == Authority.CUSTOMER_USER && !authUser.getId().equals(userId)) {
throw new ThingsboardException("You don't have permission to perform this operation!",
throw new ThingsboardException(YOU_DON_T_HAVE_PERMISSION_TO_PERFORM_THIS_OPERATION,
ThingsboardErrorCode.PERMISSION_DENIED);
}
User user = checkUserId(userId);
UserCredentials userCredentials = userService.findUserCredentialsByUserId(user.getId());
if (!userCredentials.isEnabled()) {
String baseUrl = constructBaseUrl(request);
String activateUrl = String.format("%s/api/noauth/activate?activateToken=%s", baseUrl,
String activateUrl = String.format(ACTIVATE_URL_PATTERN, baseUrl,
userCredentials.getActivateToken());
return activateUrl;
} else {
@ -149,8 +152,8 @@ public class UserController extends BaseController {
@PreAuthorize("hasAnyAuthority('SYS_ADMIN', 'TENANT_ADMIN')")
@RequestMapping(value = "/user/{userId}", method = RequestMethod.DELETE)
@ResponseStatus(value = HttpStatus.OK)
public void deleteUser(@PathVariable("userId") String strUserId) throws ThingsboardException {
checkParameter("userId", strUserId);
public void deleteUser(@PathVariable(USER_ID) String strUserId) throws ThingsboardException {
checkParameter(USER_ID, strUserId);
try {
UserId userId = new UserId(toUUID(strUserId));
checkUserId(userId);

10
application/src/main/java/org/thingsboard/server/controller/plugin/PluginApiController.java

@ -47,12 +47,6 @@ import javax.servlet.http.HttpServletRequest;
@Slf4j
public class PluginApiController extends BaseController {
@Autowired
private ActorService actorService;
@Autowired
private PluginService pluginService;
@SuppressWarnings("rawtypes")
@PreAuthorize("hasAnyAuthority('SYS_ADMIN', 'TENANT_ADMIN', 'CUSTOMER_USER')")
@RequestMapping(value = "/{pluginToken}/**")
@ -71,7 +65,7 @@ public class PluginApiController extends BaseController {
TenantId tenantId = getCurrentUser().getTenantId();
CustomerId customerId = getCurrentUser().getCustomerId();
if (validatePluginAccess(pluginMd, tenantId, customerId)) {
if(ModelConstants.NULL_UUID.equals(tenantId.getId())){
if(tenantId != null && ModelConstants.NULL_UUID.equals(tenantId.getId())){
tenantId = null;
}
PluginApiCallSecurityContext securityCtx = new PluginApiCallSecurityContext(pluginMd.getTenantId(), pluginMd.getId(), tenantId, customerId);
@ -97,7 +91,7 @@ public class PluginApiController extends BaseController {
validUser = true;
}
} else {
if ((pluginMd.isPublicAccess() || tenantAdministrator) && tenantId.equals(pluginMd.getTenantId())) {
if ((pluginMd.isPublicAccess() || tenantAdministrator) && tenantId != null && tenantId.equals(pluginMd.getTenantId())) {
// All tenant users can access public tenant plugins. Only tenant
// administrator can access private tenant plugins
validUser = true;

5
application/src/main/java/org/thingsboard/server/install/ThingsboardInstallService.java

@ -28,7 +28,6 @@ import org.thingsboard.server.service.install.DatabaseSchemaService;
import org.thingsboard.server.service.install.DatabaseUpgradeService;
import org.thingsboard.server.service.install.SystemDataLoaderService;
import java.nio.file.Files;
import java.nio.file.Paths;
@Service
@ -69,7 +68,7 @@ public class ThingsboardInstallService {
log.info("Starting ThingsBoard Upgrade from version {} ...", upgradeFromVersion);
switch (upgradeFromVersion) {
case "1.2.3":
case "1.2.3": //NOSONAR, Need to execute gradual upgrade starting from upgradeFromVersion
log.info("Upgrading ThingsBoard from version 1.2.3 to 1.3.0 ...");
databaseUpgradeService.upgradeDatabase(upgradeFromVersion);
@ -115,7 +114,7 @@ public class ThingsboardInstallService {
if (this.dataDir == null) {
throw new RuntimeException("'install.data_dir' property should specified!");
}
if (!Files.isDirectory(Paths.get(this.dataDir))) {
if (!Paths.get(this.dataDir).toFile().isDirectory()) {
throw new RuntimeException("'install.data_dir' property value is not a valid directory!");
}

4
application/src/main/java/org/thingsboard/server/service/cluster/discovery/DummyDiscoveryService.java

@ -45,12 +45,12 @@ public class DummyDiscoveryService implements DiscoveryService {
@Override
public void publishCurrentServer() {
//Do nothing
}
@Override
public void unpublishCurrentServer() {
//Do nothing
}
@Override

2
application/src/main/java/org/thingsboard/server/service/cluster/discovery/ZkDiscoveryService.java

@ -202,6 +202,8 @@ public class ZkDiscoveryService implements DiscoveryService, PathChildrenCacheLi
case CHILD_REMOVED:
listeners.forEach(listener -> listener.onServerRemoved(instance));
break;
default:
break;
}
}
}

2
application/src/main/java/org/thingsboard/server/service/cluster/rpc/ClusterGrpcService.java

@ -95,6 +95,7 @@ public class ClusterGrpcService extends ClusterRpcServiceGrpc.ClusterRpcServiceI
future.onMsg(msg);
} catch (InterruptedException e) {
log.warn("Failed to report created session!");
Thread.currentThread().interrupt();
}
} else {
log.warn("Failed to lookup pending session!");
@ -117,6 +118,7 @@ public class ClusterGrpcService extends ClusterRpcServiceGrpc.ClusterRpcServiceI
log.info("RPC server stopped!");
} catch (InterruptedException e) {
log.warn("Failed to onStop RPC server!");
Thread.currentThread().interrupt();
}
}
}

60
application/src/main/java/org/thingsboard/server/service/cluster/rpc/GrpcSession.java

@ -29,7 +29,7 @@ import java.util.UUID;
*/
@Data
@Slf4j
final public class GrpcSession implements Closeable {
public final class GrpcSession implements Closeable {
private final UUID sessionId;
private final boolean client;
private final GrpcSessionListener listener;
@ -59,36 +59,14 @@ final public class GrpcSession implements Closeable {
this.inputStream = new StreamObserver<ClusterAPIProtos.ToRpcServerMessage>() {
@Override
public void onNext(ClusterAPIProtos.ToRpcServerMessage msg) {
if (!connected) {
if (msg.hasConnectMsg()) {
connected = true;
ClusterAPIProtos.ServerAddress rpcAddress = msg.getConnectMsg().getServerAddress();
remoteServer = new ServerAddress(rpcAddress.getHost(), rpcAddress.getPort());
listener.onConnected(GrpcSession.this);
}
if (!connected && msg.hasConnectMsg()) {
connected = true;
ClusterAPIProtos.ServerAddress rpcAddress = msg.getConnectMsg().getServerAddress();
remoteServer = new ServerAddress(rpcAddress.getHost(), rpcAddress.getPort());
listener.onConnected(GrpcSession.this);
}
if (connected) {
if (msg.hasToPluginRpcMsg()) {
listener.onToPluginRpcMsg(GrpcSession.this, msg.getToPluginRpcMsg());
}
if (msg.hasToDeviceActorRpcMsg()) {
listener.onToDeviceActorRpcMsg(GrpcSession.this, msg.getToDeviceActorRpcMsg());
}
if (msg.hasToDeviceSessionActorRpcMsg()) {
listener.onToDeviceSessionActorRpcMsg(GrpcSession.this, msg.getToDeviceSessionActorRpcMsg());
}
if (msg.hasToDeviceActorNotificationRpcMsg()) {
listener.onToDeviceActorNotificationRpcMsg(GrpcSession.this, msg.getToDeviceActorNotificationRpcMsg());
}
if (msg.hasToDeviceRpcRequestRpcMsg()) {
listener.onToDeviceRpcRequestRpcMsg(GrpcSession.this, msg.getToDeviceRpcRequestRpcMsg());
}
if (msg.hasToPluginRpcResponseRpcMsg()) {
listener.onFromDeviceRpcResponseRpcMsg(GrpcSession.this, msg.getToPluginRpcResponseRpcMsg());
}
if (msg.hasToAllNodesRpcMsg()) {
listener.onToAllNodesRpcMessage(GrpcSession.this, msg.getToAllNodesRpcMsg());
}
handleToRpcServerMessage(msg);
}
}
@ -105,6 +83,30 @@ final public class GrpcSession implements Closeable {
};
}
private void handleToRpcServerMessage(ClusterAPIProtos.ToRpcServerMessage msg) {
if (msg.hasToPluginRpcMsg()) {
listener.onToPluginRpcMsg(GrpcSession.this, msg.getToPluginRpcMsg());
}
if (msg.hasToDeviceActorRpcMsg()) {
listener.onToDeviceActorRpcMsg(GrpcSession.this, msg.getToDeviceActorRpcMsg());
}
if (msg.hasToDeviceSessionActorRpcMsg()) {
listener.onToDeviceSessionActorRpcMsg(GrpcSession.this, msg.getToDeviceSessionActorRpcMsg());
}
if (msg.hasToDeviceActorNotificationRpcMsg()) {
listener.onToDeviceActorNotificationRpcMsg(GrpcSession.this, msg.getToDeviceActorNotificationRpcMsg());
}
if (msg.hasToDeviceRpcRequestRpcMsg()) {
listener.onToDeviceRpcRequestRpcMsg(GrpcSession.this, msg.getToDeviceRpcRequestRpcMsg());
}
if (msg.hasToPluginRpcResponseRpcMsg()) {
listener.onFromDeviceRpcResponseRpcMsg(GrpcSession.this, msg.getToPluginRpcResponseRpcMsg());
}
if (msg.hasToAllNodesRpcMsg()) {
listener.onToAllNodesRpcMessage(GrpcSession.this, msg.getToAllNodesRpcMsg());
}
}
public void initOutputStream() {
if (client) {
listener.onConnected(GrpcSession.this);

139
application/src/main/java/org/thingsboard/server/service/component/AnnotationComponentDiscoveryService.java

@ -79,78 +79,83 @@ public class AnnotationComponentDiscoveryService implements ComponentDiscoverySe
private List<ComponentDescriptor> persist(Set<BeanDefinition> filterDefs, ComponentType type) {
List<ComponentDescriptor> result = new ArrayList<>();
for (BeanDefinition def : filterDefs) {
ComponentDescriptor scannedComponent = new ComponentDescriptor();
String clazzName = def.getBeanClassName();
try {
scannedComponent.setType(type);
Class<?> clazz = Class.forName(clazzName);
String descriptorResourceName;
switch (type) {
case FILTER:
Filter filterAnnotation = clazz.getAnnotation(Filter.class);
scannedComponent.setName(filterAnnotation.name());
scannedComponent.setScope(filterAnnotation.scope());
descriptorResourceName = filterAnnotation.descriptor();
break;
case PROCESSOR:
Processor processorAnnotation = clazz.getAnnotation(Processor.class);
scannedComponent.setName(processorAnnotation.name());
scannedComponent.setScope(processorAnnotation.scope());
descriptorResourceName = processorAnnotation.descriptor();
break;
case ACTION:
Action actionAnnotation = clazz.getAnnotation(Action.class);
scannedComponent.setName(actionAnnotation.name());
scannedComponent.setScope(actionAnnotation.scope());
descriptorResourceName = actionAnnotation.descriptor();
break;
case PLUGIN:
Plugin pluginAnnotation = clazz.getAnnotation(Plugin.class);
scannedComponent.setName(pluginAnnotation.name());
scannedComponent.setScope(pluginAnnotation.scope());
descriptorResourceName = pluginAnnotation.descriptor();
for (Class<?> actionClazz : pluginAnnotation.actions()) {
ComponentDescriptor actionComponent = getComponent(actionClazz.getName())
.orElseThrow(() -> {
log.error("Can't initialize plugin {}, due to missing action {}!", def.getBeanClassName(), actionClazz.getName());
return new ClassNotFoundException("Action: " + actionClazz.getName() + "is missing!");
});
if (actionComponent.getType() != ComponentType.ACTION) {
log.error("Plugin {} action {} has wrong component type!", def.getBeanClassName(), actionClazz.getName(), actionComponent.getType());
throw new RuntimeException("Plugin " + def.getBeanClassName() + "action " + actionClazz.getName() + " has wrong component type!");
}
}
scannedComponent.setActions(Arrays.stream(pluginAnnotation.actions()).map(action -> action.getName()).collect(Collectors.joining(",")));
break;
default:
throw new RuntimeException(type + " is not supported yet!");
}
scannedComponent.setConfigurationDescriptor(mapper.readTree(
Resources.toString(Resources.getResource(descriptorResourceName), Charsets.UTF_8)));
scannedComponent.setClazz(clazzName);
log.info("Processing scanned component: {}", scannedComponent);
} catch (Exception e) {
log.error("Can't initialize component {}, due to {}", def.getBeanClassName(), e.getMessage(), e);
throw new RuntimeException(e);
}
ComponentDescriptor persistedComponent = componentDescriptorService.findByClazz(clazzName);
if (persistedComponent == null) {
log.info("Persisting new component: {}", scannedComponent);
scannedComponent = componentDescriptorService.saveComponent(scannedComponent);
} else if (scannedComponent.equals(persistedComponent)) {
log.info("Component is already persisted: {}", persistedComponent);
scannedComponent = persistedComponent;
} else {
log.info("Component {} will be updated to {}", persistedComponent, scannedComponent);
componentDescriptorService.deleteByClazz(persistedComponent.getClazz());
scannedComponent.setId(persistedComponent.getId());
scannedComponent = componentDescriptorService.saveComponent(scannedComponent);
}
ComponentDescriptor scannedComponent = scanAndPersistComponent(def, type);
result.add(scannedComponent);
}
return result;
}
private ComponentDescriptor scanAndPersistComponent(BeanDefinition def, ComponentType type) {
ComponentDescriptor scannedComponent = new ComponentDescriptor();
String clazzName = def.getBeanClassName();
try {
scannedComponent.setType(type);
Class<?> clazz = Class.forName(clazzName);
String descriptorResourceName;
switch (type) {
case FILTER:
Filter filterAnnotation = clazz.getAnnotation(Filter.class);
scannedComponent.setName(filterAnnotation.name());
scannedComponent.setScope(filterAnnotation.scope());
descriptorResourceName = filterAnnotation.descriptor();
break;
case PROCESSOR:
Processor processorAnnotation = clazz.getAnnotation(Processor.class);
scannedComponent.setName(processorAnnotation.name());
scannedComponent.setScope(processorAnnotation.scope());
descriptorResourceName = processorAnnotation.descriptor();
break;
case ACTION:
Action actionAnnotation = clazz.getAnnotation(Action.class);
scannedComponent.setName(actionAnnotation.name());
scannedComponent.setScope(actionAnnotation.scope());
descriptorResourceName = actionAnnotation.descriptor();
break;
case PLUGIN:
Plugin pluginAnnotation = clazz.getAnnotation(Plugin.class);
scannedComponent.setName(pluginAnnotation.name());
scannedComponent.setScope(pluginAnnotation.scope());
descriptorResourceName = pluginAnnotation.descriptor();
for (Class<?> actionClazz : pluginAnnotation.actions()) {
ComponentDescriptor actionComponent = getComponent(actionClazz.getName())
.orElseThrow(() -> {
log.error("Can't initialize plugin {}, due to missing action {}!", def.getBeanClassName(), actionClazz.getName());
return new ClassNotFoundException("Action: " + actionClazz.getName() + "is missing!");
});
if (actionComponent.getType() != ComponentType.ACTION) {
log.error("Plugin {} action {} has wrong component type!", def.getBeanClassName(), actionClazz.getName(), actionComponent.getType());
throw new RuntimeException("Plugin " + def.getBeanClassName() + "action " + actionClazz.getName() + " has wrong component type!");
}
}
scannedComponent.setActions(Arrays.stream(pluginAnnotation.actions()).map(action -> action.getName()).collect(Collectors.joining(",")));
break;
default:
throw new RuntimeException(type + " is not supported yet!");
}
scannedComponent.setConfigurationDescriptor(mapper.readTree(
Resources.toString(Resources.getResource(descriptorResourceName), Charsets.UTF_8)));
scannedComponent.setClazz(clazzName);
log.info("Processing scanned component: {}", scannedComponent);
} catch (Exception e) {
log.error("Can't initialize component {}, due to {}", def.getBeanClassName(), e.getMessage(), e);
throw new RuntimeException(e);
}
ComponentDescriptor persistedComponent = componentDescriptorService.findByClazz(clazzName);
if (persistedComponent == null) {
log.info("Persisting new component: {}", scannedComponent);
scannedComponent = componentDescriptorService.saveComponent(scannedComponent);
} else if (scannedComponent.equals(persistedComponent)) {
log.info("Component is already persisted: {}", persistedComponent);
scannedComponent = persistedComponent;
} else {
log.info("Component {} will be updated to {}", persistedComponent, scannedComponent);
componentDescriptorService.deleteByClazz(persistedComponent.getClazz());
scannedComponent.setId(persistedComponent.getId());
scannedComponent = componentDescriptorService.saveComponent(scannedComponent);
}
return scannedComponent;
}
private Set<BeanDefinition> getBeanDefinitions(Class<? extends Annotation> componentType) {
ClassPathScanningCandidateComponentProvider scanner = new ClassPathScanningCandidateComponentProvider(false);
scanner.addIncludeFilter(new AnnotationTypeFilter(componentType));

38
application/src/main/java/org/thingsboard/server/service/install/CassandraDatabaseUpgradeService.java

@ -40,6 +40,12 @@ import java.util.List;
public class CassandraDatabaseUpgradeService implements DatabaseUpgradeService {
private static final String SCHEMA_UPDATE_CQL = "schema_update.cql";
public static final String DEVICE = "device";
public static final String TENANT_ID = "tenant_id";
public static final String CUSTOMER_ID = "customer_id";
public static final String SEARCH_TEXT = "search_text";
public static final String ADDITIONAL_INFO = "additional_info";
public static final String ASSET = "asset";
@Value("${install.data_dir}")
private String dataDir;
@ -63,22 +69,22 @@ public class CassandraDatabaseUpgradeService implements DatabaseUpgradeService {
KeyspaceMetadata ks = cluster.getCluster().getMetadata().getKeyspace(cluster.getKeyspaceName());
log.info("Dumping devices ...");
Path devicesDump = CassandraDbHelper.dumpCfIfExists(ks, cluster.getSession(), "device",
new String[]{"id", "tenant_id", "customer_id", "name", "search_text", "additional_info", "type"},
Path devicesDump = CassandraDbHelper.dumpCfIfExists(ks, cluster.getSession(), DEVICE,
new String[]{"id", TENANT_ID, CUSTOMER_ID, "name", SEARCH_TEXT, ADDITIONAL_INFO, "type"},
new String[]{"", "", "", "", "", "", "default"},
"tb-devices");
log.info("Devices dumped.");
log.info("Dumping assets ...");
Path assetsDump = CassandraDbHelper.dumpCfIfExists(ks, cluster.getSession(), "asset",
new String[]{"id", "tenant_id", "customer_id", "name", "search_text", "additional_info", "type"},
Path assetsDump = CassandraDbHelper.dumpCfIfExists(ks, cluster.getSession(), ASSET,
new String[]{"id", TENANT_ID, CUSTOMER_ID, "name", SEARCH_TEXT, ADDITIONAL_INFO, "type"},
new String[]{"", "", "", "", "", "", "default"},
"tb-assets");
log.info("Assets dumped.");
log.info("Dumping relations ...");
Path relationsDump = CassandraDbHelper.dumpCfIfExists(ks, cluster.getSession(), "relation",
new String[]{"from_id", "from_type", "to_id", "to_type", "relation_type", "additional_info", "relation_type_group"},
new String[]{"from_id", "from_type", "to_id", "to_type", "relation_type", ADDITIONAL_INFO, "relation_type_group"},
new String[]{"", "", "", "", "", "", "COMMON"},
"tb-relations");
log.info("Relations dumped.");
@ -92,15 +98,15 @@ public class CassandraDatabaseUpgradeService implements DatabaseUpgradeService {
log.info("Restoring devices ...");
if (devicesDump != null) {
CassandraDbHelper.loadCf(ks, cluster.getSession(), "device",
new String[]{"id", "tenant_id", "customer_id", "name", "search_text", "additional_info", "type"}, devicesDump);
CassandraDbHelper.loadCf(ks, cluster.getSession(), DEVICE,
new String[]{"id", TENANT_ID, CUSTOMER_ID, "name", SEARCH_TEXT, ADDITIONAL_INFO, "type"}, devicesDump);
Files.deleteIfExists(devicesDump);
}
log.info("Devices restored.");
log.info("Dumping device types ...");
Path deviceTypesDump = CassandraDbHelper.dumpCfIfExists(ks, cluster.getSession(), "device",
new String[]{"tenant_id", "type"},
Path deviceTypesDump = CassandraDbHelper.dumpCfIfExists(ks, cluster.getSession(), DEVICE,
new String[]{TENANT_ID, "type"},
new String[]{"", ""},
"tb-device-types");
if (deviceTypesDump != null) {
@ -110,22 +116,22 @@ public class CassandraDatabaseUpgradeService implements DatabaseUpgradeService {
log.info("Loading device types ...");
if (deviceTypesDump != null) {
CassandraDbHelper.loadCf(ks, cluster.getSession(), "entity_subtype",
new String[]{"tenant_id", "type", "entity_type"}, deviceTypesDump);
new String[]{TENANT_ID, "type", "entity_type"}, deviceTypesDump);
Files.deleteIfExists(deviceTypesDump);
}
log.info("Device types loaded.");
log.info("Restoring assets ...");
if (assetsDump != null) {
CassandraDbHelper.loadCf(ks, cluster.getSession(), "asset",
new String[]{"id", "tenant_id", "customer_id", "name", "search_text", "additional_info", "type"}, assetsDump);
CassandraDbHelper.loadCf(ks, cluster.getSession(), ASSET,
new String[]{"id", TENANT_ID, CUSTOMER_ID, "name", SEARCH_TEXT, ADDITIONAL_INFO, "type"}, assetsDump);
Files.deleteIfExists(assetsDump);
}
log.info("Assets restored.");
log.info("Dumping asset types ...");
Path assetTypesDump = CassandraDbHelper.dumpCfIfExists(ks, cluster.getSession(), "asset",
new String[]{"tenant_id", "type"},
Path assetTypesDump = CassandraDbHelper.dumpCfIfExists(ks, cluster.getSession(), ASSET,
new String[]{TENANT_ID, "type"},
new String[]{"", ""},
"tb-asset-types");
if (assetTypesDump != null) {
@ -135,7 +141,7 @@ public class CassandraDatabaseUpgradeService implements DatabaseUpgradeService {
log.info("Loading asset types ...");
if (assetTypesDump != null) {
CassandraDbHelper.loadCf(ks, cluster.getSession(), "entity_subtype",
new String[]{"tenant_id", "type", "entity_type"}, assetTypesDump);
new String[]{TENANT_ID, "type", "entity_type"}, assetTypesDump);
Files.deleteIfExists(assetTypesDump);
}
log.info("Asset types loaded.");
@ -143,7 +149,7 @@ public class CassandraDatabaseUpgradeService implements DatabaseUpgradeService {
log.info("Restoring relations ...");
if (relationsDump != null) {
CassandraDbHelper.loadCf(ks, cluster.getSession(), "relation",
new String[]{"from_id", "from_type", "to_id", "to_type", "relation_type", "additional_info", "relation_type_group"}, relationsDump);
new String[]{"from_id", "from_type", "to_id", "to_type", "relation_type", ADDITIONAL_INFO, "relation_type_group"}, relationsDump);
Files.deleteIfExists(relationsDump);
}
log.info("Relations restored.");

187
application/src/main/java/org/thingsboard/server/service/install/DefaultSystemDataLoaderService.java

@ -51,6 +51,7 @@ import org.thingsboard.server.dao.widget.WidgetTypeService;
import org.thingsboard.server.dao.widget.WidgetsBundleService;
import java.io.IOException;
import java.nio.file.DirectoryStream;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
@ -69,6 +70,9 @@ public class DefaultSystemDataLoaderService implements SystemDataLoaderService {
private static final String DASHBOARDS_DIR = "dashboards";
private static final ObjectMapper objectMapper = new ObjectMapper();
public static final String JSON_EXT = ".json";
public static final String CUSTOMER_CRED = "customer";
public static final String DEFAULT_DEVICE_TYPE = "default";
@Value("${install.data_dir}")
private String dataDir;
@ -138,7 +142,7 @@ public class DefaultSystemDataLoaderService implements SystemDataLoaderService {
node.put("timeout", "10000");
node.put("enableTls", "false");
node.put("username", "");
node.put("password", "");
node.put("password", ""); //NOSONAR, key used to identify password field (not password value itself)
mailSettings.setJsonValue(node);
adminSettingsService.saveAdminSettings(mailSettings);
}
@ -146,33 +150,34 @@ public class DefaultSystemDataLoaderService implements SystemDataLoaderService {
@Override
public void loadSystemWidgets() throws Exception {
Path widgetBundlesDir = Paths.get(dataDir, JSON_DIR, SYSTEM_DIR, WIDGET_BUNDLES_DIR);
Files.newDirectoryStream(widgetBundlesDir, path -> path.toString().endsWith(".json"))
.forEach(
path -> {
try {
JsonNode widgetsBundleDescriptorJson = objectMapper.readTree(path.toFile());
JsonNode widgetsBundleJson = widgetsBundleDescriptorJson.get("widgetsBundle");
WidgetsBundle widgetsBundle = objectMapper.treeToValue(widgetsBundleJson, WidgetsBundle.class);
WidgetsBundle savedWidgetsBundle = widgetsBundleService.saveWidgetsBundle(widgetsBundle);
JsonNode widgetTypesArrayJson = widgetsBundleDescriptorJson.get("widgetTypes");
widgetTypesArrayJson.forEach(
widgetTypeJson -> {
try {
WidgetType widgetType = objectMapper.treeToValue(widgetTypeJson, WidgetType.class);
widgetType.setBundleAlias(savedWidgetsBundle.getAlias());
widgetTypeService.saveWidgetType(widgetType);
} catch (Exception e) {
log.error("Unable to load widget type from json: [{}]", path.toString());
throw new RuntimeException("Unable to load widget type from json", e);
}
try (DirectoryStream<Path> dirStream = Files.newDirectoryStream(widgetBundlesDir, path -> path.toString().endsWith(JSON_EXT))) {
dirStream.forEach(
path -> {
try {
JsonNode widgetsBundleDescriptorJson = objectMapper.readTree(path.toFile());
JsonNode widgetsBundleJson = widgetsBundleDescriptorJson.get("widgetsBundle");
WidgetsBundle widgetsBundle = objectMapper.treeToValue(widgetsBundleJson, WidgetsBundle.class);
WidgetsBundle savedWidgetsBundle = widgetsBundleService.saveWidgetsBundle(widgetsBundle);
JsonNode widgetTypesArrayJson = widgetsBundleDescriptorJson.get("widgetTypes");
widgetTypesArrayJson.forEach(
widgetTypeJson -> {
try {
WidgetType widgetType = objectMapper.treeToValue(widgetTypeJson, WidgetType.class);
widgetType.setBundleAlias(savedWidgetsBundle.getAlias());
widgetTypeService.saveWidgetType(widgetType);
} catch (Exception e) {
log.error("Unable to load widget type from json: [{}]", path.toString());
throw new RuntimeException("Unable to load widget type from json", e);
}
);
} catch (Exception e) {
log.error("Unable to load widgets bundle from json: [{}]", path.toString());
throw new RuntimeException("Unable to load widgets bundle from json", e);
}
}
);
} catch (Exception e) {
log.error("Unable to load widgets bundle from json: [{}]", path.toString());
throw new RuntimeException("Unable to load widgets bundle from json", e);
}
);
}
);
}
}
@Override
@ -206,21 +211,21 @@ public class DefaultSystemDataLoaderService implements SystemDataLoaderService {
customerC.setTenantId(demoTenant.getId());
customerC.setTitle("Customer C");
customerC = customerService.saveCustomer(customerC);
createUser(Authority.CUSTOMER_USER, demoTenant.getId(), customerA.getId(), "customer@thingsboard.org", "customer");
createUser(Authority.CUSTOMER_USER, demoTenant.getId(), customerA.getId(), "customerA@thingsboard.org", "customer");
createUser(Authority.CUSTOMER_USER, demoTenant.getId(), customerB.getId(), "customerB@thingsboard.org", "customer");
createUser(Authority.CUSTOMER_USER, demoTenant.getId(), customerC.getId(), "customerC@thingsboard.org", "customer");
createDevice(demoTenant.getId(), customerA.getId(), "default", "Test Device A1", "A1_TEST_TOKEN", null);
createDevice(demoTenant.getId(), customerA.getId(), "default", "Test Device A2", "A2_TEST_TOKEN", null);
createDevice(demoTenant.getId(), customerA.getId(), "default", "Test Device A3", "A3_TEST_TOKEN", null);
createDevice(demoTenant.getId(), customerB.getId(), "default", "Test Device B1", "B1_TEST_TOKEN", null);
createDevice(demoTenant.getId(), customerC.getId(), "default", "Test Device C1", "C1_TEST_TOKEN", null);
createDevice(demoTenant.getId(), null, "default", "DHT11 Demo Device", "DHT11_DEMO_TOKEN", "Demo device that is used in sample " +
createUser(Authority.CUSTOMER_USER, demoTenant.getId(), customerA.getId(), "customer@thingsboard.org", CUSTOMER_CRED);
createUser(Authority.CUSTOMER_USER, demoTenant.getId(), customerA.getId(), "customerA@thingsboard.org", CUSTOMER_CRED);
createUser(Authority.CUSTOMER_USER, demoTenant.getId(), customerB.getId(), "customerB@thingsboard.org", CUSTOMER_CRED);
createUser(Authority.CUSTOMER_USER, demoTenant.getId(), customerC.getId(), "customerC@thingsboard.org", CUSTOMER_CRED);
createDevice(demoTenant.getId(), customerA.getId(), DEFAULT_DEVICE_TYPE, "Test Device A1", "A1_TEST_TOKEN", null);
createDevice(demoTenant.getId(), customerA.getId(), DEFAULT_DEVICE_TYPE, "Test Device A2", "A2_TEST_TOKEN", null);
createDevice(demoTenant.getId(), customerA.getId(), DEFAULT_DEVICE_TYPE, "Test Device A3", "A3_TEST_TOKEN", null);
createDevice(demoTenant.getId(), customerB.getId(), DEFAULT_DEVICE_TYPE, "Test Device B1", "B1_TEST_TOKEN", null);
createDevice(demoTenant.getId(), customerC.getId(), DEFAULT_DEVICE_TYPE, "Test Device C1", "C1_TEST_TOKEN", null);
createDevice(demoTenant.getId(), null, DEFAULT_DEVICE_TYPE, "DHT11 Demo Device", "DHT11_DEMO_TOKEN", "Demo device that is used in sample " +
"applications that upload data from DHT11 temperature and humidity sensor");
createDevice(demoTenant.getId(), null, "default", "Raspberry Pi Demo Device", "RASPBERRY_PI_DEMO_TOKEN", "Demo device that is used in " +
createDevice(demoTenant.getId(), null, DEFAULT_DEVICE_TYPE, "Raspberry Pi Demo Device", "RASPBERRY_PI_DEMO_TOKEN", "Demo device that is used in " +
"Raspberry Pi GPIO control sample application");
loadPlugins(Paths.get(dataDir, JSON_DIR, DEMO_DIR, PLUGINS_DIR), demoTenant.getId());
@ -279,67 +284,69 @@ public class DefaultSystemDataLoaderService implements SystemDataLoaderService {
}
private void loadPlugins(Path pluginsDir, TenantId tenantId) throws Exception{
Files.newDirectoryStream(pluginsDir, path -> path.toString().endsWith(".json"))
.forEach(
path -> {
try {
JsonNode pluginJson = objectMapper.readTree(path.toFile());
PluginMetaData plugin = objectMapper.treeToValue(pluginJson, PluginMetaData.class);
plugin.setTenantId(tenantId);
if (plugin.getState() == ComponentLifecycleState.ACTIVE) {
plugin.setState(ComponentLifecycleState.SUSPENDED);
PluginMetaData savedPlugin = pluginService.savePlugin(plugin);
pluginService.activatePluginById(savedPlugin.getId());
} else {
pluginService.savePlugin(plugin);
}
} catch (Exception e) {
log.error("Unable to load plugin from json: [{}]", path.toString());
throw new RuntimeException("Unable to load plugin from json", e);
try (DirectoryStream<Path> dirStream = Files.newDirectoryStream(pluginsDir, path -> path.toString().endsWith(JSON_EXT))) {
dirStream.forEach(
path -> {
try {
JsonNode pluginJson = objectMapper.readTree(path.toFile());
PluginMetaData plugin = objectMapper.treeToValue(pluginJson, PluginMetaData.class);
plugin.setTenantId(tenantId);
if (plugin.getState() == ComponentLifecycleState.ACTIVE) {
plugin.setState(ComponentLifecycleState.SUSPENDED);
PluginMetaData savedPlugin = pluginService.savePlugin(plugin);
pluginService.activatePluginById(savedPlugin.getId());
} else {
pluginService.savePlugin(plugin);
}
} catch (Exception e) {
log.error("Unable to load plugin from json: [{}]", path.toString());
throw new RuntimeException("Unable to load plugin from json", e);
}
);
}
);
}
}
private void loadRules(Path rulesDir, TenantId tenantId) throws Exception {
Files.newDirectoryStream(rulesDir, path -> path.toString().endsWith(".json"))
.forEach(
path -> {
try {
JsonNode ruleJson = objectMapper.readTree(path.toFile());
RuleMetaData rule = objectMapper.treeToValue(ruleJson, RuleMetaData.class);
rule.setTenantId(tenantId);
if (rule.getState() == ComponentLifecycleState.ACTIVE) {
rule.setState(ComponentLifecycleState.SUSPENDED);
RuleMetaData savedRule = ruleService.saveRule(rule);
ruleService.activateRuleById(savedRule.getId());
} else {
ruleService.saveRule(rule);
}
} catch (Exception e) {
log.error("Unable to load rule from json: [{}]", path.toString());
throw new RuntimeException("Unable to load rule from json", e);
try (DirectoryStream<Path> dirStream = Files.newDirectoryStream(rulesDir, path -> path.toString().endsWith(JSON_EXT))) {
dirStream.forEach(
path -> {
try {
JsonNode ruleJson = objectMapper.readTree(path.toFile());
RuleMetaData rule = objectMapper.treeToValue(ruleJson, RuleMetaData.class);
rule.setTenantId(tenantId);
if (rule.getState() == ComponentLifecycleState.ACTIVE) {
rule.setState(ComponentLifecycleState.SUSPENDED);
RuleMetaData savedRule = ruleService.saveRule(rule);
ruleService.activateRuleById(savedRule.getId());
} else {
ruleService.saveRule(rule);
}
} catch (Exception e) {
log.error("Unable to load rule from json: [{}]", path.toString());
throw new RuntimeException("Unable to load rule from json", e);
}
);
}
);
}
}
private void loadDashboards(Path dashboardsDir, TenantId tenantId, CustomerId customerId) throws Exception {
Files.newDirectoryStream(dashboardsDir, path -> path.toString().endsWith(".json"))
.forEach(
path -> {
try {
JsonNode dashboardJson = objectMapper.readTree(path.toFile());
Dashboard dashboard = objectMapper.treeToValue(dashboardJson, Dashboard.class);
dashboard.setTenantId(tenantId);
dashboard.setCustomerId(customerId);
dashboardService.saveDashboard(dashboard);
} catch (Exception e) {
log.error("Unable to load dashboard from json: [{}]", path.toString());
throw new RuntimeException("Unable to load dashboard from json", e);
}
try (DirectoryStream<Path> dirStream = Files.newDirectoryStream(dashboardsDir, path -> path.toString().endsWith(JSON_EXT))) {
dirStream.forEach(
path -> {
try {
JsonNode dashboardJson = objectMapper.readTree(path.toFile());
Dashboard dashboard = objectMapper.treeToValue(dashboardJson, Dashboard.class);
dashboard.setTenantId(tenantId);
dashboard.setCustomerId(customerId);
dashboardService.saveDashboard(dashboard);
} catch (Exception e) {
log.error("Unable to load dashboard from json: [{}]", path.toString());
throw new RuntimeException("Unable to load dashboard from json", e);
}
);
}
);
}
}
}

3
application/src/main/java/org/thingsboard/server/service/install/SqlDatabaseSchemaService.java

@ -28,6 +28,7 @@ import java.nio.file.Path;
import java.nio.file.Paths;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
@Service
@Profile("install")
@ -58,7 +59,7 @@ public class SqlDatabaseSchemaService implements DatabaseSchemaService {
Path schemaFile = Paths.get(this.dataDir, SQL_DIR, SCHEMA_SQL);
try (Connection conn = DriverManager.getConnection(dbUrl, dbUserName, dbPassword)) {
String sql = new String(Files.readAllBytes(schemaFile), Charset.forName("UTF-8"));
conn.createStatement().execute(sql);
conn.prepareStatement(sql).execute(); //NOSONAR, ignoring because method used to load initial thingsboard database schema
}
}

91
application/src/main/java/org/thingsboard/server/service/install/cql/CQLStatementsParser.java

@ -44,7 +44,7 @@ public class CQLStatementsParser {
public CQLStatementsParser(Path cql) throws IOException {
try {
List<String> lines = Files.readAllLines(cql);
StringBuffer t = new StringBuffer();
StringBuilder t = new StringBuilder();
for (String l : lines) {
t.append(l.trim());
t.append('\n');
@ -68,36 +68,14 @@ public class CQLStatementsParser {
private void parseStatements() {
this.statements = new ArrayList<>();
StringBuffer statementUnderConstruction = new StringBuffer();
StringBuilder statementUnderConstruction = new StringBuilder();
char c;
while ((c = getChar()) != 0) {
switch (state) {
case DEFAULT:
if (c == '/' && peekAhead() == '/') {
state = State.INSINGLELINECOMMENT;
advance();
} else if (c == '-' && peekAhead() == '-') {
state = State.INSINGLELINECOMMENT;
advance();
} else if (c == '/' && peekAhead() == '*') {
state = State.INMULTILINECOMMENT;
advance();
} else if (c == '\n') {
statementUnderConstruction.append(' ');
} else {
statementUnderConstruction.append(c);
if (c == '\"') {
state = State.INQUOTESTRING;
} else if (c == '\'') {
state = State.INSQUOTESTRING;
} else if (c == ';') {
statements.add(statementUnderConstruction.toString().trim());
statementUnderConstruction.setLength(0);
}
}
processDefaultState(c, statementUnderConstruction);
break;
case INSINGLELINECOMMENT:
if (c == '\n') {
state = State.DEFAULT;
@ -112,25 +90,10 @@ public class CQLStatementsParser {
break;
case INQUOTESTRING:
statementUnderConstruction.append(c);
if (c == '"') {
if (peekAhead() == '"') {
statementUnderConstruction.append(getChar());
} else {
state = State.DEFAULT;
}
}
processInQuoteStringState(c, statementUnderConstruction);
break;
case INSQUOTESTRING:
statementUnderConstruction.append(c);
if (c == '\'') {
if (peekAhead() == '\'') {
statementUnderConstruction.append(getChar());
} else {
state = State.DEFAULT;
}
}
processInSQuoteStringState(c, statementUnderConstruction);
break;
}
@ -141,6 +104,50 @@ public class CQLStatementsParser {
}
}
private void processDefaultState(char c, StringBuilder statementUnderConstruction) {
if ((c == '/' && peekAhead() == '/') || (c == '-' && peekAhead() == '-')) {
state = State.INSINGLELINECOMMENT;
advance();
} else if (c == '/' && peekAhead() == '*') {
state = State.INMULTILINECOMMENT;
advance();
} else if (c == '\n') {
statementUnderConstruction.append(' ');
} else {
statementUnderConstruction.append(c);
if (c == '\"') {
state = State.INQUOTESTRING;
} else if (c == '\'') {
state = State.INSQUOTESTRING;
} else if (c == ';') {
statements.add(statementUnderConstruction.toString().trim());
statementUnderConstruction.setLength(0);
}
}
}
private void processInQuoteStringState(char c, StringBuilder statementUnderConstruction) {
statementUnderConstruction.append(c);
if (c == '"') {
if (peekAhead() == '"') {
statementUnderConstruction.append(getChar());
} else {
state = State.DEFAULT;
}
}
}
private void processInSQuoteStringState(char c, StringBuilder statementUnderConstruction) {
statementUnderConstruction.append(c);
if (c == '\'') {
if (peekAhead() == '\'') {
statementUnderConstruction.append(getChar());
} else {
state = State.DEFAULT;
}
}
}
private char getChar() {
if (pos < text.length())
return text.charAt(pos++);

35
application/src/main/java/org/thingsboard/server/service/mail/DefaultMailService.java

@ -44,6 +44,9 @@ import java.util.Properties;
@Slf4j
public class DefaultMailService implements MailService {
public static final String MAIL_PROP = "mail.";
public static final String TARGET_EMAIL = "targetEmail";
public static final String UTF_8 = "UTF-8";
@Autowired
private MessageSource messages;
@ -89,11 +92,11 @@ public class DefaultMailService implements MailService {
Properties javaMailProperties = new Properties();
String protocol = jsonConfig.get("smtpProtocol").asText();
javaMailProperties.put("mail.transport.protocol", protocol);
javaMailProperties.put("mail." + protocol + ".host", jsonConfig.get("smtpHost").asText());
javaMailProperties.put("mail." + protocol + ".port", jsonConfig.get("smtpPort").asText());
javaMailProperties.put("mail." + protocol + ".timeout", jsonConfig.get("timeout").asText());
javaMailProperties.put("mail." + protocol + ".auth", String.valueOf(StringUtils.isNotEmpty(jsonConfig.get("username").asText())));
javaMailProperties.put("mail." + protocol + ".starttls.enable", jsonConfig.get("enableTls"));
javaMailProperties.put(MAIL_PROP + protocol + ".host", jsonConfig.get("smtpHost").asText());
javaMailProperties.put(MAIL_PROP + protocol + ".port", jsonConfig.get("smtpPort").asText());
javaMailProperties.put(MAIL_PROP + protocol + ".timeout", jsonConfig.get("timeout").asText());
javaMailProperties.put(MAIL_PROP + protocol + ".auth", String.valueOf(StringUtils.isNotEmpty(jsonConfig.get("username").asText())));
javaMailProperties.put(MAIL_PROP + protocol + ".starttls.enable", jsonConfig.get("enableTls"));
return javaMailProperties;
}
@ -117,10 +120,10 @@ public class DefaultMailService implements MailService {
String subject = messages.getMessage("test.message.subject", null, Locale.US);
Map<String, Object> model = new HashMap<String, Object>();
model.put("targetEmail", email);
model.put(TARGET_EMAIL, email);
String message = VelocityEngineUtils.mergeTemplateIntoString(this.engine,
"test.vm", "UTF-8", model);
"test.vm", UTF_8, model);
sendMail(testMailSender, mailFrom, email, subject, message);
}
@ -132,10 +135,10 @@ public class DefaultMailService implements MailService {
Map<String, Object> model = new HashMap<String, Object>();
model.put("activationLink", activationLink);
model.put("targetEmail", email);
model.put(TARGET_EMAIL, email);
String message = VelocityEngineUtils.mergeTemplateIntoString(this.engine,
"activation.vm", "UTF-8", model);
"activation.vm", UTF_8, model);
sendMail(mailSender, mailFrom, email, subject, message);
}
@ -147,10 +150,10 @@ public class DefaultMailService implements MailService {
Map<String, Object> model = new HashMap<String, Object>();
model.put("loginLink", loginLink);
model.put("targetEmail", email);
model.put(TARGET_EMAIL, email);
String message = VelocityEngineUtils.mergeTemplateIntoString(this.engine,
"account.activated.vm", "UTF-8", model);
"account.activated.vm", UTF_8, model);
sendMail(mailSender, mailFrom, email, subject, message);
}
@ -162,10 +165,10 @@ public class DefaultMailService implements MailService {
Map<String, Object> model = new HashMap<String, Object>();
model.put("passwordResetLink", passwordResetLink);
model.put("targetEmail", email);
model.put(TARGET_EMAIL, email);
String message = VelocityEngineUtils.mergeTemplateIntoString(this.engine,
"reset.password.vm", "UTF-8", model);
"reset.password.vm", UTF_8, model);
sendMail(mailSender, mailFrom, email, subject, message);
}
@ -177,10 +180,10 @@ public class DefaultMailService implements MailService {
Map<String, Object> model = new HashMap<String, Object>();
model.put("loginLink", loginLink);
model.put("targetEmail", email);
model.put(TARGET_EMAIL, email);
String message = VelocityEngineUtils.mergeTemplateIntoString(this.engine,
"password.was.reset.vm", "UTF-8", model);
"password.was.reset.vm", UTF_8, model);
sendMail(mailSender, mailFrom, email, subject, message);
}
@ -191,7 +194,7 @@ public class DefaultMailService implements MailService {
String subject, String message) throws ThingsboardException {
try {
MimeMessage mimeMsg = mailSender.createMimeMessage();
MimeMessageHelper helper = new MimeMessageHelper(mimeMsg, "UTF-8");
MimeMessageHelper helper = new MimeMessageHelper(mimeMsg, UTF_8);
helper.setFrom(mailFrom);
helper.setTo(email);
helper.setSubject(subject);

7
application/src/main/java/org/thingsboard/server/service/security/auth/jwt/RefreshTokenProcessingFilter.java

@ -16,6 +16,7 @@
package org.thingsboard.server.service.security.auth.jwt;
import com.fasterxml.jackson.databind.ObjectMapper;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
@ -37,8 +38,8 @@ import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
@Slf4j
public class RefreshTokenProcessingFilter extends AbstractAuthenticationProcessingFilter {
private static Logger logger = LoggerFactory.getLogger(RefreshTokenProcessingFilter.class);
private final AuthenticationSuccessHandler successHandler;
private final AuthenticationFailureHandler failureHandler;
@ -57,8 +58,8 @@ public class RefreshTokenProcessingFilter extends AbstractAuthenticationProcessi
public Authentication attemptAuthentication(HttpServletRequest request, HttpServletResponse response)
throws AuthenticationException, IOException, ServletException {
if (!HttpMethod.POST.name().equals(request.getMethod())) {
if(logger.isDebugEnabled()) {
logger.debug("Authentication method not supported. Request method: " + request.getMethod());
if(log.isDebugEnabled()) {
log.debug("Authentication method not supported. Request method: " + request.getMethod());
}
throw new AuthMethodNotSupportedException("Authentication method not supported");
}

2
application/src/main/java/org/thingsboard/server/service/security/auth/jwt/extractor/JwtHeaderTokenExtractor.java

@ -24,7 +24,7 @@ import javax.servlet.http.HttpServletRequest;
@Component(value="jwtHeaderTokenExtractor")
public class JwtHeaderTokenExtractor implements TokenExtractor {
public static String HEADER_PREFIX = "Bearer ";
public static final String HEADER_PREFIX = "Bearer ";
@Override
public String extract(HttpServletRequest request) {

7
application/src/main/java/org/thingsboard/server/service/security/auth/rest/RestLoginProcessingFilter.java

@ -16,6 +16,7 @@
package org.thingsboard.server.service.security.auth.rest;
import com.fasterxml.jackson.databind.ObjectMapper;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
@ -37,8 +38,8 @@ import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
@Slf4j
public class RestLoginProcessingFilter extends AbstractAuthenticationProcessingFilter {
private static Logger logger = LoggerFactory.getLogger(RestLoginProcessingFilter.class);
private final AuthenticationSuccessHandler successHandler;
private final AuthenticationFailureHandler failureHandler;
@ -57,8 +58,8 @@ public class RestLoginProcessingFilter extends AbstractAuthenticationProcessingF
public Authentication attemptAuthentication(HttpServletRequest request, HttpServletResponse response)
throws AuthenticationException, IOException, ServletException {
if (!HttpMethod.POST.name().equals(request.getMethod())) {
if(logger.isDebugEnabled()) {
logger.debug("Authentication method not supported. Request method: " + request.getMethod());
if(log.isDebugEnabled()) {
log.debug("Authentication method not supported. Request method: " + request.getMethod());
}
throw new AuthMethodNotSupportedException("Authentication method not supported");
}

7
application/src/main/java/org/thingsboard/server/service/security/auth/rest/RestPublicLoginProcessingFilter.java

@ -16,6 +16,7 @@
package org.thingsboard.server.service.security.auth.rest;
import com.fasterxml.jackson.databind.ObjectMapper;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
@ -37,8 +38,8 @@ import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
@Slf4j
public class RestPublicLoginProcessingFilter extends AbstractAuthenticationProcessingFilter {
private static Logger logger = LoggerFactory.getLogger(RestPublicLoginProcessingFilter.class);
private final AuthenticationSuccessHandler successHandler;
private final AuthenticationFailureHandler failureHandler;
@ -57,8 +58,8 @@ public class RestPublicLoginProcessingFilter extends AbstractAuthenticationProce
public Authentication attemptAuthentication(HttpServletRequest request, HttpServletResponse response)
throws AuthenticationException, IOException, ServletException {
if (!HttpMethod.POST.name().equals(request.getMethod())) {
if(logger.isDebugEnabled()) {
logger.debug("Authentication method not supported. Request method: " + request.getMethod());
if(log.isDebugEnabled()) {
log.debug("Authentication method not supported. Request method: " + request.getMethod());
}
throw new AuthMethodNotSupportedException("Authentication method not supported");
}

2
application/src/main/java/org/thingsboard/server/service/security/model/SecurityUser.java

@ -46,7 +46,7 @@ public class SecurityUser extends User {
this.userPrincipal = userPrincipal;
}
public Collection<? extends GrantedAuthority> getAuthorities() {
public Collection<GrantedAuthority> getAuthorities() {
if (authorities == null) {
authorities = Stream.of(SecurityUser.this.getAuthority())
.map(authority -> new SimpleGrantedAuthority(authority.name()))

4
application/src/main/java/org/thingsboard/server/service/security/model/UserPrincipal.java

@ -16,7 +16,9 @@
package org.thingsboard.server.service.security.model;
public class UserPrincipal {
import java.io.Serializable;
public class UserPrincipal implements Serializable {
private final Type type;
private final String value;

2
application/src/main/java/org/thingsboard/server/service/security/model/token/AccessJwtToken.java

@ -21,7 +21,7 @@ import io.jsonwebtoken.Claims;
public final class AccessJwtToken implements JwtToken {
private final String rawToken;
@JsonIgnore
private Claims claims;
private transient Claims claims;
protected AccessJwtToken(final String token, Claims claims) {
this.rawToken = token;

4
application/src/main/java/org/thingsboard/server/service/security/model/token/JwtToken.java

@ -15,6 +15,8 @@
*/
package org.thingsboard.server.service.security.model.token;
public interface JwtToken {
import java.io.Serializable;
public interface JwtToken extends Serializable {
String getToken();
}

7
application/src/main/java/org/thingsboard/server/service/security/model/token/RawAccessJwtToken.java

@ -21,7 +21,12 @@ import org.slf4j.LoggerFactory;
import org.springframework.security.authentication.BadCredentialsException;
import org.thingsboard.server.service.security.exception.JwtExpiredTokenException;
public class RawAccessJwtToken implements JwtToken {
import java.io.Serializable;
public class RawAccessJwtToken implements JwtToken, Serializable {
private static final long serialVersionUID = -797397445703066079L;
private static Logger logger = LoggerFactory.getLogger(RawAccessJwtToken.class);
private String token;

75
application/src/main/java/org/thingsboard/server/service/update/DefaultUpdateService.java

@ -27,6 +27,7 @@ import org.thingsboard.server.service.update.model.UpdateMessage;
import javax.annotation.PostConstruct;
import javax.annotation.PreDestroy;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
@ -71,25 +72,34 @@ public class DefaultUpdateService implements UpdateService {
if (version == null) {
version = "unknown";
}
Path instanceIdPath = Paths.get(INSTANCE_ID_FILE);
if (Files.exists(instanceIdPath)) {
byte[] data = Files.readAllBytes(instanceIdPath);
if (data != null && data.length > 0) {
try {
instanceId = UUID.fromString(new String(data));
} catch (IllegalArgumentException e) {
}
}
}
if (instanceId == null) {
instanceId = UUID.randomUUID();
Files.write(instanceIdPath, instanceId.toString().getBytes());
}
instanceId = parseInstanceId();
checkUpdatesFuture = scheduler.scheduleAtFixedRate(checkUpdatesRunnable, 0, 1, TimeUnit.HOURS);
} catch (Exception e) {}
} catch (Exception e) {
//Do nothing
}
}
}
private UUID parseInstanceId() throws IOException {
UUID result = null;
Path instanceIdPath = Paths.get(INSTANCE_ID_FILE);
if (instanceIdPath.toFile().exists()) {
byte[] data = Files.readAllBytes(instanceIdPath);
if (data != null && data.length > 0) {
try {
result = UUID.fromString(new String(data));
} catch (IllegalArgumentException e) {
//Do nothing
}
}
}
if (result == null) {
result = UUID.randomUUID();
Files.write(instanceIdPath, result.toString().getBytes());
}
return result;
}
@PreDestroy
private void destroy() {
try {
@ -97,26 +107,25 @@ public class DefaultUpdateService implements UpdateService {
checkUpdatesFuture.cancel(true);
}
scheduler.shutdownNow();
} catch (Exception e) {}
} catch (Exception e) {
//Do nothing
}
}
Runnable checkUpdatesRunnable = new Runnable() {
@Override
public void run() {
try {
log.trace("Executing check update method for instanceId [{}], platform [{}] and version [{}]", instanceId, platform, version);
ObjectNode request = new ObjectMapper().createObjectNode();
request.put(PLATFORM_PARAM, platform);
request.put(VERSION_PARAM, version);
request.put(INSTANCE_ID_PARAM, instanceId.toString());
JsonNode response = restClient.postForObject(UPDATE_SERVER_BASE_URL+"/api/thingsboard/updates", request, JsonNode.class);
updateMessage = new UpdateMessage(
response.get("message").asText(),
response.get("updateAvailable").asBoolean()
);
} catch (Exception e) {
log.trace(e.getMessage());
}
Runnable checkUpdatesRunnable = () -> {
try {
log.trace("Executing check update method for instanceId [{}], platform [{}] and version [{}]", instanceId, platform, version);
ObjectNode request = new ObjectMapper().createObjectNode();
request.put(PLATFORM_PARAM, platform);
request.put(VERSION_PARAM, version);
request.put(INSTANCE_ID_PARAM, instanceId.toString());
JsonNode response = restClient.postForObject(UPDATE_SERVER_BASE_URL+"/api/thingsboard/updates", request, JsonNode.class);
updateMessage = new UpdateMessage(
response.get("message").asText(),
response.get("updateAvailable").asBoolean()
);
} catch (Exception e) {
log.trace(e.getMessage());
}
};

2
common/data/src/main/java/org/thingsboard/server/common/data/AdminSettings.java

@ -24,7 +24,7 @@ public class AdminSettings extends BaseData<AdminSettingsId> {
private static final long serialVersionUID = -7670322981725511892L;
private String key;
private JsonNode jsonValue;
private transient JsonNode jsonValue;
public AdminSettings() {
super();

70
common/data/src/main/java/org/thingsboard/server/common/data/ContactBased.java

@ -15,8 +15,10 @@
*/
package org.thingsboard.server.common.data;
import lombok.EqualsAndHashCode;
import org.thingsboard.server.common.data.id.UUIDBased;
@EqualsAndHashCode(callSuper = true)
public abstract class ContactBased<I extends UUIDBased> extends SearchTextBased<I> {
private static final long serialVersionUID = 5047448057830660988L;
@ -114,72 +116,4 @@ public abstract class ContactBased<I extends UUIDBased> extends SearchTextBased<
this.email = email;
}
@Override
public int hashCode() {
final int prime = 31;
int result = super.hashCode();
result = prime * result + ((address == null) ? 0 : address.hashCode());
result = prime * result + ((address2 == null) ? 0 : address2.hashCode());
result = prime * result + ((city == null) ? 0 : city.hashCode());
result = prime * result + ((country == null) ? 0 : country.hashCode());
result = prime * result + ((email == null) ? 0 : email.hashCode());
result = prime * result + ((phone == null) ? 0 : phone.hashCode());
result = prime * result + ((state == null) ? 0 : state.hashCode());
result = prime * result + ((zip == null) ? 0 : zip.hashCode());
return result;
}
@SuppressWarnings("rawtypes")
@Override
public boolean equals(Object obj) {
if (this == obj)
return true;
if (!super.equals(obj))
return false;
if (getClass() != obj.getClass())
return false;
ContactBased other = (ContactBased) obj;
if (address == null) {
if (other.address != null)
return false;
} else if (!address.equals(other.address))
return false;
if (address2 == null) {
if (other.address2 != null)
return false;
} else if (!address2.equals(other.address2))
return false;
if (city == null) {
if (other.city != null)
return false;
} else if (!city.equals(other.city))
return false;
if (country == null) {
if (other.country != null)
return false;
} else if (!country.equals(other.country))
return false;
if (email == null) {
if (other.email != null)
return false;
} else if (!email.equals(other.email))
return false;
if (phone == null) {
if (other.phone != null)
return false;
} else if (!phone.equals(other.phone))
return false;
if (state == null) {
if (other.state != null)
return false;
} else if (!state.equals(other.state))
return false;
if (zip == null) {
if (other.zip != null)
return false;
} else if (!zip.equals(other.zip))
return false;
return true;
}
}

4
common/data/src/main/java/org/thingsboard/server/common/data/Customer.java

@ -29,7 +29,7 @@ public class Customer extends ContactBased<CustomerId> implements HasName {
private String title;
private TenantId tenantId;
private JsonNode additionalInfo;
private transient JsonNode additionalInfo;
public Customer() {
super();
@ -87,7 +87,7 @@ public class Customer extends ContactBased<CustomerId> implements HasName {
@Override
public String getSearchText() {
return title;
return getTitle();
}
@Override

2
common/data/src/main/java/org/thingsboard/server/common/data/Dashboard.java

@ -22,7 +22,7 @@ public class Dashboard extends DashboardInfo {
private static final long serialVersionUID = 872682138346187503L;
private JsonNode configuration;
private transient JsonNode configuration;
public Dashboard() {
super();

2
common/data/src/main/java/org/thingsboard/server/common/data/DashboardInfo.java

@ -73,7 +73,7 @@ public class DashboardInfo extends SearchTextBased<DashboardId> implements HasNa
@Override
public String getSearchText() {
return title;
return getTitle();
}
@Override

4
common/data/src/main/java/org/thingsboard/server/common/data/DataConstants.java

@ -29,7 +29,9 @@ public class DataConstants {
public static final String SERVER_SCOPE = "SERVER_SCOPE";
public static final String SHARED_SCOPE = "SHARED_SCOPE";
public static final String[] ALL_SCOPES = {CLIENT_SCOPE, SHARED_SCOPE, SERVER_SCOPE};
public static final String[] allScopes() {
return new String[]{CLIENT_SCOPE, SHARED_SCOPE, SERVER_SCOPE};
}
public static final String ALARM = "ALARM";
public static final String ERROR = "ERROR";

55
common/data/src/main/java/org/thingsboard/server/common/data/Device.java

@ -15,12 +15,14 @@
*/
package org.thingsboard.server.common.data;
import lombok.EqualsAndHashCode;
import org.thingsboard.server.common.data.id.CustomerId;
import org.thingsboard.server.common.data.id.DeviceId;
import org.thingsboard.server.common.data.id.TenantId;
import com.fasterxml.jackson.databind.JsonNode;
@EqualsAndHashCode(callSuper = true)
public class Device extends SearchTextBased<DeviceId> implements HasName {
private static final long serialVersionUID = 2807343040519543363L;
@ -29,7 +31,7 @@ public class Device extends SearchTextBased<DeviceId> implements HasName {
private CustomerId customerId;
private String name;
private String type;
private JsonNode additionalInfo;
private transient JsonNode additionalInfo;
public Device() {
super();
@ -91,56 +93,7 @@ public class Device extends SearchTextBased<DeviceId> implements HasName {
@Override
public String getSearchText() {
return name;
}
@Override
public int hashCode() {
final int prime = 31;
int result = super.hashCode();
result = prime * result + ((additionalInfo == null) ? 0 : additionalInfo.hashCode());
result = prime * result + ((customerId == null) ? 0 : customerId.hashCode());
result = prime * result + ((name == null) ? 0 : name.hashCode());
result = prime * result + ((type == null) ? 0 : type.hashCode());
result = prime * result + ((tenantId == null) ? 0 : tenantId.hashCode());
return result;
}
@Override
public boolean equals(Object obj) {
if (this == obj)
return true;
if (!super.equals(obj))
return false;
if (getClass() != obj.getClass())
return false;
Device other = (Device) obj;
if (additionalInfo == null) {
if (other.additionalInfo != null)
return false;
} else if (!additionalInfo.equals(other.additionalInfo))
return false;
if (customerId == null) {
if (other.customerId != null)
return false;
} else if (!customerId.equals(other.customerId))
return false;
if (name == null) {
if (other.name != null)
return false;
} else if (!name.equals(other.name))
return false;
if (type == null) {
if (other.type != null)
return false;
} else if (!type.equals(other.type))
return false;
if (tenantId == null) {
if (other.tenantId != null)
return false;
} else if (!tenantId.equals(other.tenantId))
return false;
return true;
return getName();
}
@Override

2
common/data/src/main/java/org/thingsboard/server/common/data/Event.java

@ -31,7 +31,7 @@ public class Event extends BaseData<EventId> {
private String type;
private String uid;
private EntityId entityId;
private JsonNode body;
private transient JsonNode body;
public Event() {
super();

43
common/data/src/main/java/org/thingsboard/server/common/data/Tenant.java

@ -16,17 +16,19 @@
package org.thingsboard.server.common.data;
import com.fasterxml.jackson.annotation.JsonProperty;
import lombok.EqualsAndHashCode;
import org.thingsboard.server.common.data.id.TenantId;
import com.fasterxml.jackson.databind.JsonNode;
@EqualsAndHashCode(callSuper = true)
public class Tenant extends ContactBased<TenantId> implements HasName {
private static final long serialVersionUID = 8057243243859922101L;
private String title;
private String region;
private JsonNode additionalInfo;
private transient JsonNode additionalInfo;
public Tenant() {
super();
@ -75,44 +77,7 @@ public class Tenant extends ContactBased<TenantId> implements HasName {
@Override
public String getSearchText() {
return title;
}
@Override
public int hashCode() {
final int prime = 31;
int result = super.hashCode();
result = prime * result + ((additionalInfo == null) ? 0 : additionalInfo.hashCode());
result = prime * result + ((region == null) ? 0 : region.hashCode());
result = prime * result + ((title == null) ? 0 : title.hashCode());
return result;
}
@Override
public boolean equals(Object obj) {
if (this == obj)
return true;
if (!super.equals(obj))
return false;
if (getClass() != obj.getClass())
return false;
Tenant other = (Tenant) obj;
if (additionalInfo == null) {
if (other.additionalInfo != null)
return false;
} else if (!additionalInfo.equals(other.additionalInfo))
return false;
if (region == null) {
if (other.region != null)
return false;
} else if (!region.equals(other.region))
return false;
if (title == null) {
if (other.title != null)
return false;
} else if (!title.equals(other.title))
return false;
return true;
return getTitle();
}
@Override

64
common/data/src/main/java/org/thingsboard/server/common/data/User.java

@ -16,6 +16,7 @@
package org.thingsboard.server.common.data;
import com.fasterxml.jackson.annotation.JsonProperty;
import lombok.EqualsAndHashCode;
import org.thingsboard.server.common.data.id.CustomerId;
import org.thingsboard.server.common.data.id.TenantId;
import org.thingsboard.server.common.data.id.UserId;
@ -23,6 +24,7 @@ import org.thingsboard.server.common.data.security.Authority;
import com.fasterxml.jackson.databind.JsonNode;
@EqualsAndHashCode(callSuper = true)
public class User extends SearchTextBased<UserId> implements HasName {
private static final long serialVersionUID = 8250339805336035966L;
@ -33,7 +35,7 @@ public class User extends SearchTextBased<UserId> implements HasName {
private Authority authority;
private String firstName;
private String lastName;
private JsonNode additionalInfo;
private transient JsonNode additionalInfo;
public User() {
super();
@ -118,65 +120,7 @@ public class User extends SearchTextBased<UserId> implements HasName {
@Override
public String getSearchText() {
return email;
}
@Override
public int hashCode() {
final int prime = 31;
int result = super.hashCode();
result = prime * result + ((additionalInfo == null) ? 0 : additionalInfo.hashCode());
result = prime * result + ((authority == null) ? 0 : authority.hashCode());
result = prime * result + ((customerId == null) ? 0 : customerId.hashCode());
result = prime * result + ((email == null) ? 0 : email.hashCode());
result = prime * result + ((firstName == null) ? 0 : firstName.hashCode());
result = prime * result + ((lastName == null) ? 0 : lastName.hashCode());
result = prime * result + ((tenantId == null) ? 0 : tenantId.hashCode());
return result;
}
@Override
public boolean equals(Object obj) {
if (this == obj)
return true;
if (!super.equals(obj))
return false;
if (getClass() != obj.getClass())
return false;
User other = (User) obj;
if (additionalInfo == null) {
if (other.additionalInfo != null)
return false;
} else if (!additionalInfo.equals(other.additionalInfo))
return false;
if (authority != other.authority)
return false;
if (customerId == null) {
if (other.customerId != null)
return false;
} else if (!customerId.equals(other.customerId))
return false;
if (email == null) {
if (other.email != null)
return false;
} else if (!email.equals(other.email))
return false;
if (firstName == null) {
if (other.firstName != null)
return false;
} else if (!firstName.equals(other.firstName))
return false;
if (lastName == null) {
if (other.lastName != null)
return false;
} else if (!lastName.equals(other.lastName))
return false;
if (tenantId == null) {
if (other.tenantId != null)
return false;
} else if (!tenantId.equals(other.tenantId))
return false;
return true;
return getEmail();
}
@Override

2
common/data/src/main/java/org/thingsboard/server/common/data/alarm/Alarm.java

@ -42,7 +42,7 @@ public class Alarm extends BaseData<AlarmId> implements HasName {
private long endTs;
private long ackTs;
private long clearTs;
private JsonNode details;
private transient JsonNode details;
private boolean propagate;
public Alarm() {

55
common/data/src/main/java/org/thingsboard/server/common/data/asset/Asset.java

@ -16,12 +16,14 @@
package org.thingsboard.server.common.data.asset;
import com.fasterxml.jackson.databind.JsonNode;
import lombok.EqualsAndHashCode;
import org.thingsboard.server.common.data.HasName;
import org.thingsboard.server.common.data.SearchTextBased;
import org.thingsboard.server.common.data.id.AssetId;
import org.thingsboard.server.common.data.id.CustomerId;
import org.thingsboard.server.common.data.id.TenantId;
@EqualsAndHashCode(callSuper = true)
public class Asset extends SearchTextBased<AssetId> implements HasName {
private static final long serialVersionUID = 2807343040519543363L;
@ -30,7 +32,7 @@ public class Asset extends SearchTextBased<AssetId> implements HasName {
private CustomerId customerId;
private String name;
private String type;
private JsonNode additionalInfo;
private transient JsonNode additionalInfo;
public Asset() {
super();
@ -92,56 +94,7 @@ public class Asset extends SearchTextBased<AssetId> implements HasName {
@Override
public String getSearchText() {
return name;
}
@Override
public int hashCode() {
final int prime = 31;
int result = super.hashCode();
result = prime * result + ((additionalInfo == null) ? 0 : additionalInfo.hashCode());
result = prime * result + ((customerId == null) ? 0 : customerId.hashCode());
result = prime * result + ((name == null) ? 0 : name.hashCode());
result = prime * result + ((type == null) ? 0 : type.hashCode());
result = prime * result + ((tenantId == null) ? 0 : tenantId.hashCode());
return result;
}
@Override
public boolean equals(Object obj) {
if (this == obj)
return true;
if (!super.equals(obj))
return false;
if (getClass() != obj.getClass())
return false;
Asset other = (Asset) obj;
if (additionalInfo == null) {
if (other.additionalInfo != null)
return false;
} else if (!additionalInfo.equals(other.additionalInfo))
return false;
if (customerId == null) {
if (other.customerId != null)
return false;
} else if (!customerId.equals(other.customerId))
return false;
if (name == null) {
if (other.name != null)
return false;
} else if (!name.equals(other.name))
return false;
if (type == null) {
if (other.type != null)
return false;
} else if (!type.equals(other.type))
return false;
if (tenantId == null) {
if (other.tenantId != null)
return false;
} else if (!tenantId.equals(other.tenantId))
return false;
return true;
return getName();
}
@Override

3
common/data/src/main/java/org/thingsboard/server/common/data/id/EntityId.java

@ -20,6 +20,7 @@ import com.fasterxml.jackson.databind.annotation.JsonDeserialize;
import com.fasterxml.jackson.databind.annotation.JsonSerialize;
import org.thingsboard.server.common.data.EntityType;
import java.io.Serializable;
import java.util.UUID;
/**
@ -28,7 +29,7 @@ import java.util.UUID;
@JsonDeserialize(using = EntityIdDeserializer.class)
@JsonSerialize(using = EntityIdSerializer.class)
public interface EntityId {
public interface EntityId extends Serializable { //NOSONAR, the constant is closely related to EntityId
UUID NULL_UUID = UUID.fromString("13814000-1dd2-11b2-8080-808080808080");

6
common/data/src/main/java/org/thingsboard/server/common/data/page/PageDataIterable.java

@ -17,6 +17,7 @@ package org.thingsboard.server.common.data.page;
import java.util.Iterator;
import java.util.List;
import java.util.NoSuchElementException;
import org.thingsboard.server.common.data.SearchTextBased;
import org.thingsboard.server.common.data.id.UUIDBased;
@ -54,7 +55,7 @@ public class PageDataIterable<T extends SearchTextBased<? extends UUIDBased>> im
fetch(nextPackLink);
}
}
return currentIdx != currentItems.size();
return currentIdx < currentItems.size();
}
private void fetch(TextPageLink link) {
@ -67,6 +68,9 @@ public class PageDataIterable<T extends SearchTextBased<? extends UUIDBased>> im
@Override
public T next() {
if(!hasNext()){
throw new NoSuchElementException();
}
return currentItems.get(currentIdx++);
}

2
common/data/src/main/java/org/thingsboard/server/common/data/plugin/ComponentDescriptor.java

@ -32,7 +32,7 @@ public class ComponentDescriptor extends SearchTextBased<ComponentDescriptorId>
@Getter @Setter private ComponentScope scope;
@Getter @Setter private String name;
@Getter @Setter private String clazz;
@Getter @Setter private JsonNode configurationDescriptor;
@Getter @Setter private transient JsonNode configurationDescriptor;
@Getter @Setter private String actions;
public ComponentDescriptor() {

51
common/data/src/main/java/org/thingsboard/server/common/data/plugin/PluginMetaData.java

@ -15,6 +15,7 @@
*/
package org.thingsboard.server.common.data.plugin;
import lombok.EqualsAndHashCode;
import org.thingsboard.server.common.data.HasName;
import org.thingsboard.server.common.data.SearchTextBased;
import org.thingsboard.server.common.data.id.PluginId;
@ -22,6 +23,7 @@ import org.thingsboard.server.common.data.id.TenantId;
import com.fasterxml.jackson.databind.JsonNode;
@EqualsAndHashCode(callSuper = true)
public class PluginMetaData extends SearchTextBased<PluginId> implements HasName {
private static final long serialVersionUID = 1L;
@ -32,8 +34,8 @@ public class PluginMetaData extends SearchTextBased<PluginId> implements HasName
private String clazz;
private boolean publicAccess;
private ComponentLifecycleState state;
private JsonNode configuration;
private JsonNode additionalInfo;
private transient JsonNode configuration;
private transient JsonNode additionalInfo;
public PluginMetaData() {
super();
@ -57,7 +59,7 @@ public class PluginMetaData extends SearchTextBased<PluginId> implements HasName
@Override
public String getSearchText() {
return name;
return getName();
}
public String getApiToken() {
@ -125,49 +127,6 @@ public class PluginMetaData extends SearchTextBased<PluginId> implements HasName
this.additionalInfo = additionalInfo;
}
@Override
public int hashCode() {
final int prime = 31;
int result = super.hashCode();
result = prime * result + ((apiToken == null) ? 0 : apiToken.hashCode());
result = prime * result + ((clazz == null) ? 0 : clazz.hashCode());
result = prime * result + ((name == null) ? 0 : name.hashCode());
result = prime * result + ((tenantId == null) ? 0 : tenantId.hashCode());
return result;
}
@Override
public boolean equals(Object obj) {
if (this == obj)
return true;
if (!super.equals(obj))
return false;
if (getClass() != obj.getClass())
return false;
PluginMetaData other = (PluginMetaData) obj;
if (apiToken == null) {
if (other.apiToken != null)
return false;
} else if (!apiToken.equals(other.apiToken))
return false;
if (clazz == null) {
if (other.clazz != null)
return false;
} else if (!clazz.equals(other.clazz))
return false;
if (name == null) {
if (other.name != null)
return false;
} else if (!name.equals(other.name))
return false;
if (tenantId == null) {
if (other.tenantId != null)
return false;
} else if (!tenantId.equals(other.tenantId))
return false;
return true;
}
@Override
public String toString() {
return "PluginMetaData [apiToken=" + apiToken + ", tenantId=" + tenantId + ", name=" + name + ", clazz=" + clazz + ", publicAccess=" + publicAccess

10
common/data/src/main/java/org/thingsboard/server/common/data/rule/RuleMetaData.java

@ -35,10 +35,10 @@ public class RuleMetaData extends SearchTextBased<RuleId> implements HasName {
private ComponentLifecycleState state;
private int weight;
private String pluginToken;
private JsonNode filters;
private JsonNode processor;
private JsonNode action;
private JsonNode additionalInfo;
private transient JsonNode filters;
private transient JsonNode processor;
private transient JsonNode action;
private transient JsonNode additionalInfo;
public RuleMetaData() {
super();
@ -63,7 +63,7 @@ public class RuleMetaData extends SearchTextBased<RuleId> implements HasName {
@Override
public String getSearchText() {
return name;
return getName();
}
@Override

42
common/data/src/main/java/org/thingsboard/server/common/data/security/DeviceCredentials.java

@ -15,10 +15,12 @@
*/
package org.thingsboard.server.common.data.security;
import lombok.EqualsAndHashCode;
import org.thingsboard.server.common.data.BaseData;
import org.thingsboard.server.common.data.id.DeviceCredentialsId;
import org.thingsboard.server.common.data.id.DeviceId;
@EqualsAndHashCode(callSuper = true)
public class DeviceCredentials extends BaseData<DeviceCredentialsId> implements DeviceCredentialsFilter {
private static final long serialVersionUID = -7869261127032877765L;
@ -78,46 +80,6 @@ public class DeviceCredentials extends BaseData<DeviceCredentialsId> implements
this.credentialsValue = credentialsValue;
}
@Override
public int hashCode() {
final int prime = 31;
int result = super.hashCode();
result = prime * result + ((credentialsId == null) ? 0 : credentialsId.hashCode());
result = prime * result + ((credentialsType == null) ? 0 : credentialsType.hashCode());
result = prime * result + ((credentialsValue == null) ? 0 : credentialsValue.hashCode());
result = prime * result + ((deviceId == null) ? 0 : deviceId.hashCode());
return result;
}
@Override
public boolean equals(Object obj) {
if (this == obj)
return true;
if (!super.equals(obj))
return false;
if (getClass() != obj.getClass())
return false;
DeviceCredentials other = (DeviceCredentials) obj;
if (credentialsId == null) {
if (other.credentialsId != null)
return false;
} else if (!credentialsId.equals(other.credentialsId))
return false;
if (credentialsType != other.credentialsType)
return false;
if (credentialsValue == null) {
if (other.credentialsValue != null)
return false;
} else if (!credentialsValue.equals(other.credentialsValue))
return false;
if (deviceId == null) {
if (other.deviceId != null)
return false;
} else if (!deviceId.equals(other.deviceId))
return false;
return true;
}
@Override
public String toString() {
return "DeviceCredentials [deviceId=" + deviceId + ", credentialsType=" + credentialsType + ", credentialsId="

48
common/data/src/main/java/org/thingsboard/server/common/data/security/UserCredentials.java

@ -15,10 +15,12 @@
*/
package org.thingsboard.server.common.data.security;
import lombok.EqualsAndHashCode;
import org.thingsboard.server.common.data.BaseData;
import org.thingsboard.server.common.data.id.UserCredentialsId;
import org.thingsboard.server.common.data.id.UserId;
@EqualsAndHashCode(callSuper = true)
public class UserCredentials extends BaseData<UserCredentialsId> {
private static final long serialVersionUID = -2108436378880529163L;
@ -86,52 +88,6 @@ public class UserCredentials extends BaseData<UserCredentialsId> {
this.resetToken = resetToken;
}
@Override
public int hashCode() {
final int prime = 31;
int result = super.hashCode();
result = prime * result + ((activateToken == null) ? 0 : activateToken.hashCode());
result = prime * result + (enabled ? 1231 : 1237);
result = prime * result + ((password == null) ? 0 : password.hashCode());
result = prime * result + ((resetToken == null) ? 0 : resetToken.hashCode());
result = prime * result + ((userId == null) ? 0 : userId.hashCode());
return result;
}
@Override
public boolean equals(Object obj) {
if (this == obj)
return true;
if (!super.equals(obj))
return false;
if (getClass() != obj.getClass())
return false;
UserCredentials other = (UserCredentials) obj;
if (activateToken == null) {
if (other.activateToken != null)
return false;
} else if (!activateToken.equals(other.activateToken))
return false;
if (enabled != other.enabled)
return false;
if (password == null) {
if (other.password != null)
return false;
} else if (!password.equals(other.password))
return false;
if (resetToken == null) {
if (other.resetToken != null)
return false;
} else if (!resetToken.equals(other.resetToken))
return false;
if (userId == null) {
if (other.userId != null)
return false;
} else if (!userId.equals(other.userId))
return false;
return true;
}
@Override
public String toString() {
StringBuilder builder = new StringBuilder();

31
common/data/src/main/java/org/thingsboard/server/common/data/widget/WidgetType.java

@ -16,10 +16,12 @@
package org.thingsboard.server.common.data.widget;
import com.fasterxml.jackson.databind.JsonNode;
import lombok.EqualsAndHashCode;
import org.thingsboard.server.common.data.BaseData;
import org.thingsboard.server.common.data.id.TenantId;
import org.thingsboard.server.common.data.id.WidgetTypeId;
@EqualsAndHashCode(callSuper = true)
public class WidgetType extends BaseData<WidgetTypeId> {
private static final long serialVersionUID = 8388684344603660756L;
@ -28,7 +30,7 @@ public class WidgetType extends BaseData<WidgetTypeId> {
private String bundleAlias;
private String alias;
private String name;
private JsonNode descriptor;
private transient JsonNode descriptor;
public WidgetType() {
super();
@ -87,33 +89,6 @@ public class WidgetType extends BaseData<WidgetTypeId> {
this.descriptor = descriptor;
}
@Override
public int hashCode() {
int result = super.hashCode();
result = 31 * result + (tenantId != null ? tenantId.hashCode() : 0);
result = 31 * result + (bundleAlias != null ? bundleAlias.hashCode() : 0);
result = 31 * result + (alias != null ? alias.hashCode() : 0);
result = 31 * result + (name != null ? name.hashCode() : 0);
result = 31 * result + (descriptor != null ? descriptor.hashCode() : 0);
return result;
}
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
if (!super.equals(o)) return false;
WidgetType that = (WidgetType) o;
if (tenantId != null ? !tenantId.equals(that.tenantId) : that.tenantId != null) return false;
if (bundleAlias != null ? !bundleAlias.equals(that.bundleAlias) : that.bundleAlias != null) return false;
if (alias != null ? !alias.equals(that.alias) : that.alias != null) return false;
if (name != null ? !name.equals(that.name) : that.name != null) return false;
return descriptor != null ? descriptor.equals(that.descriptor) : that.descriptor == null;
}
@Override
public String toString() {
final StringBuilder sb = new StringBuilder("WidgetType{");

2
common/data/src/main/java/org/thingsboard/server/common/data/widget/WidgetsBundle.java

@ -80,7 +80,7 @@ public class WidgetsBundle extends SearchTextBased<WidgetsBundleId> {
@Override
public String getSearchText() {
return title;
return getTitle();
}
@Override

11
common/transport/src/main/java/org/thingsboard/server/common/transport/adaptor/JsonConverter.java

@ -30,6 +30,7 @@ import org.thingsboard.server.common.msg.kv.AttributesKVMsg;
public class JsonConverter {
private static final Gson GSON = new Gson();
public static final String CAN_T_PARSE_VALUE = "Can't parse value: ";
public static TelemetryUploadRequest convertToTelemetry(JsonElement jsonObject) throws JsonSyntaxException {
return convertToTelemetry(jsonObject, BasicRequest.DEFAULT_REQUEST_ID);
@ -45,11 +46,11 @@ public class JsonConverter {
if (je.isJsonObject()) {
parseObject(request, systemTs, je.getAsJsonObject());
} else {
throw new JsonSyntaxException("Can't parse value: " + je);
throw new JsonSyntaxException(CAN_T_PARSE_VALUE + je);
}
});
} else {
throw new JsonSyntaxException("Can't parse value: " + jsonObject);
throw new JsonSyntaxException(CAN_T_PARSE_VALUE + jsonObject);
}
return request;
}
@ -99,10 +100,10 @@ public class JsonConverter {
result.add(new LongDataEntry(valueEntry.getKey(), value.getAsLong()));
}
} else {
throw new JsonSyntaxException("Can't parse value: " + value);
throw new JsonSyntaxException(CAN_T_PARSE_VALUE + value);
}
} else {
throw new JsonSyntaxException("Can't parse value: " + element);
throw new JsonSyntaxException(CAN_T_PARSE_VALUE + element);
}
}
return result;
@ -119,7 +120,7 @@ public class JsonConverter {
request.add(parseValues(element.getAsJsonObject()).stream().map(kv -> new BaseAttributeKvEntry(kv, ts)).collect(Collectors.toList()));
return request;
} else {
throw new JsonSyntaxException("Can't parse value: " + element);
throw new JsonSyntaxException(CAN_T_PARSE_VALUE + element);
}
}

38
dao/src/main/java/org/thingsboard/server/dao/alarm/BaseAlarmService.java

@ -37,7 +37,6 @@ import org.thingsboard.server.dao.entity.EntityService;
import org.thingsboard.server.dao.exception.DataValidationException;
import org.thingsboard.server.common.data.relation.EntityRelationsQuery;
import org.thingsboard.server.common.data.relation.EntitySearchDirection;
import org.thingsboard.server.dao.relation.RelationService;
import org.thingsboard.server.common.data.relation.RelationsSearchParameters;
import org.thingsboard.server.dao.service.DataValidator;
import org.thingsboard.server.dao.tenant.TenantDao;
@ -67,9 +66,6 @@ public class BaseAlarmService extends AbstractEntityService implements AlarmServ
@Autowired
private TenantDao tenantDao;
@Autowired
private RelationService relationService;
@Autowired
private EntityService entityService;
@ -272,7 +268,7 @@ public class BaseAlarmService extends AbstractEntityService implements AlarmServ
boolean hasNext = true;
AlarmSeverity highestSeverity = null;
AlarmQuery query;
while (hasNext) {
while (hasNext && AlarmSeverity.CRITICAL != highestSeverity) {
query = new AlarmQuery(entityId, nextPageLink, alarmSearchStatus, alarmStatus, false);
List<AlarmInfo> alarms;
try {
@ -286,33 +282,37 @@ public class BaseAlarmService extends AbstractEntityService implements AlarmServ
if (hasNext) {
nextPageLink = new TimePageData<>(alarms, nextPageLink).getNextPageLink();
}
if (alarms.isEmpty()) {
AlarmSeverity severity = detectHighestSeverity(alarms);
if (severity == null) {
continue;
}
if (severity == AlarmSeverity.CRITICAL || highestSeverity == null) {
highestSeverity = severity;
} else {
List<AlarmInfo> sorted = new ArrayList(alarms);
sorted.sort((p1, p2) -> p1.getSeverity().compareTo(p2.getSeverity()));
AlarmSeverity severity = sorted.get(0).getSeverity();
if (severity == AlarmSeverity.CRITICAL) {
highestSeverity = severity;
break;
} else if (highestSeverity == null) {
highestSeverity = severity;
} else {
highestSeverity = highestSeverity.compareTo(severity) < 0 ? highestSeverity : severity;
}
highestSeverity = highestSeverity.compareTo(severity) < 0 ? highestSeverity : severity;
}
}
return highestSeverity;
}
private AlarmSeverity detectHighestSeverity(List<AlarmInfo> alarms) {
if (!alarms.isEmpty()) {
List<AlarmInfo> sorted = new ArrayList(alarms);
sorted.sort((p1, p2) -> p1.getSeverity().compareTo(p2.getSeverity()));
return sorted.get(0).getSeverity();
} else {
return null;
}
}
private void deleteRelation(EntityRelation alarmRelation) throws ExecutionException, InterruptedException {
log.debug("Deleting Alarm relation: {}", alarmRelation);
relationService.deleteRelation(alarmRelation).get();
relationService.deleteRelationAsync(alarmRelation).get();
}
private void createRelation(EntityRelation alarmRelation) throws ExecutionException, InterruptedException {
log.debug("Creating Alarm relation: {}", alarmRelation);
relationService.saveRelation(alarmRelation).get();
relationService.saveRelationAsync(alarmRelation).get();
}
private Alarm merge(Alarm existing, Alarm alarm) {

68
dao/src/main/java/org/thingsboard/server/dao/asset/BaseAssetService.java

@ -37,19 +37,15 @@ import org.thingsboard.server.common.data.id.TenantId;
import org.thingsboard.server.common.data.page.TextPageData;
import org.thingsboard.server.common.data.page.TextPageLink;
import org.thingsboard.server.common.data.relation.EntityRelation;
import org.thingsboard.server.common.data.relation.EntitySearchDirection;
import org.thingsboard.server.dao.customer.CustomerDao;
import org.thingsboard.server.dao.entity.AbstractEntityService;
import org.thingsboard.server.dao.exception.DataValidationException;
import org.thingsboard.server.common.data.relation.EntitySearchDirection;
import org.thingsboard.server.dao.service.DataValidator;
import org.thingsboard.server.dao.service.PaginatedRemover;
import org.thingsboard.server.dao.tenant.TenantDao;
import javax.annotation.Nullable;
import java.util.ArrayList;
import java.util.Comparator;
import java.util.List;
import java.util.Optional;
import java.util.*;
import java.util.stream.Collectors;
import static org.thingsboard.server.dao.DaoUtil.toUUIDs;
@ -60,6 +56,10 @@ import static org.thingsboard.server.dao.service.Validator.*;
@Slf4j
public class BaseAssetService extends AbstractEntityService implements AssetService {
public static final String INCORRECT_TENANT_ID = "Incorrect tenantId ";
public static final String INCORRECT_PAGE_LINK = "Incorrect page link ";
public static final String INCORRECT_CUSTOMER_ID = "Incorrect customerId ";
public static final String INCORRECT_ASSET_ID = "Incorrect assetId ";
@Autowired
private AssetDao assetDao;
@ -72,21 +72,21 @@ public class BaseAssetService extends AbstractEntityService implements AssetServ
@Override
public Asset findAssetById(AssetId assetId) {
log.trace("Executing findAssetById [{}]", assetId);
validateId(assetId, "Incorrect assetId " + assetId);
validateId(assetId, INCORRECT_ASSET_ID + assetId);
return assetDao.findById(assetId.getId());
}
@Override
public ListenableFuture<Asset> findAssetByIdAsync(AssetId assetId) {
log.trace("Executing findAssetById [{}]", assetId);
validateId(assetId, "Incorrect assetId " + assetId);
validateId(assetId, INCORRECT_ASSET_ID + assetId);
return assetDao.findByIdAsync(assetId.getId());
}
@Override
public Optional<Asset> findAssetByTenantIdAndName(TenantId tenantId, String name) {
log.trace("Executing findAssetByTenantIdAndName [{}][{}]", tenantId, name);
validateId(tenantId, "Incorrect tenantId " + tenantId);
validateId(tenantId, INCORRECT_TENANT_ID + tenantId);
return assetDao.findAssetsByTenantIdAndName(tenantId.getId(), name);
}
@ -114,7 +114,7 @@ public class BaseAssetService extends AbstractEntityService implements AssetServ
@Override
public void deleteAsset(AssetId assetId) {
log.trace("Executing deleteAsset [{}]", assetId);
validateId(assetId, "Incorrect assetId " + assetId);
validateId(assetId, INCORRECT_ASSET_ID + assetId);
deleteEntityRelations(assetId);
assetDao.removeById(assetId.getId());
}
@ -122,8 +122,8 @@ public class BaseAssetService extends AbstractEntityService implements AssetServ
@Override
public TextPageData<Asset> findAssetsByTenantId(TenantId tenantId, TextPageLink pageLink) {
log.trace("Executing findAssetsByTenantId, tenantId [{}], pageLink [{}]", tenantId, pageLink);
validateId(tenantId, "Incorrect tenantId " + tenantId);
validatePageLink(pageLink, "Incorrect page link " + pageLink);
validateId(tenantId, INCORRECT_TENANT_ID + tenantId);
validatePageLink(pageLink, INCORRECT_PAGE_LINK + pageLink);
List<Asset> assets = assetDao.findAssetsByTenantId(tenantId.getId(), pageLink);
return new TextPageData<>(assets, pageLink);
}
@ -131,9 +131,9 @@ public class BaseAssetService extends AbstractEntityService implements AssetServ
@Override
public TextPageData<Asset> findAssetsByTenantIdAndType(TenantId tenantId, String type, TextPageLink pageLink) {
log.trace("Executing findAssetsByTenantIdAndType, tenantId [{}], type [{}], pageLink [{}]", tenantId, type, pageLink);
validateId(tenantId, "Incorrect tenantId " + tenantId);
validateId(tenantId, INCORRECT_TENANT_ID + tenantId);
validateString(type, "Incorrect type " + type);
validatePageLink(pageLink, "Incorrect page link " + pageLink);
validatePageLink(pageLink, INCORRECT_PAGE_LINK + pageLink);
List<Asset> assets = assetDao.findAssetsByTenantIdAndType(tenantId.getId(), type, pageLink);
return new TextPageData<>(assets, pageLink);
}
@ -141,7 +141,7 @@ public class BaseAssetService extends AbstractEntityService implements AssetServ
@Override
public ListenableFuture<List<Asset>> findAssetsByTenantIdAndIdsAsync(TenantId tenantId, List<AssetId> assetIds) {
log.trace("Executing findAssetsByTenantIdAndIdsAsync, tenantId [{}], assetIds [{}]", tenantId, assetIds);
validateId(tenantId, "Incorrect tenantId " + tenantId);
validateId(tenantId, INCORRECT_TENANT_ID + tenantId);
validateIds(assetIds, "Incorrect assetIds " + assetIds);
return assetDao.findAssetsByTenantIdAndIdsAsync(tenantId.getId(), toUUIDs(assetIds));
}
@ -149,27 +149,27 @@ public class BaseAssetService extends AbstractEntityService implements AssetServ
@Override
public void deleteAssetsByTenantId(TenantId tenantId) {
log.trace("Executing deleteAssetsByTenantId, tenantId [{}]", tenantId);
validateId(tenantId, "Incorrect tenantId " + tenantId);
validateId(tenantId, INCORRECT_TENANT_ID + tenantId);
tenantAssetsRemover.removeEntities(tenantId);
}
@Override
public TextPageData<Asset> findAssetsByTenantIdAndCustomerId(TenantId tenantId, CustomerId customerId, TextPageLink pageLink) {
log.trace("Executing findAssetsByTenantIdAndCustomerId, tenantId [{}], customerId [{}], pageLink [{}]", tenantId, customerId, pageLink);
validateId(tenantId, "Incorrect tenantId " + tenantId);
validateId(customerId, "Incorrect customerId " + customerId);
validatePageLink(pageLink, "Incorrect page link " + pageLink);
validateId(tenantId, INCORRECT_TENANT_ID + tenantId);
validateId(customerId, INCORRECT_CUSTOMER_ID + customerId);
validatePageLink(pageLink, INCORRECT_PAGE_LINK + pageLink);
List<Asset> assets = assetDao.findAssetsByTenantIdAndCustomerId(tenantId.getId(), customerId.getId(), pageLink);
return new TextPageData<Asset>(assets, pageLink);
return new TextPageData<>(assets, pageLink);
}
@Override
public TextPageData<Asset> findAssetsByTenantIdAndCustomerIdAndType(TenantId tenantId, CustomerId customerId, String type, TextPageLink pageLink) {
log.trace("Executing findAssetsByTenantIdAndCustomerIdAndType, tenantId [{}], customerId [{}], type [{}], pageLink [{}]", tenantId, customerId, type, pageLink);
validateId(tenantId, "Incorrect tenantId " + tenantId);
validateId(customerId, "Incorrect customerId " + customerId);
validateId(tenantId, INCORRECT_TENANT_ID + tenantId);
validateId(customerId, INCORRECT_CUSTOMER_ID + customerId);
validateString(type, "Incorrect type " + type);
validatePageLink(pageLink, "Incorrect page link " + pageLink);
validatePageLink(pageLink, INCORRECT_PAGE_LINK + pageLink);
List<Asset> assets = assetDao.findAssetsByTenantIdAndCustomerIdAndType(tenantId.getId(), customerId.getId(), type, pageLink);
return new TextPageData<>(assets, pageLink);
}
@ -177,8 +177,8 @@ public class BaseAssetService extends AbstractEntityService implements AssetServ
@Override
public ListenableFuture<List<Asset>> findAssetsByTenantIdCustomerIdAndIdsAsync(TenantId tenantId, CustomerId customerId, List<AssetId> assetIds) {
log.trace("Executing findAssetsByTenantIdAndCustomerIdAndIdsAsync, tenantId [{}], customerId [{}], assetIds [{}]", tenantId, customerId, assetIds);
validateId(tenantId, "Incorrect tenantId " + tenantId);
validateId(customerId, "Incorrect customerId " + customerId);
validateId(tenantId, INCORRECT_TENANT_ID + tenantId);
validateId(customerId, INCORRECT_CUSTOMER_ID + customerId);
validateIds(assetIds, "Incorrect assetIds " + assetIds);
return assetDao.findAssetsByTenantIdAndCustomerIdAndIdsAsync(tenantId.getId(), customerId.getId(), toUUIDs(assetIds));
}
@ -186,8 +186,8 @@ public class BaseAssetService extends AbstractEntityService implements AssetServ
@Override
public void unassignCustomerAssets(TenantId tenantId, CustomerId customerId) {
log.trace("Executing unassignCustomerAssets, tenantId [{}], customerId [{}]", tenantId, customerId);
validateId(tenantId, "Incorrect tenantId " + tenantId);
validateId(customerId, "Incorrect customerId " + customerId);
validateId(tenantId, INCORRECT_TENANT_ID + tenantId);
validateId(customerId, INCORRECT_CUSTOMER_ID + customerId);
new CustomerAssetsUnassigner(tenantId).removeEntities(customerId);
}
@ -205,22 +205,16 @@ public class BaseAssetService extends AbstractEntityService implements AssetServ
}
return Futures.successfulAsList(futures);
});
assets = Futures.transform(assets, new Function<List<Asset>, List<Asset>>() {
@Nullable
@Override
public List<Asset> apply(@Nullable List<Asset> assetList) {
return assetList.stream().filter(asset -> query.getAssetTypes().contains(asset.getType())).collect(Collectors.toList());
}
});
assets = Futures.transform(assets, (Function<List<Asset>, List<Asset>>)assetList ->
assetList == null ? Collections.emptyList() : assetList.stream().filter(asset -> query.getAssetTypes().contains(asset.getType())).collect(Collectors.toList())
);
return assets;
}
@Override
public ListenableFuture<List<EntitySubtype>> findAssetTypesByTenantId(TenantId tenantId) {
log.trace("Executing findAssetTypesByTenantId, tenantId [{}]", tenantId);
validateId(tenantId, "Incorrect tenantId " + tenantId);
validateId(tenantId, INCORRECT_TENANT_ID + tenantId);
ListenableFuture<List<EntitySubtype>> tenantAssetTypes = assetDao.findTenantAssetTypesAsync(tenantId.getId());
return Futures.transform(tenantAssetTypes,
(Function<List<EntitySubtype>, List<EntitySubtype>>) assetTypes -> {

15
dao/src/main/java/org/thingsboard/server/dao/attributes/CassandraBaseAttributesDao.java

@ -109,18 +109,21 @@ public class CassandraBaseAttributesDao extends CassandraAbstractAsyncDao implem
stmt.setString(3, attribute.getKey());
stmt.setLong(4, attribute.getLastUpdateTs());
stmt.setString(5, attribute.getStrValue().orElse(null));
if (attribute.getBooleanValue().isPresent()) {
stmt.setBool(6, attribute.getBooleanValue().get());
Optional<Boolean> booleanValue = attribute.getBooleanValue();
if (booleanValue.isPresent()) {
stmt.setBool(6, booleanValue.get());
} else {
stmt.setToNull(6);
}
if (attribute.getLongValue().isPresent()) {
stmt.setLong(7, attribute.getLongValue().get());
Optional<Long> longValue = attribute.getLongValue();
if (longValue.isPresent()) {
stmt.setLong(7, longValue.get());
} else {
stmt.setToNull(7);
}
if (attribute.getDoubleValue().isPresent()) {
stmt.setDouble(8, attribute.getDoubleValue().get());
Optional<Double> doubleValue = attribute.getDoubleValue();
if (doubleValue.isPresent()) {
stmt.setDouble(8, doubleValue.get());
} else {
stmt.setToNull(8);
}

1
dao/src/main/java/org/thingsboard/server/dao/cassandra/AbstractCassandraCluster.java

@ -153,6 +153,7 @@ public abstract class AbstractCassandraCluster {
Thread.sleep(initRetryInterval);
} catch (InterruptedException ie) {
log.warn("Failed to wait until retry", ie);
Thread.currentThread().interrupt();
}
}
}

14
dao/src/main/java/org/thingsboard/server/dao/component/CassandraBaseComponentDescriptorDao.java

@ -49,6 +49,8 @@ import static com.datastax.driver.core.querybuilder.QueryBuilder.select;
@NoSqlDao
public class CassandraBaseComponentDescriptorDao extends CassandraAbstractSearchTextDao<ComponentDescriptorEntity, ComponentDescriptor> implements ComponentDescriptorDao {
public static final String SEARCH_RESULT = "Search result: [{}]";
@Override
protected Class<ComponentDescriptorEntity> getColumnFamilyClass() {
return ComponentDescriptorEntity.class;
@ -79,7 +81,7 @@ public class CassandraBaseComponentDescriptorDao extends CassandraAbstractSearch
if (log.isTraceEnabled()) {
log.trace("Search result: [{}] for component entity [{}]", componentDescriptor != null, componentDescriptor);
} else {
log.debug("Search result: [{}]", componentDescriptor != null);
log.debug(SEARCH_RESULT, componentDescriptor != null);
}
return componentDescriptor;
}
@ -93,7 +95,7 @@ public class CassandraBaseComponentDescriptorDao extends CassandraAbstractSearch
if (log.isTraceEnabled()) {
log.trace("Search result: [{}] for component entity [{}]", entity != null, entity);
} else {
log.debug("Search result: [{}]", entity != null);
log.debug(SEARCH_RESULT, entity != null);
}
return DaoUtil.getData(entity);
}
@ -104,9 +106,9 @@ public class CassandraBaseComponentDescriptorDao extends CassandraAbstractSearch
List<ComponentDescriptorEntity> entities = findPageWithTextSearch(ModelConstants.COMPONENT_DESCRIPTOR_BY_TYPE_AND_SEARCH_TEXT_COLUMN_FAMILY_NAME,
Arrays.asList(eq(ModelConstants.COMPONENT_DESCRIPTOR_TYPE_PROPERTY, type)), pageLink);
if (log.isTraceEnabled()) {
log.trace("Search result: [{}]", Arrays.toString(entities.toArray()));
log.trace(SEARCH_RESULT, Arrays.toString(entities.toArray()));
} else {
log.debug("Search result: [{}]", entities.size());
log.debug(SEARCH_RESULT, entities.size());
}
return DaoUtil.convertDataList(entities);
}
@ -118,9 +120,9 @@ public class CassandraBaseComponentDescriptorDao extends CassandraAbstractSearch
Arrays.asList(eq(ModelConstants.COMPONENT_DESCRIPTOR_TYPE_PROPERTY, type),
eq(ModelConstants.COMPONENT_DESCRIPTOR_SCOPE_PROPERTY, scope.name())), pageLink);
if (log.isTraceEnabled()) {
log.trace("Search result: [{}]", Arrays.toString(entities.toArray()));
log.trace(SEARCH_RESULT, Arrays.toString(entities.toArray()));
} else {
log.debug("Search result: [{}]", entities.size());
log.debug(SEARCH_RESULT, entities.size());
}
return DaoUtil.convertDataList(entities);
}

9
dao/src/main/java/org/thingsboard/server/dao/customer/CustomerServiceImpl.java

@ -51,6 +51,7 @@ import static org.thingsboard.server.dao.service.Validator.validateId;
public class CustomerServiceImpl extends AbstractEntityService implements CustomerService {
private static final String PUBLIC_CUSTOMER_TITLE = "Public";
public static final String INCORRECT_CUSTOMER_ID = "Incorrect customerId ";
@Autowired
private CustomerDao customerDao;
@ -73,14 +74,14 @@ public class CustomerServiceImpl extends AbstractEntityService implements Custom
@Override
public Customer findCustomerById(CustomerId customerId) {
log.trace("Executing findCustomerById [{}]", customerId);
Validator.validateId(customerId, "Incorrect customerId " + customerId);
Validator.validateId(customerId, INCORRECT_CUSTOMER_ID + customerId);
return customerDao.findById(customerId.getId());
}
@Override
public ListenableFuture<Customer> findCustomerByIdAsync(CustomerId customerId) {
log.trace("Executing findCustomerByIdAsync [{}]", customerId);
validateId(customerId, "Incorrect customerId " + customerId);
validateId(customerId, INCORRECT_CUSTOMER_ID + customerId);
return customerDao.findByIdAsync(customerId.getId());
}
@ -94,7 +95,7 @@ public class CustomerServiceImpl extends AbstractEntityService implements Custom
@Override
public void deleteCustomer(CustomerId customerId) {
log.trace("Executing deleteCustomer [{}]", customerId);
Validator.validateId(customerId, "Incorrect customerId " + customerId);
Validator.validateId(customerId, INCORRECT_CUSTOMER_ID + customerId);
Customer customer = findCustomerById(customerId);
if (customer == null) {
throw new IncorrectParameterException("Unable to delete non-existent customer.");
@ -110,7 +111,7 @@ public class CustomerServiceImpl extends AbstractEntityService implements Custom
@Override
public Customer findOrCreatePublicCustomer(TenantId tenantId) {
log.trace("Executing findOrCreatePublicCustomer, tenantId [{}]", tenantId);
Validator.validateId(tenantId, "Incorrect customerId " + tenantId);
Validator.validateId(tenantId, INCORRECT_CUSTOMER_ID + tenantId);
Optional<Customer> publicCustomerOpt = customerDao.findCustomersByTenantIdAndTitle(tenantId.getId(), PUBLIC_CUSTOMER_TITLE);
if (publicCustomerOpt.isPresent()) {
return publicCustomerOpt.get();

20
dao/src/main/java/org/thingsboard/server/dao/dashboard/DashboardServiceImpl.java

@ -46,6 +46,8 @@ import static org.thingsboard.server.dao.service.Validator.validateId;
@Slf4j
public class DashboardServiceImpl extends AbstractEntityService implements DashboardService {
public static final String INCORRECT_DASHBOARD_ID = "Incorrect dashboardId ";
public static final String INCORRECT_TENANT_ID = "Incorrect tenantId ";
@Autowired
private DashboardDao dashboardDao;
@ -61,28 +63,28 @@ public class DashboardServiceImpl extends AbstractEntityService implements Dashb
@Override
public Dashboard findDashboardById(DashboardId dashboardId) {
log.trace("Executing findDashboardById [{}]", dashboardId);
Validator.validateId(dashboardId, "Incorrect dashboardId " + dashboardId);
Validator.validateId(dashboardId, INCORRECT_DASHBOARD_ID + dashboardId);
return dashboardDao.findById(dashboardId.getId());
}
@Override
public ListenableFuture<Dashboard> findDashboardByIdAsync(DashboardId dashboardId) {
log.trace("Executing findDashboardByIdAsync [{}]", dashboardId);
validateId(dashboardId, "Incorrect dashboardId " + dashboardId);
validateId(dashboardId, INCORRECT_DASHBOARD_ID + dashboardId);
return dashboardDao.findByIdAsync(dashboardId.getId());
}
@Override
public DashboardInfo findDashboardInfoById(DashboardId dashboardId) {
log.trace("Executing findDashboardInfoById [{}]", dashboardId);
Validator.validateId(dashboardId, "Incorrect dashboardId " + dashboardId);
Validator.validateId(dashboardId, INCORRECT_DASHBOARD_ID + dashboardId);
return dashboardInfoDao.findById(dashboardId.getId());
}
@Override
public ListenableFuture<DashboardInfo> findDashboardInfoByIdAsync(DashboardId dashboardId) {
log.trace("Executing findDashboardInfoByIdAsync [{}]", dashboardId);
validateId(dashboardId, "Incorrect dashboardId " + dashboardId);
validateId(dashboardId, INCORRECT_DASHBOARD_ID + dashboardId);
return dashboardInfoDao.findByIdAsync(dashboardId.getId());
}
@ -110,7 +112,7 @@ public class DashboardServiceImpl extends AbstractEntityService implements Dashb
@Override
public void deleteDashboard(DashboardId dashboardId) {
log.trace("Executing deleteDashboard [{}]", dashboardId);
Validator.validateId(dashboardId, "Incorrect dashboardId " + dashboardId);
Validator.validateId(dashboardId, INCORRECT_DASHBOARD_ID + dashboardId);
deleteEntityRelations(dashboardId);
dashboardDao.removeById(dashboardId.getId());
}
@ -118,7 +120,7 @@ public class DashboardServiceImpl extends AbstractEntityService implements Dashb
@Override
public TextPageData<DashboardInfo> findDashboardsByTenantId(TenantId tenantId, TextPageLink pageLink) {
log.trace("Executing findDashboardsByTenantId, tenantId [{}], pageLink [{}]", tenantId, pageLink);
Validator.validateId(tenantId, "Incorrect tenantId " + tenantId);
Validator.validateId(tenantId, INCORRECT_TENANT_ID + tenantId);
Validator.validatePageLink(pageLink, "Incorrect page link " + pageLink);
List<DashboardInfo> dashboards = dashboardInfoDao.findDashboardsByTenantId(tenantId.getId(), pageLink);
return new TextPageData<>(dashboards, pageLink);
@ -127,14 +129,14 @@ public class DashboardServiceImpl extends AbstractEntityService implements Dashb
@Override
public void deleteDashboardsByTenantId(TenantId tenantId) {
log.trace("Executing deleteDashboardsByTenantId, tenantId [{}]", tenantId);
Validator.validateId(tenantId, "Incorrect tenantId " + tenantId);
Validator.validateId(tenantId, INCORRECT_TENANT_ID + tenantId);
tenantDashboardsRemover.removeEntities(tenantId);
}
@Override
public TextPageData<DashboardInfo> findDashboardsByTenantIdAndCustomerId(TenantId tenantId, CustomerId customerId, TextPageLink pageLink) {
log.trace("Executing findDashboardsByTenantIdAndCustomerId, tenantId [{}], customerId [{}], pageLink [{}]", tenantId, customerId, pageLink);
Validator.validateId(tenantId, "Incorrect tenantId " + tenantId);
Validator.validateId(tenantId, INCORRECT_TENANT_ID + tenantId);
Validator.validateId(customerId, "Incorrect customerId " + customerId);
Validator.validatePageLink(pageLink, "Incorrect page link " + pageLink);
List<DashboardInfo> dashboards = dashboardInfoDao.findDashboardsByTenantIdAndCustomerId(tenantId.getId(), customerId.getId(), pageLink);
@ -144,7 +146,7 @@ public class DashboardServiceImpl extends AbstractEntityService implements Dashb
@Override
public void unassignCustomerDashboards(TenantId tenantId, CustomerId customerId) {
log.trace("Executing unassignCustomerDashboards, tenantId [{}], customerId [{}]", tenantId, customerId);
Validator.validateId(tenantId, "Incorrect tenantId " + tenantId);
Validator.validateId(tenantId, INCORRECT_TENANT_ID + tenantId);
Validator.validateId(customerId, "Incorrect customerId " + customerId);
new CustomerDashboardsUnassigner(tenantId).removeEntities(customerId);
}

53
dao/src/main/java/org/thingsboard/server/dao/device/DeviceServiceImpl.java

@ -44,10 +44,7 @@ import org.thingsboard.server.dao.service.PaginatedRemover;
import org.thingsboard.server.dao.tenant.TenantDao;
import javax.annotation.Nullable;
import java.util.ArrayList;
import java.util.Comparator;
import java.util.List;
import java.util.Optional;
import java.util.*;
import java.util.stream.Collectors;
import static org.thingsboard.server.dao.DaoUtil.toUUIDs;
@ -58,6 +55,10 @@ import static org.thingsboard.server.dao.service.Validator.*;
@Slf4j
public class DeviceServiceImpl extends AbstractEntityService implements DeviceService {
public static final String INCORRECT_TENANT_ID = "Incorrect tenantId ";
public static final String INCORRECT_PAGE_LINK = "Incorrect page link ";
public static final String INCORRECT_CUSTOMER_ID = "Incorrect customerId ";
public static final String INCORRECT_DEVICE_ID = "Incorrect deviceId ";
@Autowired
private DeviceDao deviceDao;
@ -73,21 +74,21 @@ public class DeviceServiceImpl extends AbstractEntityService implements DeviceSe
@Override
public Device findDeviceById(DeviceId deviceId) {
log.trace("Executing findDeviceById [{}]", deviceId);
validateId(deviceId, "Incorrect deviceId " + deviceId);
validateId(deviceId, INCORRECT_DEVICE_ID + deviceId);
return deviceDao.findById(deviceId.getId());
}
@Override
public ListenableFuture<Device> findDeviceByIdAsync(DeviceId deviceId) {
log.trace("Executing findDeviceById [{}]", deviceId);
validateId(deviceId, "Incorrect deviceId " + deviceId);
validateId(deviceId, INCORRECT_DEVICE_ID + deviceId);
return deviceDao.findByIdAsync(deviceId.getId());
}
@Override
public Optional<Device> findDeviceByTenantIdAndName(TenantId tenantId, String name) {
log.trace("Executing findDeviceByTenantIdAndName [{}][{}]", tenantId, name);
validateId(tenantId, "Incorrect tenantId " + tenantId);
validateId(tenantId, INCORRECT_TENANT_ID + tenantId);
Optional<Device> deviceOpt = deviceDao.findDeviceByTenantIdAndName(tenantId.getId(), name);
if (deviceOpt.isPresent()) {
return Optional.of(deviceOpt.get());
@ -128,7 +129,7 @@ public class DeviceServiceImpl extends AbstractEntityService implements DeviceSe
@Override
public void deleteDevice(DeviceId deviceId) {
log.trace("Executing deleteDevice [{}]", deviceId);
validateId(deviceId, "Incorrect deviceId " + deviceId);
validateId(deviceId, INCORRECT_DEVICE_ID + deviceId);
DeviceCredentials deviceCredentials = deviceCredentialsService.findDeviceCredentialsByDeviceId(deviceId);
if (deviceCredentials != null) {
deviceCredentialsService.deleteDeviceCredentials(deviceCredentials);
@ -140,8 +141,8 @@ public class DeviceServiceImpl extends AbstractEntityService implements DeviceSe
@Override
public TextPageData<Device> findDevicesByTenantId(TenantId tenantId, TextPageLink pageLink) {
log.trace("Executing findDevicesByTenantId, tenantId [{}], pageLink [{}]", tenantId, pageLink);
validateId(tenantId, "Incorrect tenantId " + tenantId);
validatePageLink(pageLink, "Incorrect page link " + pageLink);
validateId(tenantId, INCORRECT_TENANT_ID + tenantId);
validatePageLink(pageLink, INCORRECT_PAGE_LINK + pageLink);
List<Device> devices = deviceDao.findDevicesByTenantId(tenantId.getId(), pageLink);
return new TextPageData<>(devices, pageLink);
}
@ -149,9 +150,9 @@ public class DeviceServiceImpl extends AbstractEntityService implements DeviceSe
@Override
public TextPageData<Device> findDevicesByTenantIdAndType(TenantId tenantId, String type, TextPageLink pageLink) {
log.trace("Executing findDevicesByTenantIdAndType, tenantId [{}], type [{}], pageLink [{}]", tenantId, type, pageLink);
validateId(tenantId, "Incorrect tenantId " + tenantId);
validateId(tenantId, INCORRECT_TENANT_ID + tenantId);
validateString(type, "Incorrect type " + type);
validatePageLink(pageLink, "Incorrect page link " + pageLink);
validatePageLink(pageLink, INCORRECT_PAGE_LINK + pageLink);
List<Device> devices = deviceDao.findDevicesByTenantIdAndType(tenantId.getId(), type, pageLink);
return new TextPageData<>(devices, pageLink);
}
@ -159,7 +160,7 @@ public class DeviceServiceImpl extends AbstractEntityService implements DeviceSe
@Override
public ListenableFuture<List<Device>> findDevicesByTenantIdAndIdsAsync(TenantId tenantId, List<DeviceId> deviceIds) {
log.trace("Executing findDevicesByTenantIdAndIdsAsync, tenantId [{}], deviceIds [{}]", tenantId, deviceIds);
validateId(tenantId, "Incorrect tenantId " + tenantId);
validateId(tenantId, INCORRECT_TENANT_ID + tenantId);
validateIds(deviceIds, "Incorrect deviceIds " + deviceIds);
return deviceDao.findDevicesByTenantIdAndIdsAsync(tenantId.getId(), toUUIDs(deviceIds));
}
@ -168,16 +169,16 @@ public class DeviceServiceImpl extends AbstractEntityService implements DeviceSe
@Override
public void deleteDevicesByTenantId(TenantId tenantId) {
log.trace("Executing deleteDevicesByTenantId, tenantId [{}]", tenantId);
validateId(tenantId, "Incorrect tenantId " + tenantId);
validateId(tenantId, INCORRECT_TENANT_ID + tenantId);
tenantDevicesRemover.removeEntities(tenantId);
}
@Override
public TextPageData<Device> findDevicesByTenantIdAndCustomerId(TenantId tenantId, CustomerId customerId, TextPageLink pageLink) {
log.trace("Executing findDevicesByTenantIdAndCustomerId, tenantId [{}], customerId [{}], pageLink [{}]", tenantId, customerId, pageLink);
validateId(tenantId, "Incorrect tenantId " + tenantId);
validateId(customerId, "Incorrect customerId " + customerId);
validatePageLink(pageLink, "Incorrect page link " + pageLink);
validateId(tenantId, INCORRECT_TENANT_ID + tenantId);
validateId(customerId, INCORRECT_CUSTOMER_ID + customerId);
validatePageLink(pageLink, INCORRECT_PAGE_LINK + pageLink);
List<Device> devices = deviceDao.findDevicesByTenantIdAndCustomerId(tenantId.getId(), customerId.getId(), pageLink);
return new TextPageData<>(devices, pageLink);
}
@ -185,10 +186,10 @@ public class DeviceServiceImpl extends AbstractEntityService implements DeviceSe
@Override
public TextPageData<Device> findDevicesByTenantIdAndCustomerIdAndType(TenantId tenantId, CustomerId customerId, String type, TextPageLink pageLink) {
log.trace("Executing findDevicesByTenantIdAndCustomerIdAndType, tenantId [{}], customerId [{}], type [{}], pageLink [{}]", tenantId, customerId, type, pageLink);
validateId(tenantId, "Incorrect tenantId " + tenantId);
validateId(customerId, "Incorrect customerId " + customerId);
validateId(tenantId, INCORRECT_TENANT_ID + tenantId);
validateId(customerId, INCORRECT_CUSTOMER_ID + customerId);
validateString(type, "Incorrect type " + type);
validatePageLink(pageLink, "Incorrect page link " + pageLink);
validatePageLink(pageLink, INCORRECT_PAGE_LINK + pageLink);
List<Device> devices = deviceDao.findDevicesByTenantIdAndCustomerIdAndType(tenantId.getId(), customerId.getId(), type, pageLink);
return new TextPageData<>(devices, pageLink);
}
@ -196,8 +197,8 @@ public class DeviceServiceImpl extends AbstractEntityService implements DeviceSe
@Override
public ListenableFuture<List<Device>> findDevicesByTenantIdCustomerIdAndIdsAsync(TenantId tenantId, CustomerId customerId, List<DeviceId> deviceIds) {
log.trace("Executing findDevicesByTenantIdCustomerIdAndIdsAsync, tenantId [{}], customerId [{}], deviceIds [{}]", tenantId, customerId, deviceIds);
validateId(tenantId, "Incorrect tenantId " + tenantId);
validateId(customerId, "Incorrect customerId " + customerId);
validateId(tenantId, INCORRECT_TENANT_ID + tenantId);
validateId(customerId, INCORRECT_CUSTOMER_ID + customerId);
validateIds(deviceIds, "Incorrect deviceIds " + deviceIds);
return deviceDao.findDevicesByTenantIdCustomerIdAndIdsAsync(tenantId.getId(),
customerId.getId(), toUUIDs(deviceIds));
@ -206,8 +207,8 @@ public class DeviceServiceImpl extends AbstractEntityService implements DeviceSe
@Override
public void unassignCustomerDevices(TenantId tenantId, CustomerId customerId) {
log.trace("Executing unassignCustomerDevices, tenantId [{}], customerId [{}]", tenantId, customerId);
validateId(tenantId, "Incorrect tenantId " + tenantId);
validateId(customerId, "Incorrect customerId " + customerId);
validateId(tenantId, INCORRECT_TENANT_ID + tenantId);
validateId(customerId, INCORRECT_CUSTOMER_ID + customerId);
new CustomerDevicesUnassigner(tenantId).removeEntities(customerId);
}
@ -230,7 +231,7 @@ public class DeviceServiceImpl extends AbstractEntityService implements DeviceSe
@Nullable
@Override
public List<Device> apply(@Nullable List<Device> deviceList) {
return deviceList.stream().filter(device -> query.getDeviceTypes().contains(device.getType())).collect(Collectors.toList());
return deviceList == null ? Collections.emptyList() : deviceList.stream().filter(device -> query.getDeviceTypes().contains(device.getType())).collect(Collectors.toList());
}
});
@ -240,7 +241,7 @@ public class DeviceServiceImpl extends AbstractEntityService implements DeviceSe
@Override
public ListenableFuture<List<EntitySubtype>> findDeviceTypesByTenantId(TenantId tenantId) {
log.trace("Executing findDeviceTypesByTenantId, tenantId [{}]", tenantId);
validateId(tenantId, "Incorrect tenantId " + tenantId);
validateId(tenantId, INCORRECT_TENANT_ID + tenantId);
ListenableFuture<List<EntitySubtype>> tenantDeviceTypes = deviceDao.findTenantDeviceTypesAsync(tenantId.getId());
return Futures.transform(tenantDeviceTypes,
(Function<List<EntitySubtype>, List<EntitySubtype>>) deviceTypes -> {

7
dao/src/main/java/org/thingsboard/server/dao/entity/AbstractEntityService.java

@ -31,12 +31,7 @@ public abstract class AbstractEntityService {
protected void deleteEntityRelations(EntityId entityId) {
log.trace("Executing deleteEntityRelations [{}]", entityId);
try {
relationService.deleteEntityRelations(entityId).get();
} catch (InterruptedException | ExecutionException e) {
throw new RuntimeException(e);
}
relationService.deleteEntityRelations(entityId);
}
}

2
dao/src/main/java/org/thingsboard/server/dao/model/BaseEntity.java

@ -18,7 +18,7 @@ package org.thingsboard.server.dao.model;
import java.io.Serializable;
import java.util.UUID;
public interface BaseEntity<D> extends ToData<D>, Serializable {
public interface BaseEntity<D> extends ToData<D> {
UUID getId();

4
dao/src/main/java/org/thingsboard/server/dao/model/EntitySubtypeEntity.java

@ -19,7 +19,6 @@ package org.thingsboard.server.dao.model;
import com.datastax.driver.mapping.annotations.Column;
import com.datastax.driver.mapping.annotations.PartitionKey;
import com.datastax.driver.mapping.annotations.Table;
import com.datastax.driver.mapping.annotations.Transient;
import org.thingsboard.server.common.data.EntitySubtype;
import org.thingsboard.server.common.data.EntityType;
import org.thingsboard.server.common.data.id.TenantId;
@ -32,9 +31,6 @@ import static org.thingsboard.server.dao.model.ModelConstants.*;
@Table(name = ENTITY_SUBTYPE_COLUMN_FAMILY_NAME)
public class EntitySubtypeEntity {
@Transient
private static final long serialVersionUID = -1268181961886910152L;
@PartitionKey(value = 0)
@Column(name = ENTITY_SUBTYPE_TENANT_ID_PROPERTY)
private UUID tenantId;

29
dao/src/main/java/org/thingsboard/server/dao/model/ModelConstants.java

@ -27,8 +27,8 @@ public class ModelConstants {
private ModelConstants() {
}
public static UUID NULL_UUID = UUIDs.startOf(0);
public static String NULL_UUID_STR = UUIDConverter.fromTimeUUID(NULL_UUID);
public static final UUID NULL_UUID = UUIDs.startOf(0);
public static final String NULL_UUID_STR = UUIDConverter.fromTimeUUID(NULL_UUID);
/**
* Generic constants.
@ -42,6 +42,7 @@ public class ModelConstants {
public static final String ALIAS_PROPERTY = "alias";
public static final String SEARCH_TEXT_PROPERTY = "search_text";
public static final String ADDITIONAL_INFO_PROPERTY = "additional_info";
public static final String ENTITY_TYPE_PROPERTY = "entity_type";
/**
* Cassandra user constants.
@ -66,7 +67,7 @@ public class ModelConstants {
public static final String USER_CREDENTIALS_COLUMN_FAMILY_NAME = "user_credentials";
public static final String USER_CREDENTIALS_USER_ID_PROPERTY = USER_ID_PROPERTY;
public static final String USER_CREDENTIALS_ENABLED_PROPERTY = "enabled";
public static final String USER_CREDENTIALS_PASSWORD_PROPERTY = "password";
public static final String USER_CREDENTIALS_PASSWORD_PROPERTY = "password"; //NOSONAR, the constant used to identify password column name (not password value itself)
public static final String USER_CREDENTIALS_ACTIVATE_TOKEN_PROPERTY = "activate_token";
public static final String USER_CREDENTIALS_RESET_TOKEN_PROPERTY = "reset_token";
@ -155,7 +156,7 @@ public class ModelConstants {
*/
public static final String ENTITY_SUBTYPE_COLUMN_FAMILY_NAME = "entity_subtype";
public static final String ENTITY_SUBTYPE_TENANT_ID_PROPERTY = TENANT_ID_PROPERTY;
public static final String ENTITY_SUBTYPE_ENTITY_TYPE_PROPERTY = "entity_type";
public static final String ENTITY_SUBTYPE_ENTITY_TYPE_PROPERTY = ENTITY_TYPE_PROPERTY;
public static final String ENTITY_SUBTYPE_TYPE_PROPERTY = "type";
/**
@ -250,7 +251,7 @@ public class ModelConstants {
public static final String PLUGIN_API_TOKEN_PROPERTY = "api_token";
public static final String PLUGIN_CLASS_PROPERTY = "plugin_class";
public static final String PLUGIN_ACCESS_PROPERTY = "public_access";
public static final String PLUGIN_STATE_PROPERTY = "state";
public static final String PLUGIN_STATE_PROPERTY = STATE_PROPERTY;
public static final String PLUGIN_CONFIGURATION_PROPERTY = "configuration";
public static final String PLUGIN_BY_API_TOKEN_COLUMN_FAMILY_NAME = "plugin_by_api_token";
@ -277,7 +278,7 @@ public class ModelConstants {
public static final String RULE_COLUMN_FAMILY_NAME = "rule";
public static final String RULE_TENANT_ID_PROPERTY = TENANT_ID_PROPERTY;
public static final String RULE_NAME_PROPERTY = "name";
public static final String RULE_STATE_PROPERTY = "state";
public static final String RULE_STATE_PROPERTY = STATE_PROPERTY;
public static final String RULE_WEIGHT_PROPERTY = "weight";
public static final String RULE_PLUGIN_TOKEN_PROPERTY = "plugin_token";
public static final String RULE_FILTERS = "filters";
@ -294,7 +295,7 @@ public class ModelConstants {
public static final String EVENT_TENANT_ID_PROPERTY = TENANT_ID_PROPERTY;
public static final String EVENT_TYPE_PROPERTY = "event_type";
public static final String EVENT_UID_PROPERTY = "event_uid";
public static final String EVENT_ENTITY_TYPE_PROPERTY = "entity_type";
public static final String EVENT_ENTITY_TYPE_PROPERTY = ENTITY_TYPE_PROPERTY;
public static final String EVENT_ENTITY_ID_PROPERTY = "entity_id";
public static final String EVENT_BODY_PROPERTY = "body";
@ -310,7 +311,7 @@ public class ModelConstants {
public static final String TS_KV_LATEST_CF = "ts_kv_latest_cf";
public static final String ENTITY_TYPE_COLUMN = "entity_type";
public static final String ENTITY_TYPE_COLUMN = ENTITY_TYPE_PROPERTY;
public static final String ENTITY_ID_COLUMN = "entity_id";
public static final String ATTRIBUTE_TYPE_COLUMN = "attribute_type";
public static final String ATTRIBUTE_KEY_COLUMN = "attribute_key";
@ -328,17 +329,17 @@ public class ModelConstants {
public static final String LONG_VALUE_COLUMN = "long_v";
public static final String DOUBLE_VALUE_COLUMN = "dbl_v";
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};
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};
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)};
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)};
public static final String[] MIN_AGGREGATION_COLUMNS = ArrayUtils.addAll(COUNT_AGGREGATION_COLUMNS,
protected static final String[] MIN_AGGREGATION_COLUMNS = ArrayUtils.addAll(COUNT_AGGREGATION_COLUMNS,
new String[]{min(LONG_VALUE_COLUMN), min(DOUBLE_VALUE_COLUMN), min(BOOLEAN_VALUE_COLUMN), min(STRING_VALUE_COLUMN)});
public static final String[] MAX_AGGREGATION_COLUMNS = ArrayUtils.addAll(COUNT_AGGREGATION_COLUMNS,
protected static final String[] MAX_AGGREGATION_COLUMNS = ArrayUtils.addAll(COUNT_AGGREGATION_COLUMNS,
new String[]{max(LONG_VALUE_COLUMN), max(DOUBLE_VALUE_COLUMN), max(BOOLEAN_VALUE_COLUMN), max(STRING_VALUE_COLUMN)});
public static final String[] SUM_AGGREGATION_COLUMNS = ArrayUtils.addAll(COUNT_AGGREGATION_COLUMNS,
protected static final String[] SUM_AGGREGATION_COLUMNS = ArrayUtils.addAll(COUNT_AGGREGATION_COLUMNS,
new String[]{sum(LONG_VALUE_COLUMN), sum(DOUBLE_VALUE_COLUMN)});
public static final String[] AVG_AGGREGATION_COLUMNS = SUM_AGGREGATION_COLUMNS;
protected static final String[] AVG_AGGREGATION_COLUMNS = SUM_AGGREGATION_COLUMNS;
public static String min(String s) {
return "min(" + s + ")";

58
dao/src/main/java/org/thingsboard/server/dao/model/nosql/AdminSettingsEntity.java

@ -19,8 +19,9 @@ import com.datastax.driver.core.utils.UUIDs;
import com.datastax.driver.mapping.annotations.Column;
import com.datastax.driver.mapping.annotations.PartitionKey;
import com.datastax.driver.mapping.annotations.Table;
import com.datastax.driver.mapping.annotations.Transient;
import com.fasterxml.jackson.databind.JsonNode;
import lombok.EqualsAndHashCode;
import lombok.ToString;
import org.thingsboard.server.common.data.AdminSettings;
import org.thingsboard.server.common.data.id.AdminSettingsId;
import org.thingsboard.server.dao.model.BaseEntity;
@ -31,11 +32,10 @@ import java.util.UUID;
import static org.thingsboard.server.dao.model.ModelConstants.*;
@Table(name = ADMIN_SETTINGS_COLUMN_FAMILY_NAME)
@EqualsAndHashCode
@ToString
public final class AdminSettingsEntity implements BaseEntity<AdminSettings> {
@Transient
private static final long serialVersionUID = 899117723388310403L;
@PartitionKey(value = 0)
@Column(name = ID_PROPERTY)
private UUID id;
@ -82,56 +82,6 @@ public final class AdminSettingsEntity implements BaseEntity<AdminSettings> {
this.jsonValue = jsonValue;
}
@Override
public int hashCode() {
final int prime = 31;
int result = 1;
result = prime * result + ((id == null) ? 0 : id.hashCode());
result = prime * result + ((jsonValue == null) ? 0 : jsonValue.hashCode());
result = prime * result + ((key == null) ? 0 : key.hashCode());
return result;
}
@Override
public boolean equals(Object obj) {
if (this == obj)
return true;
if (obj == null)
return false;
if (getClass() != obj.getClass())
return false;
AdminSettingsEntity other = (AdminSettingsEntity) obj;
if (id == null) {
if (other.id != null)
return false;
} else if (!id.equals(other.id))
return false;
if (jsonValue == null) {
if (other.jsonValue != null)
return false;
} else if (!jsonValue.equals(other.jsonValue))
return false;
if (key == null) {
if (other.key != null)
return false;
} else if (!key.equals(other.key))
return false;
return true;
}
@Override
public String toString() {
StringBuilder builder = new StringBuilder();
builder.append("AdminSettingsEntity [id=");
builder.append(id);
builder.append(", key=");
builder.append(key);
builder.append(", jsonValue=");
builder.append(jsonValue);
builder.append("]");
return builder.toString();
}
@Override
public AdminSettings toData() {
AdminSettings adminSettings = new AdminSettings(new AdminSettingsId(id));

7
dao/src/main/java/org/thingsboard/server/dao/model/nosql/AlarmEntity.java

@ -18,6 +18,8 @@ package org.thingsboard.server.dao.model.nosql;
import com.datastax.driver.core.utils.UUIDs;
import com.datastax.driver.mapping.annotations.*;
import com.fasterxml.jackson.databind.JsonNode;
import lombok.EqualsAndHashCode;
import lombok.ToString;
import org.thingsboard.server.common.data.EntityType;
import org.thingsboard.server.common.data.alarm.Alarm;
import org.thingsboard.server.common.data.alarm.AlarmId;
@ -36,11 +38,10 @@ import java.util.UUID;
import static org.thingsboard.server.dao.model.ModelConstants.*;
@Table(name = ALARM_COLUMN_FAMILY_NAME)
@EqualsAndHashCode
@ToString
public final class AlarmEntity implements BaseEntity<Alarm> {
@Transient
private static final long serialVersionUID = -1265181166886910152L;
@ClusteringColumn(value = 1)
@Column(name = ID_PROPERTY)
private UUID id;

84
dao/src/main/java/org/thingsboard/server/dao/model/nosql/AssetEntity.java

@ -19,8 +19,9 @@ import com.datastax.driver.core.utils.UUIDs;
import com.datastax.driver.mapping.annotations.Column;
import com.datastax.driver.mapping.annotations.PartitionKey;
import com.datastax.driver.mapping.annotations.Table;
import com.datastax.driver.mapping.annotations.Transient;
import com.fasterxml.jackson.databind.JsonNode;
import lombok.EqualsAndHashCode;
import lombok.ToString;
import org.thingsboard.server.common.data.asset.Asset;
import org.thingsboard.server.common.data.id.AssetId;
import org.thingsboard.server.common.data.id.CustomerId;
@ -33,11 +34,10 @@ import java.util.UUID;
import static org.thingsboard.server.dao.model.ModelConstants.*;
@Table(name = ASSET_COLUMN_FAMILY_NAME)
@EqualsAndHashCode
@ToString
public final class AssetEntity implements SearchTextEntity<Asset> {
@Transient
private static final long serialVersionUID = -1265181166886910152L;
@PartitionKey(value = 0)
@Column(name = ID_PROPERTY)
private UUID id;
@ -132,7 +132,7 @@ public final class AssetEntity implements SearchTextEntity<Asset> {
@Override
public String getSearchTextSource() {
return name;
return getName();
}
@Override
@ -144,80 +144,6 @@ public final class AssetEntity implements SearchTextEntity<Asset> {
return searchText;
}
@Override
public int hashCode() {
final int prime = 31;
int result = 1;
result = prime * result + ((additionalInfo == null) ? 0 : additionalInfo.hashCode());
result = prime * result + ((customerId == null) ? 0 : customerId.hashCode());
result = prime * result + ((id == null) ? 0 : id.hashCode());
result = prime * result + ((name == null) ? 0 : name.hashCode());
result = prime * result + ((type == null) ? 0 : type.hashCode());
result = prime * result + ((tenantId == null) ? 0 : tenantId.hashCode());
return result;
}
@Override
public boolean equals(Object obj) {
if (this == obj)
return true;
if (obj == null)
return false;
if (getClass() != obj.getClass())
return false;
AssetEntity other = (AssetEntity) obj;
if (additionalInfo == null) {
if (other.additionalInfo != null)
return false;
} else if (!additionalInfo.equals(other.additionalInfo))
return false;
if (customerId == null) {
if (other.customerId != null)
return false;
} else if (!customerId.equals(other.customerId))
return false;
if (id == null) {
if (other.id != null)
return false;
} else if (!id.equals(other.id))
return false;
if (name == null) {
if (other.name != null)
return false;
} else if (!name.equals(other.name))
return false;
if (type == null) {
if (other.type != null)
return false;
} else if (!type.equals(other.type))
return false;
if (tenantId == null) {
if (other.tenantId != null)
return false;
} else if (!tenantId.equals(other.tenantId))
return false;
return true;
}
@Override
public String toString() {
StringBuilder builder = new StringBuilder();
builder.append("AssetEntity [id=");
builder.append(id);
builder.append(", tenantId=");
builder.append(tenantId);
builder.append(", customerId=");
builder.append(customerId);
builder.append(", name=");
builder.append(name);
builder.append(", type=");
builder.append(type);
builder.append(", additionalInfo=");
builder.append(additionalInfo);
builder.append("]");
return builder.toString();
}
@Override
public Asset toData() {
Asset asset = new Asset(new AssetId(id));

4
dao/src/main/java/org/thingsboard/server/dao/model/nosql/ComponentDescriptorEntity.java

@ -36,8 +36,6 @@ import static org.thingsboard.server.dao.model.ModelConstants.*;
@Table(name = COMPONENT_DESCRIPTOR_COLUMN_FAMILY_NAME)
public class ComponentDescriptorEntity implements SearchTextEntity<ComponentDescriptor> {
private static final long serialVersionUID = 1L;
@PartitionKey
@Column(name = ID_PROPERTY)
private UUID id;
@ -160,6 +158,6 @@ public class ComponentDescriptorEntity implements SearchTextEntity<ComponentDesc
@Override
public String getSearchTextSource() {
return searchText;
return getSearchText();
}
}

132
dao/src/main/java/org/thingsboard/server/dao/model/nosql/CustomerEntity.java

@ -19,8 +19,9 @@ import com.datastax.driver.core.utils.UUIDs;
import com.datastax.driver.mapping.annotations.Column;
import com.datastax.driver.mapping.annotations.PartitionKey;
import com.datastax.driver.mapping.annotations.Table;
import com.datastax.driver.mapping.annotations.Transient;
import com.fasterxml.jackson.databind.JsonNode;
import lombok.EqualsAndHashCode;
import lombok.ToString;
import org.thingsboard.server.common.data.Customer;
import org.thingsboard.server.common.data.id.CustomerId;
import org.thingsboard.server.common.data.id.TenantId;
@ -32,11 +33,10 @@ import java.util.UUID;
import static org.thingsboard.server.dao.model.ModelConstants.*;
@Table(name = CUSTOMER_COLUMN_FAMILY_NAME)
@EqualsAndHashCode
@ToString
public final class CustomerEntity implements SearchTextEntity<Customer> {
@Transient
private static final long serialVersionUID = -7732527103760948490L;
@PartitionKey(value = 0)
@Column(name = ID_PROPERTY)
private UUID id;
@ -197,7 +197,7 @@ public final class CustomerEntity implements SearchTextEntity<Customer> {
@Override
public String getSearchTextSource() {
return title;
return getTitle();
}
@Override
@ -209,128 +209,6 @@ public final class CustomerEntity implements SearchTextEntity<Customer> {
return searchText;
}
@Override
public int hashCode() {
final int prime = 31;
int result = 1;
result = prime * result + ((additionalInfo == null) ? 0 : additionalInfo.hashCode());
result = prime * result + ((address == null) ? 0 : address.hashCode());
result = prime * result + ((address2 == null) ? 0 : address2.hashCode());
result = prime * result + ((city == null) ? 0 : city.hashCode());
result = prime * result + ((country == null) ? 0 : country.hashCode());
result = prime * result + ((email == null) ? 0 : email.hashCode());
result = prime * result + ((id == null) ? 0 : id.hashCode());
result = prime * result + ((phone == null) ? 0 : phone.hashCode());
result = prime * result + ((state == null) ? 0 : state.hashCode());
result = prime * result + ((tenantId == null) ? 0 : tenantId.hashCode());
result = prime * result + ((title == null) ? 0 : title.hashCode());
result = prime * result + ((zip == null) ? 0 : zip.hashCode());
return result;
}
@Override
public boolean equals(Object obj) {
if (this == obj)
return true;
if (obj == null)
return false;
if (getClass() != obj.getClass())
return false;
CustomerEntity other = (CustomerEntity) obj;
if (additionalInfo == null) {
if (other.additionalInfo != null)
return false;
} else if (!additionalInfo.equals(other.additionalInfo))
return false;
if (address == null) {
if (other.address != null)
return false;
} else if (!address.equals(other.address))
return false;
if (address2 == null) {
if (other.address2 != null)
return false;
} else if (!address2.equals(other.address2))
return false;
if (city == null) {
if (other.city != null)
return false;
} else if (!city.equals(other.city))
return false;
if (country == null) {
if (other.country != null)
return false;
} else if (!country.equals(other.country))
return false;
if (email == null) {
if (other.email != null)
return false;
} else if (!email.equals(other.email))
return false;
if (id == null) {
if (other.id != null)
return false;
} else if (!id.equals(other.id))
return false;
if (phone == null) {
if (other.phone != null)
return false;
} else if (!phone.equals(other.phone))
return false;
if (state == null) {
if (other.state != null)
return false;
} else if (!state.equals(other.state))
return false;
if (tenantId == null) {
if (other.tenantId != null)
return false;
} else if (!tenantId.equals(other.tenantId))
return false;
if (title == null) {
if (other.title != null)
return false;
} else if (!title.equals(other.title))
return false;
if (zip == null) {
if (other.zip != null)
return false;
} else if (!zip.equals(other.zip))
return false;
return true;
}
@Override
public String toString() {
StringBuilder builder = new StringBuilder();
builder.append("CustomerEntity [id=");
builder.append(id);
builder.append(", tenantId=");
builder.append(tenantId);
builder.append(", title=");
builder.append(title);
builder.append(", country=");
builder.append(country);
builder.append(", state=");
builder.append(state);
builder.append(", city=");
builder.append(city);
builder.append(", address=");
builder.append(address);
builder.append(", address2=");
builder.append(address2);
builder.append(", zip=");
builder.append(zip);
builder.append(", phone=");
builder.append(phone);
builder.append(", email=");
builder.append(email);
builder.append(", additionalInfo=");
builder.append(additionalInfo);
builder.append("]");
return builder.toString();
}
@Override
public Customer toData() {
Customer customer = new Customer(new CustomerId(id));

84
dao/src/main/java/org/thingsboard/server/dao/model/nosql/DashboardEntity.java

@ -19,8 +19,9 @@ import com.datastax.driver.core.utils.UUIDs;
import com.datastax.driver.mapping.annotations.Column;
import com.datastax.driver.mapping.annotations.PartitionKey;
import com.datastax.driver.mapping.annotations.Table;
import com.datastax.driver.mapping.annotations.Transient;
import com.fasterxml.jackson.databind.JsonNode;
import lombok.EqualsAndHashCode;
import lombok.ToString;
import org.thingsboard.server.common.data.Dashboard;
import org.thingsboard.server.common.data.id.CustomerId;
import org.thingsboard.server.common.data.id.DashboardId;
@ -33,11 +34,10 @@ import java.util.UUID;
import static org.thingsboard.server.dao.model.ModelConstants.*;
@Table(name = DASHBOARD_COLUMN_FAMILY_NAME)
@EqualsAndHashCode
@ToString
public final class DashboardEntity implements SearchTextEntity<Dashboard> {
@Transient
private static final long serialVersionUID = 2998395951247446191L;
@PartitionKey(value = 0)
@Column(name = ID_PROPERTY)
private UUID id;
@ -119,7 +119,7 @@ public final class DashboardEntity implements SearchTextEntity<Dashboard> {
@Override
public String getSearchTextSource() {
return title;
return getTitle();
}
@Override
@ -131,80 +131,6 @@ public final class DashboardEntity implements SearchTextEntity<Dashboard> {
return searchText;
}
@Override
public int hashCode() {
final int prime = 31;
int result = 1;
result = prime * result + ((configuration == null) ? 0 : configuration.hashCode());
result = prime * result + ((customerId == null) ? 0 : customerId.hashCode());
result = prime * result + ((id == null) ? 0 : id.hashCode());
result = prime * result + ((searchText == null) ? 0 : searchText.hashCode());
result = prime * result + ((tenantId == null) ? 0 : tenantId.hashCode());
result = prime * result + ((title == null) ? 0 : title.hashCode());
return result;
}
@Override
public boolean equals(Object obj) {
if (this == obj)
return true;
if (obj == null)
return false;
if (getClass() != obj.getClass())
return false;
DashboardEntity other = (DashboardEntity) obj;
if (configuration == null) {
if (other.configuration != null)
return false;
} else if (!configuration.equals(other.configuration))
return false;
if (customerId == null) {
if (other.customerId != null)
return false;
} else if (!customerId.equals(other.customerId))
return false;
if (id == null) {
if (other.id != null)
return false;
} else if (!id.equals(other.id))
return false;
if (searchText == null) {
if (other.searchText != null)
return false;
} else if (!searchText.equals(other.searchText))
return false;
if (tenantId == null) {
if (other.tenantId != null)
return false;
} else if (!tenantId.equals(other.tenantId))
return false;
if (title == null) {
if (other.title != null)
return false;
} else if (!title.equals(other.title))
return false;
return true;
}
@Override
public String toString() {
StringBuilder builder = new StringBuilder();
builder.append("DashboardEntity [id=");
builder.append(id);
builder.append(", tenantId=");
builder.append(tenantId);
builder.append(", customerId=");
builder.append(customerId);
builder.append(", title=");
builder.append(title);
builder.append(", searchText=");
builder.append(searchText);
builder.append(", configuration=");
builder.append(configuration);
builder.append("]");
return builder.toString();
}
@Override
public Dashboard toData() {
Dashboard dashboard = new Dashboard(new DashboardId(id));

76
dao/src/main/java/org/thingsboard/server/dao/model/nosql/DashboardInfoEntity.java

@ -19,7 +19,8 @@ import com.datastax.driver.core.utils.UUIDs;
import com.datastax.driver.mapping.annotations.Column;
import com.datastax.driver.mapping.annotations.PartitionKey;
import com.datastax.driver.mapping.annotations.Table;
import com.datastax.driver.mapping.annotations.Transient;
import lombok.EqualsAndHashCode;
import lombok.ToString;
import org.thingsboard.server.common.data.DashboardInfo;
import org.thingsboard.server.common.data.id.CustomerId;
import org.thingsboard.server.common.data.id.DashboardId;
@ -31,11 +32,10 @@ import java.util.UUID;
import static org.thingsboard.server.dao.model.ModelConstants.*;
@Table(name = DASHBOARD_COLUMN_FAMILY_NAME)
@EqualsAndHashCode
@ToString
public class DashboardInfoEntity implements SearchTextEntity<DashboardInfo> {
@Transient
private static final long serialVersionUID = 2998395951247446191L;
@PartitionKey(value = 0)
@Column(name = ID_PROPERTY)
private UUID id;
@ -105,7 +105,7 @@ public class DashboardInfoEntity implements SearchTextEntity<DashboardInfo> {
@Override
public String getSearchTextSource() {
return title;
return getTitle();
}
@Override
@ -117,72 +117,6 @@ public class DashboardInfoEntity implements SearchTextEntity<DashboardInfo> {
return searchText;
}
@Override
public int hashCode() {
final int prime = 31;
int result = 1;
result = prime * result + ((customerId == null) ? 0 : customerId.hashCode());
result = prime * result + ((id == null) ? 0 : id.hashCode());
result = prime * result + ((searchText == null) ? 0 : searchText.hashCode());
result = prime * result + ((tenantId == null) ? 0 : tenantId.hashCode());
result = prime * result + ((title == null) ? 0 : title.hashCode());
return result;
}
@Override
public boolean equals(Object obj) {
if (this == obj)
return true;
if (obj == null)
return false;
if (getClass() != obj.getClass())
return false;
DashboardInfoEntity other = (DashboardInfoEntity) obj;
if (customerId == null) {
if (other.customerId != null)
return false;
} else if (!customerId.equals(other.customerId))
return false;
if (id == null) {
if (other.id != null)
return false;
} else if (!id.equals(other.id))
return false;
if (searchText == null) {
if (other.searchText != null)
return false;
} else if (!searchText.equals(other.searchText))
return false;
if (tenantId == null) {
if (other.tenantId != null)
return false;
} else if (!tenantId.equals(other.tenantId))
return false;
if (title == null) {
if (other.title != null)
return false;
} else if (!title.equals(other.title))
return false;
return true;
}
@Override
public String toString() {
StringBuilder builder = new StringBuilder();
builder.append("DashboardInfoEntity [id=");
builder.append(id);
builder.append(", tenantId=");
builder.append(tenantId);
builder.append(", customerId=");
builder.append(customerId);
builder.append(", title=");
builder.append(title);
builder.append(", searchText=");
builder.append(searchText);
builder.append("]");
return builder.toString();
}
@Override
public DashboardInfo toData() {
DashboardInfo dashboardInfo = new DashboardInfo(new DashboardId(id));

71
dao/src/main/java/org/thingsboard/server/dao/model/nosql/DeviceCredentialsEntity.java

@ -19,7 +19,8 @@ import com.datastax.driver.core.utils.UUIDs;
import com.datastax.driver.mapping.annotations.Column;
import com.datastax.driver.mapping.annotations.PartitionKey;
import com.datastax.driver.mapping.annotations.Table;
import com.datastax.driver.mapping.annotations.Transient;
import lombok.EqualsAndHashCode;
import lombok.ToString;
import org.thingsboard.server.common.data.id.DeviceCredentialsId;
import org.thingsboard.server.common.data.id.DeviceId;
import org.thingsboard.server.common.data.security.DeviceCredentials;
@ -32,11 +33,10 @@ import java.util.UUID;
import static org.thingsboard.server.dao.model.ModelConstants.*;
@Table(name = DEVICE_CREDENTIALS_COLUMN_FAMILY_NAME)
@EqualsAndHashCode
@ToString
public final class DeviceCredentialsEntity implements BaseEntity<DeviceCredentials> {
@Transient
private static final long serialVersionUID = -2667310560260623272L;
@PartitionKey(value = 0)
@Column(name = ID_PROPERTY)
private UUID id;
@ -109,69 +109,6 @@ public final class DeviceCredentialsEntity implements BaseEntity<DeviceCredentia
this.credentialsValue = credentialsValue;
}
@Override
public int hashCode() {
final int prime = 31;
int result = 1;
result = prime * result + ((credentialsId == null) ? 0 : credentialsId.hashCode());
result = prime * result + ((credentialsType == null) ? 0 : credentialsType.hashCode());
result = prime * result + ((credentialsValue == null) ? 0 : credentialsValue.hashCode());
result = prime * result + ((deviceId == null) ? 0 : deviceId.hashCode());
result = prime * result + ((id == null) ? 0 : id.hashCode());
return result;
}
@Override
public boolean equals(Object obj) {
if (this == obj)
return true;
if (obj == null)
return false;
if (getClass() != obj.getClass())
return false;
DeviceCredentialsEntity other = (DeviceCredentialsEntity) obj;
if (credentialsId == null) {
if (other.credentialsId != null)
return false;
} else if (!credentialsId.equals(other.credentialsId))
return false;
if (credentialsType != other.credentialsType)
return false;
if (credentialsValue == null) {
if (other.credentialsValue != null)
return false;
} else if (!credentialsValue.equals(other.credentialsValue))
return false;
if (deviceId == null) {
if (other.deviceId != null)
return false;
} else if (!deviceId.equals(other.deviceId))
return false;
if (id == null) {
if (other.id != null)
return false;
} else if (!id.equals(other.id))
return false;
return true;
}
@Override
public String toString() {
StringBuilder builder = new StringBuilder();
builder.append("DeviceCredentialsEntity [id=");
builder.append(id);
builder.append(", deviceId=");
builder.append(deviceId);
builder.append(", credentialsType=");
builder.append(credentialsType);
builder.append(", credentialsId=");
builder.append(credentialsId);
builder.append(", credentialsValue=");
builder.append(credentialsValue);
builder.append("]");
return builder.toString();
}
@Override
public DeviceCredentials toData() {
DeviceCredentials deviceCredentials = new DeviceCredentials(new DeviceCredentialsId(id));

84
dao/src/main/java/org/thingsboard/server/dao/model/nosql/DeviceEntity.java

@ -19,8 +19,9 @@ import com.datastax.driver.core.utils.UUIDs;
import com.datastax.driver.mapping.annotations.Column;
import com.datastax.driver.mapping.annotations.PartitionKey;
import com.datastax.driver.mapping.annotations.Table;
import com.datastax.driver.mapping.annotations.Transient;
import com.fasterxml.jackson.databind.JsonNode;
import lombok.EqualsAndHashCode;
import lombok.ToString;
import org.thingsboard.server.common.data.Device;
import org.thingsboard.server.common.data.id.CustomerId;
import org.thingsboard.server.common.data.id.DeviceId;
@ -33,11 +34,10 @@ import java.util.UUID;
import static org.thingsboard.server.dao.model.ModelConstants.*;
@Table(name = DEVICE_COLUMN_FAMILY_NAME)
@EqualsAndHashCode
@ToString
public final class DeviceEntity implements SearchTextEntity<Device> {
@Transient
private static final long serialVersionUID = -1265181166886910152L;
@PartitionKey(value = 0)
@Column(name = ID_PROPERTY)
private UUID id;
@ -132,7 +132,7 @@ public final class DeviceEntity implements SearchTextEntity<Device> {
@Override
public String getSearchTextSource() {
return name;
return getName();
}
@Override
@ -144,80 +144,6 @@ public final class DeviceEntity implements SearchTextEntity<Device> {
return searchText;
}
@Override
public int hashCode() {
final int prime = 31;
int result = 1;
result = prime * result + ((additionalInfo == null) ? 0 : additionalInfo.hashCode());
result = prime * result + ((customerId == null) ? 0 : customerId.hashCode());
result = prime * result + ((id == null) ? 0 : id.hashCode());
result = prime * result + ((name == null) ? 0 : name.hashCode());
result = prime * result + ((type == null) ? 0 : type.hashCode());
result = prime * result + ((tenantId == null) ? 0 : tenantId.hashCode());
return result;
}
@Override
public boolean equals(Object obj) {
if (this == obj)
return true;
if (obj == null)
return false;
if (getClass() != obj.getClass())
return false;
DeviceEntity other = (DeviceEntity) obj;
if (additionalInfo == null) {
if (other.additionalInfo != null)
return false;
} else if (!additionalInfo.equals(other.additionalInfo))
return false;
if (customerId == null) {
if (other.customerId != null)
return false;
} else if (!customerId.equals(other.customerId))
return false;
if (id == null) {
if (other.id != null)
return false;
} else if (!id.equals(other.id))
return false;
if (name == null) {
if (other.name != null)
return false;
} else if (!name.equals(other.name))
return false;
if (type == null) {
if (other.type != null)
return false;
} else if (!type.equals(other.type))
return false;
if (tenantId == null) {
if (other.tenantId != null)
return false;
} else if (!tenantId.equals(other.tenantId))
return false;
return true;
}
@Override
public String toString() {
StringBuilder builder = new StringBuilder();
builder.append("DeviceEntity [id=");
builder.append(id);
builder.append(", tenantId=");
builder.append(tenantId);
builder.append(", customerId=");
builder.append(customerId);
builder.append(", name=");
builder.append(name);
builder.append(", type=");
builder.append(type);
builder.append(", additionalInfo=");
builder.append(additionalInfo);
builder.append("]");
return builder.toString();
}
@Override
public Device toData() {
Device device = new Device(new DeviceId(id));

3
dao/src/main/java/org/thingsboard/server/dao/model/nosql/EventEntity.java

@ -41,9 +41,6 @@ import static org.thingsboard.server.dao.model.ModelConstants.*;
@Table(name = EVENT_COLUMN_FAMILY_NAME)
public class EventEntity implements BaseEntity<Event> {
@Transient
private static final long serialVersionUID = -1265181166886910153L;
@Column(name = ID_PROPERTY)
private UUID id;

32
dao/src/main/java/org/thingsboard/server/dao/model/nosql/PluginMetaDataEntity.java

@ -18,6 +18,8 @@ package org.thingsboard.server.dao.model.nosql;
import com.datastax.driver.core.utils.UUIDs;
import com.datastax.driver.mapping.annotations.*;
import com.fasterxml.jackson.databind.JsonNode;
import lombok.EqualsAndHashCode;
import lombok.ToString;
import org.thingsboard.server.common.data.id.PluginId;
import org.thingsboard.server.common.data.id.TenantId;
import org.thingsboard.server.common.data.plugin.ComponentLifecycleState;
@ -32,11 +34,10 @@ import java.util.UUID;
import static org.thingsboard.server.dao.model.ModelConstants.*;
@Table(name = PLUGIN_COLUMN_FAMILY_NAME)
@EqualsAndHashCode
@ToString
public class PluginMetaDataEntity implements SearchTextEntity<PluginMetaData> {
@Transient
private static final long serialVersionUID = -5231612734979707866L;
@PartitionKey
@Column(name = ID_PROPERTY)
private UUID id;
@ -89,7 +90,7 @@ public class PluginMetaDataEntity implements SearchTextEntity<PluginMetaData> {
@Override
public String getSearchTextSource() {
return searchText;
return getSearchText();
}
@Override
@ -190,27 +191,4 @@ public class PluginMetaDataEntity implements SearchTextEntity<PluginMetaData> {
return data;
}
@Override
public boolean equals(Object o) {
if (this == o)
return true;
if (o == null || getClass() != o.getClass())
return false;
PluginMetaDataEntity entity = (PluginMetaDataEntity) o;
return Objects.equals(id, entity.id) && Objects.equals(apiToken, entity.apiToken) && Objects.equals(tenantId, entity.tenantId)
&& Objects.equals(name, entity.name) && Objects.equals(clazz, entity.clazz) && Objects.equals(state, entity.state)
&& Objects.equals(configuration, entity.configuration)
&& Objects.equals(searchText, entity.searchText);
}
@Override
public int hashCode() {
return Objects.hash(id, apiToken, tenantId, name, clazz, state, configuration, searchText);
}
@Override
public String toString() {
return "PluginMetaDataEntity{" + "id=" + id + ", apiToken='" + apiToken + '\'' + ", tenantId=" + tenantId + ", name='" + name + '\'' + ", clazz='"
+ clazz + '\'' + ", state=" + state + ", configuration=" + configuration + ", searchText='" + searchText + '\'' + '}';
}
}

41
dao/src/main/java/org/thingsboard/server/dao/model/nosql/RuleMetaDataEntity.java

@ -21,6 +21,8 @@ import com.datastax.driver.mapping.annotations.Column;
import com.datastax.driver.mapping.annotations.PartitionKey;
import com.datastax.driver.mapping.annotations.Table;
import com.fasterxml.jackson.databind.JsonNode;
import lombok.EqualsAndHashCode;
import lombok.ToString;
import org.thingsboard.server.common.data.id.RuleId;
import org.thingsboard.server.common.data.id.TenantId;
import org.thingsboard.server.common.data.plugin.ComponentLifecycleState;
@ -30,17 +32,15 @@ import org.thingsboard.server.dao.model.SearchTextEntity;
import org.thingsboard.server.dao.model.type.ComponentLifecycleStateCodec;
import org.thingsboard.server.dao.model.type.JsonCodec;
import javax.persistence.Transient;
import java.util.Objects;
import java.util.UUID;
import static org.thingsboard.server.dao.model.ModelConstants.*;
@Table(name = RULE_COLUMN_FAMILY_NAME)
@EqualsAndHashCode
@ToString
public class RuleMetaDataEntity implements SearchTextEntity<RuleMetaData> {
@Transient
private static final long serialVersionUID = 4011728715100800304L;
@PartitionKey
@Column(name = ID_PROPERTY)
private UUID id;
@ -87,7 +87,7 @@ public class RuleMetaDataEntity implements SearchTextEntity<RuleMetaData> {
@Override
public String getSearchTextSource() {
return searchText;
return getSearchText();
}
@Override
@ -197,35 +197,4 @@ public class RuleMetaDataEntity implements SearchTextEntity<RuleMetaData> {
return rule;
}
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
RuleMetaDataEntity that = (RuleMetaDataEntity) o;
return weight == that.weight &&
Objects.equals(id, that.id) &&
Objects.equals(tenantId, that.tenantId) &&
Objects.equals(name, that.name) &&
Objects.equals(pluginToken, that.pluginToken) &&
Objects.equals(state, that.state) &&
Objects.equals(searchText, that.searchText);
}
@Override
public int hashCode() {
return Objects.hash(id, tenantId, name, pluginToken, state, weight, searchText);
}
@Override
public String toString() {
return "RuleMetaDataEntity{" +
"id=" + id +
", tenantId=" + tenantId +
", name='" + name + '\'' +
", pluginToken='" + pluginToken + '\'' +
", state='" + state + '\'' +
", weight=" + weight +
", searchText='" + searchText + '\'' +
'}';
}
}

132
dao/src/main/java/org/thingsboard/server/dao/model/nosql/TenantEntity.java

@ -19,8 +19,9 @@ import com.datastax.driver.core.utils.UUIDs;
import com.datastax.driver.mapping.annotations.Column;
import com.datastax.driver.mapping.annotations.PartitionKey;
import com.datastax.driver.mapping.annotations.Table;
import com.datastax.driver.mapping.annotations.Transient;
import com.fasterxml.jackson.databind.JsonNode;
import lombok.EqualsAndHashCode;
import lombok.ToString;
import org.thingsboard.server.common.data.Tenant;
import org.thingsboard.server.common.data.id.TenantId;
import org.thingsboard.server.dao.model.SearchTextEntity;
@ -31,11 +32,10 @@ import java.util.UUID;
import static org.thingsboard.server.dao.model.ModelConstants.*;
@Table(name = TENANT_COLUMN_FAMILY_NAME)
@EqualsAndHashCode
@ToString
public final class TenantEntity implements SearchTextEntity<Tenant> {
@Transient
private static final long serialVersionUID = -6198635547142409206L;
@PartitionKey(value = 0)
@Column(name = ID_PROPERTY)
private UUID id;
@ -195,7 +195,7 @@ public final class TenantEntity implements SearchTextEntity<Tenant> {
@Override
public String getSearchTextSource() {
return title;
return getTitle();
}
@Override
@ -207,128 +207,6 @@ public final class TenantEntity implements SearchTextEntity<Tenant> {
return searchText;
}
@Override
public int hashCode() {
final int prime = 31;
int result = 1;
result = prime * result + ((additionalInfo == null) ? 0 : additionalInfo.hashCode());
result = prime * result + ((address == null) ? 0 : address.hashCode());
result = prime * result + ((address2 == null) ? 0 : address2.hashCode());
result = prime * result + ((city == null) ? 0 : city.hashCode());
result = prime * result + ((country == null) ? 0 : country.hashCode());
result = prime * result + ((email == null) ? 0 : email.hashCode());
result = prime * result + ((id == null) ? 0 : id.hashCode());
result = prime * result + ((phone == null) ? 0 : phone.hashCode());
result = prime * result + ((region == null) ? 0 : region.hashCode());
result = prime * result + ((state == null) ? 0 : state.hashCode());
result = prime * result + ((title == null) ? 0 : title.hashCode());
result = prime * result + ((zip == null) ? 0 : zip.hashCode());
return result;
}
@Override
public boolean equals(Object obj) {
if (this == obj)
return true;
if (obj == null)
return false;
if (getClass() != obj.getClass())
return false;
TenantEntity other = (TenantEntity) obj;
if (additionalInfo == null) {
if (other.additionalInfo != null)
return false;
} else if (!additionalInfo.equals(other.additionalInfo))
return false;
if (address == null) {
if (other.address != null)
return false;
} else if (!address.equals(other.address))
return false;
if (address2 == null) {
if (other.address2 != null)
return false;
} else if (!address2.equals(other.address2))
return false;
if (city == null) {
if (other.city != null)
return false;
} else if (!city.equals(other.city))
return false;
if (country == null) {
if (other.country != null)
return false;
} else if (!country.equals(other.country))
return false;
if (email == null) {
if (other.email != null)
return false;
} else if (!email.equals(other.email))
return false;
if (id == null) {
if (other.id != null)
return false;
} else if (!id.equals(other.id))
return false;
if (phone == null) {
if (other.phone != null)
return false;
} else if (!phone.equals(other.phone))
return false;
if (region == null) {
if (other.region != null)
return false;
} else if (!region.equals(other.region))
return false;
if (state == null) {
if (other.state != null)
return false;
} else if (!state.equals(other.state))
return false;
if (title == null) {
if (other.title != null)
return false;
} else if (!title.equals(other.title))
return false;
if (zip == null) {
if (other.zip != null)
return false;
} else if (!zip.equals(other.zip))
return false;
return true;
}
@Override
public String toString() {
StringBuilder builder = new StringBuilder();
builder.append("TenantEntity [id=");
builder.append(id);
builder.append(", title=");
builder.append(title);
builder.append(", region=");
builder.append(region);
builder.append(", country=");
builder.append(country);
builder.append(", state=");
builder.append(state);
builder.append(", city=");
builder.append(city);
builder.append(", address=");
builder.append(address);
builder.append(", address2=");
builder.append(address2);
builder.append(", zip=");
builder.append(zip);
builder.append(", phone=");
builder.append(phone);
builder.append(", email=");
builder.append(email);
builder.append(", additionalInfo=");
builder.append(additionalInfo);
builder.append("]");
return builder.toString();
}
@Override
public Tenant toData() {
Tenant tenant = new Tenant(new TenantId(id));

58
dao/src/main/java/org/thingsboard/server/dao/model/nosql/UserCredentialsEntity.java

@ -19,7 +19,7 @@ import com.datastax.driver.core.utils.UUIDs;
import com.datastax.driver.mapping.annotations.Column;
import com.datastax.driver.mapping.annotations.PartitionKey;
import com.datastax.driver.mapping.annotations.Table;
import com.datastax.driver.mapping.annotations.Transient;
import lombok.EqualsAndHashCode;
import org.thingsboard.server.common.data.id.UserCredentialsId;
import org.thingsboard.server.common.data.id.UserId;
import org.thingsboard.server.common.data.security.UserCredentials;
@ -30,11 +30,9 @@ import java.util.UUID;
import static org.thingsboard.server.dao.model.ModelConstants.*;
@Table(name = USER_CREDENTIALS_COLUMN_FAMILY_NAME)
@EqualsAndHashCode
public final class UserCredentialsEntity implements BaseEntity<UserCredentials> {
@Transient
private static final long serialVersionUID = 1348221414123438374L;
@PartitionKey(value = 0)
@Column(name = ID_PROPERTY)
private UUID id;
@ -119,58 +117,6 @@ public final class UserCredentialsEntity implements BaseEntity<UserCredentials>
this.resetToken = resetToken;
}
@Override
public int hashCode() {
final int prime = 31;
int result = 1;
result = prime * result + ((activateToken == null) ? 0 : activateToken.hashCode());
result = prime * result + (enabled ? 1231 : 1237);
result = prime * result + ((id == null) ? 0 : id.hashCode());
result = prime * result + ((password == null) ? 0 : password.hashCode());
result = prime * result + ((resetToken == null) ? 0 : resetToken.hashCode());
result = prime * result + ((userId == null) ? 0 : userId.hashCode());
return result;
}
@Override
public boolean equals(Object obj) {
if (this == obj)
return true;
if (obj == null)
return false;
if (getClass() != obj.getClass())
return false;
UserCredentialsEntity other = (UserCredentialsEntity) obj;
if (activateToken == null) {
if (other.activateToken != null)
return false;
} else if (!activateToken.equals(other.activateToken))
return false;
if (enabled != other.enabled)
return false;
if (id == null) {
if (other.id != null)
return false;
} else if (!id.equals(other.id))
return false;
if (password == null) {
if (other.password != null)
return false;
} else if (!password.equals(other.password))
return false;
if (resetToken == null) {
if (other.resetToken != null)
return false;
} else if (!resetToken.equals(other.resetToken))
return false;
if (userId == null) {
if (other.userId != null)
return false;
} else if (!userId.equals(other.userId))
return false;
return true;
}
@Override
public UserCredentials toData() {
UserCredentials userCredentials = new UserCredentials(new UserCredentialsId(id));

97
dao/src/main/java/org/thingsboard/server/dao/model/nosql/UserEntity.java

@ -19,8 +19,9 @@ import com.datastax.driver.core.utils.UUIDs;
import com.datastax.driver.mapping.annotations.Column;
import com.datastax.driver.mapping.annotations.PartitionKey;
import com.datastax.driver.mapping.annotations.Table;
import com.datastax.driver.mapping.annotations.Transient;
import com.fasterxml.jackson.databind.JsonNode;
import lombok.EqualsAndHashCode;
import lombok.ToString;
import org.thingsboard.server.common.data.User;
import org.thingsboard.server.common.data.id.CustomerId;
import org.thingsboard.server.common.data.id.TenantId;
@ -35,11 +36,10 @@ import java.util.UUID;
import static org.thingsboard.server.dao.model.ModelConstants.*;
@Table(name = USER_COLUMN_FAMILY_NAME)
@EqualsAndHashCode
@ToString
public final class UserEntity implements SearchTextEntity<User> {
@Transient
private static final long serialVersionUID = -7740338274987723489L;
@PartitionKey(value = 0)
@Column(name = ID_PROPERTY)
private UUID id;
@ -158,7 +158,7 @@ public final class UserEntity implements SearchTextEntity<User> {
@Override
public String getSearchTextSource() {
return email;
return getEmail();
}
@Override
@ -170,93 +170,6 @@ public final class UserEntity implements SearchTextEntity<User> {
return searchText;
}
@Override
public int hashCode() {
final int prime = 31;
int result = 1;
result = prime * result + ((additionalInfo == null) ? 0 : additionalInfo.hashCode());
result = prime * result + ((authority == null) ? 0 : authority.hashCode());
result = prime * result + ((customerId == null) ? 0 : customerId.hashCode());
result = prime * result + ((email == null) ? 0 : email.hashCode());
result = prime * result + ((firstName == null) ? 0 : firstName.hashCode());
result = prime * result + ((id == null) ? 0 : id.hashCode());
result = prime * result + ((lastName == null) ? 0 : lastName.hashCode());
result = prime * result + ((tenantId == null) ? 0 : tenantId.hashCode());
return result;
}
@Override
public boolean equals(Object obj) {
if (this == obj)
return true;
if (obj == null)
return false;
if (getClass() != obj.getClass())
return false;
UserEntity other = (UserEntity) obj;
if (additionalInfo == null) {
if (other.additionalInfo != null)
return false;
} else if (!additionalInfo.equals(other.additionalInfo))
return false;
if (authority != other.authority)
return false;
if (customerId == null) {
if (other.customerId != null)
return false;
} else if (!customerId.equals(other.customerId))
return false;
if (email == null) {
if (other.email != null)
return false;
} else if (!email.equals(other.email))
return false;
if (firstName == null) {
if (other.firstName != null)
return false;
} else if (!firstName.equals(other.firstName))
return false;
if (id == null) {
if (other.id != null)
return false;
} else if (!id.equals(other.id))
return false;
if (lastName == null) {
if (other.lastName != null)
return false;
} else if (!lastName.equals(other.lastName))
return false;
if (tenantId == null) {
if (other.tenantId != null)
return false;
} else if (!tenantId.equals(other.tenantId))
return false;
return true;
}
@Override
public String toString() {
StringBuilder builder = new StringBuilder();
builder.append("UserEntity [id=");
builder.append(id);
builder.append(", authority=");
builder.append(authority);
builder.append(", tenantId=");
builder.append(tenantId);
builder.append(", customerId=");
builder.append(customerId);
builder.append(", email=");
builder.append(email);
builder.append(", firstName=");
builder.append(firstName);
builder.append(", lastName=");
builder.append(lastName);
builder.append(", additionalInfo=");
builder.append(additionalInfo);
builder.append("]");
return builder.toString();
}
@Override
public User toData() {
User user = new User(new UserId(id));

47
dao/src/main/java/org/thingsboard/server/dao/model/nosql/WidgetTypeEntity.java

@ -19,8 +19,9 @@ import com.datastax.driver.core.utils.UUIDs;
import com.datastax.driver.mapping.annotations.Column;
import com.datastax.driver.mapping.annotations.PartitionKey;
import com.datastax.driver.mapping.annotations.Table;
import com.datastax.driver.mapping.annotations.Transient;
import com.fasterxml.jackson.databind.JsonNode;
import lombok.EqualsAndHashCode;
import lombok.ToString;
import org.thingsboard.server.common.data.id.TenantId;
import org.thingsboard.server.common.data.id.WidgetTypeId;
import org.thingsboard.server.common.data.widget.WidgetType;
@ -32,11 +33,10 @@ import java.util.UUID;
import static org.thingsboard.server.dao.model.ModelConstants.*;
@Table(name = WIDGET_TYPE_COLUMN_FAMILY_NAME)
@EqualsAndHashCode
@ToString
public final class WidgetTypeEntity implements BaseEntity<WidgetType> {
@Transient
private static final long serialVersionUID = 3591054897680176342L;
@PartitionKey(value = 0)
@Column(name = ID_PROPERTY)
private UUID id;
@ -125,45 +125,6 @@ public final class WidgetTypeEntity implements BaseEntity<WidgetType> {
this.descriptor = descriptor;
}
@Override
public int hashCode() {
int result = id != null ? id.hashCode() : 0;
result = 31 * result + (tenantId != null ? tenantId.hashCode() : 0);
result = 31 * result + (bundleAlias != null ? bundleAlias.hashCode() : 0);
result = 31 * result + (alias != null ? alias.hashCode() : 0);
result = 31 * result + (name != null ? name.hashCode() : 0);
result = 31 * result + (descriptor != null ? descriptor.hashCode() : 0);
return result;
}
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
WidgetTypeEntity that = (WidgetTypeEntity) o;
if (id != null ? !id.equals(that.id) : that.id != null) return false;
if (tenantId != null ? !tenantId.equals(that.tenantId) : that.tenantId != null) return false;
if (bundleAlias != null ? !bundleAlias.equals(that.bundleAlias) : that.bundleAlias != null) return false;
if (alias != null ? !alias.equals(that.alias) : that.alias != null) return false;
if (name != null ? !name.equals(that.name) : that.name != null) return false;
return descriptor != null ? descriptor.equals(that.descriptor) : that.descriptor == null;
}
@Override
public String toString() {
final StringBuilder sb = new StringBuilder("WidgetTypeEntity{");
sb.append("id=").append(id);
sb.append(", tenantId=").append(tenantId);
sb.append(", bundleAlias='").append(bundleAlias).append('\'');
sb.append(", alias='").append(alias).append('\'');
sb.append(", name ='").append(name).append('\'');
sb.append(", descriptor=").append(descriptor);
sb.append('}');
return sb.toString();
}
@Override
public WidgetType toData() {
WidgetType widgetType = new WidgetType(new WidgetTypeId(id));

50
dao/src/main/java/org/thingsboard/server/dao/model/nosql/WidgetsBundleEntity.java

@ -20,7 +20,8 @@ import com.datastax.driver.core.utils.UUIDs;
import com.datastax.driver.mapping.annotations.Column;
import com.datastax.driver.mapping.annotations.PartitionKey;
import com.datastax.driver.mapping.annotations.Table;
import com.datastax.driver.mapping.annotations.Transient;
import lombok.EqualsAndHashCode;
import lombok.ToString;
import org.thingsboard.server.common.data.id.TenantId;
import org.thingsboard.server.common.data.id.WidgetsBundleId;
import org.thingsboard.server.common.data.widget.WidgetsBundle;
@ -32,11 +33,10 @@ import java.util.UUID;
import static org.thingsboard.server.dao.model.ModelConstants.*;
@Table(name = WIDGETS_BUNDLE_COLUMN_FAMILY_NAME)
@EqualsAndHashCode
@ToString
public final class WidgetsBundleEntity implements SearchTextEntity<WidgetsBundle> {
@Transient
private static final long serialVersionUID = -8842195928585650849L;
@PartitionKey(value = 0)
@Column(name = ID_PROPERTY)
private UUID id;
@ -119,7 +119,7 @@ public final class WidgetsBundleEntity implements SearchTextEntity<WidgetsBundle
@Override
public String getSearchTextSource() {
return title;
return getTitle();
}
@Override
@ -131,46 +131,6 @@ public final class WidgetsBundleEntity implements SearchTextEntity<WidgetsBundle
return searchText;
}
@Override
public int hashCode() {
int result = id != null ? id.hashCode() : 0;
result = 31 * result + (tenantId != null ? tenantId.hashCode() : 0);
result = 31 * result + (alias != null ? alias.hashCode() : 0);
result = 31 * result + (title != null ? title.hashCode() : 0);
result = 31 * result + (searchText != null ? searchText.hashCode() : 0);
result = 31 * result + (image != null ? image.hashCode() : 0);
return result;
}
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
WidgetsBundleEntity that = (WidgetsBundleEntity) o;
if (id != null ? !id.equals(that.id) : that.id != null) return false;
if (tenantId != null ? !tenantId.equals(that.tenantId) : that.tenantId != null) return false;
if (alias != null ? !alias.equals(that.alias) : that.alias != null) return false;
if (title != null ? !title.equals(that.title) : that.title != null) return false;
if (searchText != null ? !searchText.equals(that.searchText) : that.searchText != null) return false;
return image != null ? image.equals(that.image) : that.image == null;
}
@Override
public String toString() {
final StringBuilder sb = new StringBuilder("WidgetsBundleEntity{");
sb.append("id=").append(id);
sb.append(", tenantId=").append(tenantId);
sb.append(", alias='").append(alias).append('\'');
sb.append(", title='").append(title).append('\'');
sb.append(", searchText='").append(searchText).append('\'');
sb.append(", image=").append(image);
sb.append('}');
return sb.toString();
}
@Override
public WidgetsBundle toData() {
WidgetsBundle widgetsBundle = new WidgetsBundle(new WidgetsBundleId(id));

4
dao/src/main/java/org/thingsboard/server/dao/model/sql/AdminSettingsEntity.java

@ -31,7 +31,6 @@ import org.thingsboard.server.dao.util.mapping.JsonStringType;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.Table;
import javax.persistence.Transient;
import static org.thingsboard.server.dao.model.ModelConstants.*;
@ -42,9 +41,6 @@ import static org.thingsboard.server.dao.model.ModelConstants.*;
@Table(name = ADMIN_SETTINGS_COLUMN_FAMILY_NAME)
public final class AdminSettingsEntity extends BaseSqlEntity<AdminSettings> implements BaseEntity<AdminSettings> {
@Transient
private static final long serialVersionUID = 842759712850362147L;
@Column(name = ADMIN_SETTINGS_KEY_PROPERTY)
private String key;

3
dao/src/main/java/org/thingsboard/server/dao/model/sql/AlarmEntity.java

@ -45,9 +45,6 @@ import static org.thingsboard.server.dao.model.ModelConstants.*;
@Table(name = ALARM_COLUMN_FAMILY_NAME)
public final class AlarmEntity extends BaseSqlEntity<Alarm> implements BaseEntity<Alarm> {
@Transient
private static final long serialVersionUID = -339979717281685984L;
@Column(name = ALARM_TENANT_ID_PROPERTY)
private String tenantId;

Some files were not shown because too many files changed in this diff

Loading…
Cancel
Save